From 2dba08117648b725d61eb67528508f87bfa03287 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 11 Apr 2022 14:25:00 +0200 Subject: [PATCH 01/54] Wear refactor --- app/src/main/AndroidManifest.xml | 72 +- .../info/nightscout/androidaps/MainApp.kt | 6 +- .../androidaps/activities/SurveyActivity.kt | 4 +- .../tidepool/events/EventTidepoolResetData.kt | 2 +- .../general/wear/ActionStringHandler.kt | 745 ++++++++++-------- .../plugins/general/wear/WearFragment.kt | 32 +- .../plugins/general/wear/WearPlugin.kt | 183 ++--- .../general/wear/events/EventWearUpdateGui.kt | 5 + .../SendToDataLayerThread.java | 139 ---- .../wearintegration/WatchUpdaterService.kt | 633 +++++++++++++++ ...Service.java => WatchUpdaterService1.java} | 71 +- .../IobCobCalculatorPlugin.kt | 1 + .../androidaps/plugins/pump/mdi/MDIPlugin.kt | 8 +- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 8 +- app/src/main/res/layout/wear_fragment.xml | 51 +- app/src/main/res/values/wear.xml | 25 + build.gradle | 3 +- .../plugins/pump/combo/ComboPlugin.java | 2 +- core/core_dependencies.gradle | 4 +- .../androidaps/events/EventNetworkChange.kt | 2 - .../androidaps/events/EventNtpStatus.kt | 2 - .../nightscout/androidaps/utils/InstanceId.kt | 11 +- database/build.gradle | 3 + shared/build.gradle | 4 + .../androidaps/annotations/OpenForTesting.kt | 0 .../nightscout/androidaps/events/Event.kt | 2 +- .../events/EventWearToMobileAction.kt | 7 + .../events/EventWearToMobileChange.kt | 7 + .../events/EventWearToMobileConfirm.kt | 7 + .../androidaps/plugins/bus/RxBus.kt | 0 .../nightscout/shared/weardata/ActionData.kt | 33 + .../shared/weardata/WearConstants.kt | 61 ++ .../nightscout/shared/weardata/WearUris.kt | 21 - shared/src/main/res/values/wear_paths.xml | 19 + .../androidaps/annotations/OpenForTesting.kt | 0 wear/build.gradle | 10 +- wear/src/main/AndroidManifest.xml | 145 ++-- wear/src/main/assets/logback.xml | 39 + .../java/info/nightscout/androidaps/Aaps.kt | 6 + .../BaseComplicationProviderService.java | 4 +- .../data/DataLayerListenerService.kt | 552 +++++++++++++ .../androidaps/data/ListenerService.java | 628 --------------- .../androidaps/data/RawDisplayData.java | 2 +- .../androidaps/di/WearActivitiesModule.kt | 23 + .../nightscout/androidaps/di/WearModule.kt | 9 +- .../androidaps/di/WearServicesModule.kt | 5 +- .../interaction/actions/AcceptActivity.java | 61 +- .../actions/BackgroundActionActivity.kt | 26 +- .../interaction/actions/BolusActivity.java | 32 +- .../interaction/actions/CPPActivity.java | 19 +- .../interaction/actions/CarbActivity.java | 9 +- .../interaction/actions/ECarbActivity.java | 11 +- .../interaction/actions/FillActivity.java | 14 +- .../actions/TempTargetActivity.java | 9 +- .../actions/TreatmentActivity.java | 28 +- .../actions/ViewSelectorActivity.java | 19 +- .../interaction/actions/WizardActivity.java | 9 +- .../interaction/menus/FillMenuActivity.java | 8 +- .../interaction/menus/MainMenuActivity.java | 8 +- .../interaction/menus/StatusMenuActivity.java | 10 +- .../androidaps/watchfaces/BIGChart.java | 12 +- .../androidaps/watchfaces/BaseWatchFace.java | 8 +- .../androidaps/watchfaces/NOChart.java | 6 +- wear/src/main/res/values/wear.xml | 39 +- .../data/RawDisplayDataBasalsTest.java | 4 +- 65 files changed, 2305 insertions(+), 1623 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.kt rename app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/{WatchUpdaterService.java => WatchUpdaterService1.java} (90%) create mode 100644 app/src/main/res/values/wear.xml rename {database => shared}/src/debug/java/info/nightscout/androidaps/annotations/OpenForTesting.kt (100%) rename {core => shared}/src/main/java/info/nightscout/androidaps/events/Event.kt (99%) create mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt create mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt create mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt rename {core => shared}/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt (100%) create mode 100644 shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt create mode 100644 shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt delete mode 100644 shared/src/main/java/info/nightscout/shared/weardata/WearUris.kt create mode 100644 shared/src/main/res/values/wear_paths.xml rename {database => shared}/src/release/java/info/nightscout/androidaps/annotations/OpenForTesting.kt (100%) create mode 100644 wear/src/main/assets/logback.xml create mode 100644 wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 84de1769b2..3069f7d830 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -46,6 +46,10 @@ android:supportsRtl="true" android:theme="@style/AppTheme.Launcher" > + + - - - - + + + + + + + + + - - - - - - - - @@ -247,10 +219,6 @@ - - 120) { 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 index d4eb8a30e1..52a2a5ce27 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -2,7 +2,6 @@ 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 @@ -25,8 +24,6 @@ import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTe 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 @@ -38,10 +35,28 @@ 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 info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.ActionData +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_BOLUS +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_CANCEL_CHANGE_REQUEST +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_CHANGE_REQUEST +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_CPP_SET +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_DISMISS_OVERVIEW_NOTIF +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_E_CARBS +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_FILL +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_FILL_PRESET +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_OPEN_CPP +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_QUICK_WIZARD +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_STATUS +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_TDD_STATS +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_TEMPORARY_TARGET +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_WIZARD +import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_WIZARD2 import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.text.DateFormat @@ -96,7 +111,7 @@ class ActionStringHandler @Inject constructor( disposable += rxBus .toObservable(EventWearInitiateAction::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ handleInitiate(it.action) }, fabricPrivacy::logException) + .subscribe({ handleInitiateActionOnPhone(it.action) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventWearConfirmAction::class.java) @@ -109,328 +124,360 @@ class ActionStringHandler @Inject constructor( } @Synchronized - private fun handleInitiate(actionString: String) { + private fun handleInitiateActionOnPhone(actionString: String) { //TODO: i18n - Log.i("ActionStringHandler", "handleInitiate actionString=$actionString") + aapsLogger.debug(LTag.WEAR, "handleInitiateActionOnPhone 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" + if (actionString.startsWith("{")) { + when (val command = ActionData.deserialize(actionString)) { + is ActionData.Bolus -> { + 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 } - - "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" + rMessage += rh.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" + rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" + if (insulinAfterConstraints - command.insulin != 0.0 || carbsAfterConstraints - command.carbs != 0) { + rMessage += "\n" + rh.gs(R.string.constraintapllied) } - - else -> { - sendError(rh.gs(R.string.wear_action_tempt_preset_error, preset)) + rAction += "bolus $insulinAfterConstraints $carbsAfterConstraints" + } + is ActionData.ProfileSwitch -> { + val activeProfileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() + if (activeProfileSwitch is ValueWrapper.Existing) { + rMessage = "Profile:" + "\n\n" + + "Timeshift: " + command.timeShift + "\n" + + "Percentage: " + command.percentage + "%" + rAction = actionString + } else { // read CPP values + sendError("No active profile switch!") 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 + } + } else { + // do the parsing and check constraints + val act = actionString.split("\\s+".toRegex()).toTypedArray() + when (act[0]) { + ACTION_FILL_PRESET -> { ///////////////////////////////////// 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" } - 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 + + ACTION_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 ("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 - } + ACTION_TEMPORARY_TARGET -> { + 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" + } - val wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true) + "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" + } - 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 - } + "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" + } - 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 -> { + 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 + } + } + } + + ACTION_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" + } + } + + ACTION_WIZARD -> { + sendError("Update APP on Watch!") + return + } + + ACTION_WIZARD2 -> { + 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 + } + + ACTION_QUICK_WIZARD -> { + 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() + + } + + ACTION_OPEN_CPP -> { + 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 + } + } + + ACTION_TDD_STATS -> { + 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) + } + } + + ACTION_E_CARBS -> { + 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" + } + + ACTION_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 + } + + ACTION_CANCEL_CHANGE_REQUEST -> { + rAction = "cancelChangeRequest" + wearPlugin.requestNotificationCancel(rAction) + return + } + + else -> { + sendError(rh.gs(R.string.wear_unknown_action_string) + " " + act[0]) + return } - } 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) @@ -594,44 +641,60 @@ class ActionStringHandler @Inject constructor( 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 + when (act[0]) { + ACTION_FILL -> { + 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) } - 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 + + ACTION_TEMPORARY_TARGET -> { + val duration = SafeParse.stringToInt(act[2]) + val low = SafeParse.stringToDouble(act[3]) + val high = SafeParse.stringToDouble(act[4]) + generateTempTarget(duration, low, high) + } + + ACTION_WIZARD2 -> { + if (lastBolusWizard != null) { //use last calculation as confirmed string matches + doBolus(lastBolusWizard!!.calculatedTotalInsulin, lastBolusWizard!!.carbs, null, 0) + lastBolusWizard = null + } + } + + ACTION_BOLUS -> { + val insulin = SafeParse.stringToDouble(act[1]) + val carbs = SafeParse.stringToInt(act[2]) + doBolus(insulin, carbs, null, 0) + } + + ACTION_CPP_SET -> { + val timeshift = SafeParse.stringToInt(act[1]) + val percentage = SafeParse.stringToInt(act[2]) + setCPP(timeshift, percentage) + } + + ACTION_E_CARBS -> { + val carbs = SafeParse.stringToInt(act[1]) + val starttime = SafeParse.stringToLong(act[2]) + val duration = SafeParse.stringToInt(act[3]) + doECarbs(carbs, starttime, duration) + } + + ACTION_DISMISS_OVERVIEW_NOTIF -> { + rxBus.send(EventDismissNotification(SafeParse.stringToInt(act[1]))) + } + + ACTION_CHANGE_REQUEST -> { + loop.acceptChangeRequest() + val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + notificationManager.cancel(Constants.notificationID) } - } 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 } 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..95e21f730d 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,25 @@ import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.databinding.WearFragmentBinding +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.rx.AapsSchedulers +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 private var _binding: WearFragmentBinding? = null + private val disposable = CompositeDisposable() + // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! @@ -27,7 +38,21 @@ 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.openSettings.setOnClickListener { wearPlugin.openSettings() } + } + + 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 +60,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..ead6df3277 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 @@ -6,12 +6,11 @@ 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.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 @@ -19,8 +18,10 @@ import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpda import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject import javax.inject.Singleton @@ -33,100 +34,103 @@ class WearPlugin @Inject constructor( private val sp: SP, private val ctx: Context, private val fabricPrivacy: FabricPrivacy, - private val loop: Loop, private val rxBus: RxBus, private val actionStringHandler: Lazy -) : 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 + disposable += rxBus .toObservable(EventOpenAPSUpdateGui::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) + + disposable += rxBus .toObservable(EventExtendedBolusChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventTempBasalChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventTreatmentChange::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventEffectiveProfileSwitchChanged::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = false, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ sendDataToWatch(status = false, basals = true, bgValue = false) }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventAutosensCalculationFinished::class.java) .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = true) }, fabricPrivacy::logException)) - disposable.add(rxBus + .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = true) }, fabricPrivacy::logException) + disposable += 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) + // possibly new high or low mark + resendDataToWatch() + // status may be formatted differently + sendDataToWatch(status = true, basals = false, bgValue = false) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventLoopUpdateGui::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 + sendDataToWatch(status = true, basals = false, bgValue = false) + }, fabricPrivacy::logException) + disposable += 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 + val status = rh.gs(R.string.bolusrequested, event.amount) + val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUS_PROGRESS) + intent.putExtra("progresspercent", 0) + intent.putExtra("progressstatus", status) + ctx.startService(intent) + }, fabricPrivacy::logException) + 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 + 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_BOLUS_PROGRESS) + intent.putExtra("progresspercent", 100) + intent.putExtra("progressstatus", status) + ctx.startService(intent) + }, 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)) + if (!event.isSMB() || sp.getBoolean("wear_notifySMB", true)) { + val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUS_PROGRESS) + intent.putExtra("progresspercent", event.percent) + intent.putExtra("progressstatus", event.status) + ctx.startService(intent) + } + }, fabricPrivacy::logException) actionStringHandler.get().setup() } @@ -137,51 +141,50 @@ class WearPlugin @Inject constructor( } 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)) - } + // only start service when this plugin is enabled + if (isEnabled()) { + 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 requestNotificationCancel(actionString: String?) { + ctx.startService( + Intent(ctx, WatchUpdaterService::class.java) + .setAction(WatchUpdaterService.ACTION_CANCEL_NOTIFICATION) + .also { + it.putExtra("actionstring", actionString) + }) } 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) + ctx.startService( + Intent(ctx, WatchUpdaterService::class.java) + .setAction(WatchUpdaterService.ACTION_SEND_ACTION_CONFIRMATION_REQUEST) + .also { + it.putExtra("title", title) + it.putExtra("message", message) + it.putExtra("actionstring", actionString) + }) } 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) + ctx.startService( + Intent(ctx, WatchUpdaterService::class.java) + .setAction(WatchUpdaterService.ACTION_SEND_CHANGE_CONFIRMATION_REQUEST) + .also { + it.putExtra("title", title) + it.putExtra("message", message) + it.putExtra("actionstring", actionString) + }) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt new file mode 100644 index 0000000000..4736566059 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.wear.events + +import info.nightscout.androidaps.events.Event + +class EventWearUpdateGui : Event() \ 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.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.kt new file mode 100644 index 0000000000..c3a37d4f61 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.kt @@ -0,0 +1,633 @@ +package info.nightscout.androidaps.plugins.general.wear.wearintegration + +import android.content.Intent +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.Constants +import info.nightscout.androidaps.R +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.convertedToAbsolute +import info.nightscout.androidaps.extensions.toStringShort +import info.nightscout.androidaps.extensions.valueToUnitsString +import info.nightscout.androidaps.interfaces.* +import info.nightscout.androidaps.interfaces.Profile.Companion.fromMgdlToUnits +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.general.wear.events.EventWearUpdateGui +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.to0Decimal +import info.nightscout.androidaps.utils.DecimalFormatter.to1Decimal +import info.nightscout.androidaps.utils.DecimalFormatter.to2Decimal +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.WearConstants +import io.reactivex.rxjava3.disposables.CompositeDisposable +import kotlinx.coroutines.* +import kotlinx.coroutines.tasks.await +import java.util.function.Consumer +import java.util.stream.Collectors +import javax.inject.Inject +import kotlin.math.abs + +class WatchUpdaterService : 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 glucoseStatusProvider: GlucoseStatusProvider + @Inject lateinit var trendCalculator: TrendCalculator + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var rxBus: RxBus + @Inject lateinit var wearConstants: WearConstants + + 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() + + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + aapsLogger.debug(LTag.WEAR, "onCreate") + handler.post { updateTranscriptionCapability() } + } + + 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() + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + aapsLogger.debug(LTag.WEAR, "onStartCommand ${intent?.action}") + if (wearPlugin.isEnabled()) { + handler.post { + when (intent?.action) { + ACTION_RESEND -> resendData() + ACTION_OPEN_SETTINGS -> sendMessage(wearConstants.M_W_OPEN_SETTINGS, byteArrayOf()) + ACTION_SEND_STATUS -> sendStatus() + ACTION_SEND_BASALS -> sendBasals() + ACTION_SEND_BOLUS_PROGRESS -> sendBolusProgress( + intent.getIntExtra("progresspercent", 0), + intent.getStringExtra("progressstatus") + ) + ACTION_SEND_ACTION_CONFIRMATION_REQUEST -> sendActionConfirmationRequest( + intent.getStringExtra("title"), + intent.getStringExtra("message"), + intent.getStringExtra("actionstring") + ) + ACTION_SEND_CHANGE_CONFIRMATION_REQUEST -> sendChangeConfirmationRequest( + intent.getStringExtra("title"), + intent.getStringExtra("message"), + intent.getStringExtra("actionstring") + ) + ACTION_CANCEL_NOTIFICATION -> sendCancelNotificationRequest(intent.getStringExtra("actionstring")) + + null -> {} + + else -> sendData() + } + } + } + return START_STICKY + } + + @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) + aapsLogger.debug(LTag.WEAR, "onMessageReceived: $messageEvent") + + if (wearPlugin.isEnabled()) { + when (messageEvent.path) { + wearConstants.W_M_RESEND_DATA -> resendData() + wearConstants.W_M_CANCEL_BOLUS -> activePlugin.activePump.stopBolusDelivering() + + wearConstants.W_M_INITIATE_ACTION -> + String(messageEvent.data).also { actionstring -> + aapsLogger.debug(LTag.WEAR, "Initiate action: $actionstring") + rxBus.send(EventWearInitiateAction(actionstring)) + } + + wearConstants.W_M_CONFIRM_ACTION -> + String(messageEvent.data).also { actionstring -> + aapsLogger.debug(LTag.WEAR, "Wear confirm action: $actionstring") + rxBus.send(EventWearConfirmAction(actionstring)) + } + + wearConstants.W_M_PONG -> aapsLogger.debug(LTag.WEAR, "Pong response from ${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") + sendMessage(wearConstants.M_W_PING, byteArrayOf()) + } + + // Find a nearby node or pick one arbitrarily + private fun pickBestNodeId(nodes: Set): Node? = + nodes.firstOrNull { it.isNearby } ?: nodes.firstOrNull() + + 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: ByteArray) { + if (wearPlugin.isEnabled()) { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path") + transcriptionNodeId?.also { nodeId -> + messageClient + .sendMessage(nodeId, path, data).apply { + addOnSuccessListener { } + addOnFailureListener { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure") + } + } + } + } + } + + private fun sendData() { + val lastBG = iobCobCalculator.ads.lastBg() ?: return + val glucoseStatus = glucoseStatusProvider.glucoseStatusData + aapsLogger.debug(LTag.WEAR, "Sending bg data to wear") + sendData( + wearConstants.M_W_DATA, + dataMapSingleBG(lastBG, glucoseStatus) + ) + } + + private fun resendData() { + sendPreferences() + sendQuickWizard() + val startTime = System.currentTimeMillis() - (60000 * 60 * 5.5).toLong() + val lastBg = iobCobCalculator.ads.lastBg() ?: return + val graphBgs = repository.compatGetBgReadingsDataFromTime(startTime, true).blockingGet() + val glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(true) + if (graphBgs.isNotEmpty()) { + val entries = dataMapSingleBG(lastBg, glucoseStatus) + val dataMaps = ArrayList(graphBgs.size) + for (bg in graphBgs) { + val dataMap: DataMap = dataMapSingleBG(bg, glucoseStatus) + dataMaps.add(dataMap) + } + entries.putDataMapArrayList("entries", dataMaps) + aapsLogger.debug(LTag.WEAR, "Sending graph bg data to wear") + sendData( + wearConstants.M_W_DATA, + entries + ) + } + sendBasals() + sendStatus() + } + + private fun sendBasals() { + val now = System.currentTimeMillis() + val startTimeWindow = now - (60000 * 60 * 5.5).toLong() + val basals = java.util.ArrayList() + val temps = java.util.ArrayList() + val boluses = java.util.ArrayList() + val predictions = java.util.ArrayList() + 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(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(tempMap(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(tempMap(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(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(tempMap(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(tempMap(tbStart, tbBefore, now, tbAmount, tbAmount)) + temps.add(tempMap(now, tbAmount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)) + } else { + temps.add(tempMap(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(tempMap(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(treatmentMap(timestamp, amount, 0.0, type === Bolus.Type.SMB, isValid)) } + repository.getCarbsDataFromTimeExpanded(startTimeWindow, true).blockingGet() + .forEach(Consumer { (_, _, _, isValid, _, _, timestamp, _, _, amount) -> boluses.add(treatmentMap(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(predictionMap(bg.data.timestamp, bg.data.value, bg.color(null))) + } + aapsLogger.debug(LTag.WEAR, "Sending basal data to wear") + sendData( + wearConstants.M_W_BASAL, + DataMap().apply { + putDataMapArrayList("basals", basals) + putDataMapArrayList("temps", temps) + putDataMapArrayList("boluses", boluses) + putDataMapArrayList("predictions", predictions) + }) + } + + 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) to1Decimal(abs(deltaMGDL)) else to0Decimal(abs(deltaMGDL)) + } else { + if (detailed) to2Decimal(abs(deltaMMOL)) else to1Decimal(abs(deltaMMOL)) + } + return deltaString + } + + private fun dataMapSingleBG(lastBG: GlucoseValue, glucoseStatus: GlucoseStatus?): DataMap { + val units = profileFunction.getUnits() + val lowLine = Profile.toMgdl(defaultValueHelper.determineLowLine(), units) + val highLine = Profile.toMgdl(defaultValueHelper.determineHighLine(), units) + val sgvLevel = if (lastBG.value > highLine) 1L else if (lastBG.value < lowLine) -1L else 0L + val dataMap = DataMap() + dataMap.putString("sgvString", lastBG.valueToUnitsString(units)) + dataMap.putString("glucoseUnits", units.asText) + dataMap.putLong("timestamp", lastBG.timestamp) + if (glucoseStatus == null) { + dataMap.putString("slopeArrow", "") + dataMap.putString("delta", "--") + dataMap.putString("avgDelta", "--") + } else { + dataMap.putString("slopeArrow", trendCalculator.getTrendArrow(lastBG).symbol) + dataMap.putString("delta", deltaString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)) + dataMap.putString("avgDelta", deltaString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units)) + } + dataMap.putLong("sgvLevel", sgvLevel) + dataMap.putDouble("sgvDouble", lastBG.value) + dataMap.putDouble("high", highLine) + dataMap.putDouble("low", lowLine) + return dataMap + } + + private fun tempMap(startTime: Long, startBasal: Double, to: Long, toBasal: Double, amount: Double) = + DataMap().apply { + putLong("starttime", startTime) + putDouble("startBasal", startBasal) + putLong("endtime", to) + putDouble("endbasal", toBasal) + putDouble("amount", amount) + } + + private fun basalMap(startTime: Long, endTime: Long, amount: Double) = + DataMap().apply { + putLong("starttime", startTime) + putLong("endtime", endTime) + putDouble("amount", amount) + } + + private fun treatmentMap(date: Long, bolus: Double, carbs: Double, isSMB: Boolean, isValid: Boolean) = + DataMap().apply { + putLong("date", date) + putDouble("bolus", bolus) + putDouble("carbs", carbs) + putBoolean("isSMB", isSMB) + putBoolean("isValid", isValid) + } + + private fun predictionMap(timestamp: Long, sgv: Double, color: Int) = + DataMap().apply { + putLong("timestamp", timestamp) + putDouble("sgv", sgv) + putInt("color", color) + } + + private fun quickMap(q: QuickWizardEntry) = + DataMap().apply { + putString("guid", q.guid()) + putString("button_text", q.buttonText()) + putInt("carbs", q.carbs()) + putInt("from", q.validFrom()) + putInt("to", q.validTo()) + } + + private fun sendBolusProgress(progressPercent: Int?, status: String?) { + progressPercent ?: return + aapsLogger.debug(LTag.WEAR, "Sending bolus progress: $progressPercent $status") + sendData( + wearConstants.M_W_BOLUS_PROGRESS, + DataMap().apply { + putLong("timestamp", System.currentTimeMillis()) + putString("bolusProgress", "bolusProgress") + putString("progressstatus", status ?: "") + putInt("progresspercent", progressPercent) + }) + } + + private fun sendActionConfirmationRequest(title: String?, message: String?, actionstring: String?) { + title ?: message ?: actionstring ?: return + aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: $actionstring") + sendData( + wearConstants.M_W_ACTION_CONFIRMATION_REQUEST, + DataMap().apply { + putLong("timestamp", System.currentTimeMillis()) + putString("actionConfirmationRequest", "actionConfirmationRequest") + putString("title", title) + putString("message", message) + putString("actionstring", actionstring) + }) + } + + private fun sendChangeConfirmationRequest(title: String?, message: String?, actionstring: String?) { + title ?: message ?: actionstring ?: return + aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: $actionstring") + sendData( + wearConstants.M_W_ACTION_CHANGE_CONFIRMATION_REQUEST, + DataMap().apply { + putLong("timestamp", System.currentTimeMillis()) + putString("changeConfirmationRequest", "changeConfirmationRequest") + putString("title", title) + putString("message", message) + putString("actionstring", actionstring) + }) + } + + private fun sendCancelNotificationRequest(actionstring: String?) { + actionstring ?: return + aapsLogger.debug(LTag.WEAR, "Canceling notification on wear: $actionstring") + sendData( + wearConstants.M_W_ACTION_CANCEL_NOTIFICATION_REQUEST, + DataMap().apply { + putLong("timestamp", System.currentTimeMillis()) + putString("cancelNotificationRequest", "cancelNotificationRequest") + putString("actionstring", actionstring) + }) + } + + private fun sendStatus() { + aapsLogger.debug(LTag.WEAR, "Updating status on wear") + 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 = to2Decimal(bolusIob.iob + basalIob.basaliob) + iobDetail = "(" + to2Decimal(bolusIob.iob) + "|" + to2Decimal(basalIob.basaliob) + ")" + cobString = iobCobCalculator.getCobInfo(false, "WatcherUpdaterService").generateCOBString() + currentBasal = generateBasalString() + + //bgi + val bgi = -(bolusIob.activity + basalIob.activity) * 5 * fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()) + bgiString = "" + (if (bgi >= 0) "+" else "") + 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 + + sendData( + wearConstants.M_W_STATUS, + DataMap().apply { + //unique content + putString("externalStatusString", status) + putString("iobSum", iobSum) + putString("iobDetail", iobDetail) + putBoolean("detailedIob", sp.getBoolean(R.string.key_wear_detailediob, false)) + putString("cob", cobString) + putString("currentBasal", currentBasal) + putString("battery", "" + phoneBattery) + putString("rigBattery", rigBattery) + putLong("openApsStatus", openApsStatus) + putString("bgi", bgiString) + putBoolean("showBgi", sp.getBoolean(R.string.key_wear_showbgi, false)) + putInt("batteryLevel", if (phoneBattery >= 30) 1 else 0) + }) + } + + private fun sendPreferences() { + sendData( + wearConstants.M_W_PREFERENCES, + DataMap().apply { + putLong("timestamp", System.currentTimeMillis()) + putBoolean(rh.gs(R.string.key_wear_control), sp.getBoolean(R.string.key_wear_control, false)) + putBoolean(rh.gs(R.string.key_units_mgdl), profileFunction.getUnits() == GlucoseUnit.MGDL) + putInt(rh.gs(R.string.key_boluswizard_percentage), sp.getInt(R.string.key_boluswizard_percentage, 100)) + putInt(rh.gs(R.string.key_treatmentssafety_maxcarbs), sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48)) + putDouble(rh.gs(R.string.key_treatmentssafety_maxbolus), sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0)) + }) + } + + private fun sendQuickWizard() { + val entities = ArrayList() + for (i in 0 until quickWizard.size()) { + val q = quickWizard[i] + if (q.forDevice(QuickWizardEntry.DEVICE_WATCH)) entities.add(quickMap(q)) + } + sendData( + wearConstants.M_W_QUICK_WIZARD, + DataMap().apply { + putLong("timestamp", System.currentTimeMillis()) + putDataMapArrayList("quick_wizard", entities) + }) + } + + private fun generateStatusString(profile: Profile?, currentBasal: String, iobSum: String, iobDetail: String, bgiString: String): String { + var status = "" + if (profile == null) 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 generateBasalString(): String { + val profile: Profile = profileFunction.getProfile() ?: return "" + return iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())?.toStringShort() ?: to2Decimal(profile.getBasal()) + "U/h" + } + + companion object { + + const val WEAR_CAPABILITY = "androidaps_wear" + + val ACTION_RESEND = WatchUpdaterService::class.java.name + ".Resend" + val ACTION_OPEN_SETTINGS = WatchUpdaterService::class.java.name + ".OpenSettings" + val ACTION_SEND_STATUS = WatchUpdaterService::class.java.name + ".SendStatus" + val ACTION_SEND_BASALS = WatchUpdaterService::class.java.name + ".SendBasals" + val ACTION_SEND_BOLUS_PROGRESS = WatchUpdaterService::class.java.name + ".BolusProgress" + val ACTION_SEND_ACTION_CONFIRMATION_REQUEST = WatchUpdaterService::class.java.name + ".ActionConfirmationRequest" + val ACTION_SEND_CHANGE_CONFIRMATION_REQUEST = WatchUpdaterService::class.java.name + ".ChangeConfirmationRequest" + val ACTION_CANCEL_NOTIFICATION = WatchUpdaterService::class.java.name + ".CancelNotification" + + } +} \ No newline at end of file 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/WatchUpdaterService1.java similarity index 90% rename from app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java rename to app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService1.java index 85d08c142c..95a2419d4a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService1.java @@ -1,73 +1,7 @@ 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 { +/* +public class WatchUpdaterService1 extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { @Inject public GlucoseStatusProvider glucoseStatusProvider; @Inject public AAPSLogger aapsLogger; @Inject public WearPlugin wearPlugin; @@ -841,3 +775,4 @@ public class WatchUpdaterService extends WearableListenerService implements Goog return (lastLoopStatus != enabled); } } +*/ \ No newline at end of file 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..8968308243 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 @@ -29,6 +29,7 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.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/pump/mdi/MDIPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt index c7e9ee9b9b..809ae5472f 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.InstanceId import info.nightscout.androidaps.utils.resources.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/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index f900d942da..03bc0655e4 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.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/res/layout/wear_fragment.xml b/app/src/main/res/layout/wear_fragment.xml index f93423a895..8b271deb9c 100644 --- a/app/src/main/res/layout/wear_fragment.xml +++ b/app/src/main/res/layout/wear_fragment.xml @@ -10,31 +10,38 @@ android:layout_height="wrap_content" android:orientation="vertical"> - + android:gravity="center_vertical|center_horizontal" + android:paddingTop="10dp" + android:paddingBottom="10dp" + android:textAppearance="@style/TextAppearance.AppCompat.Medium" + tools:text="---" /> + android:id="@+id/resend" + style="@style/ButtonSmallFontStyle" + android:layout_width="match_parent" + android:layout_height="match_parent" + android:layout_weight="1" + android:drawableTop="@drawable/ic_refresh" + android:paddingLeft="0dp" + android:paddingRight="0dp" + android:text="@string/resend_all_data" /> + + 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/build.gradle b/build.gradle index e9a584a8a7..4258956182 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' @@ -51,6 +51,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/ComboPlugin.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index db413a0130..0cb2fde701 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 @@ -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/core/core_dependencies.gradle b/core/core_dependencies.gradle index a84479cf9f..d824f0c142 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" 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/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/database/build.gradle b/database/build.gradle index 85fec1fec0..82516d6e33 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -18,6 +18,9 @@ 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" diff --git a/shared/build.gradle b/shared/build.gradle index 12354733b6..764adc301d 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" @@ -29,6 +30,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/EventWearToMobileAction.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt new file mode 100644 index 0000000000..1d5ca463e9 --- /dev/null +++ b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.events + +import info.nightscout.shared.weardata.ActionData +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +class EventWearToMobileAction(val actionData: ActionData) : Event() \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt new file mode 100644 index 0000000000..49ae662e82 --- /dev/null +++ b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.events + +import info.nightscout.shared.weardata.ActionData +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +class EventWearToMobileChange(val actionData: ActionData) : Event() \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt new file mode 100644 index 0000000000..c999248cde --- /dev/null +++ b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.events + +import info.nightscout.shared.weardata.ActionData +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +class EventWearToMobileConfirm(val actionData: ActionData) : Event() \ No newline at end of file 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/shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt b/shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt new file mode 100644 index 0000000000..042edc0d6f --- /dev/null +++ b/shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt @@ -0,0 +1,33 @@ +package info.nightscout.shared.weardata + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +@Serializable +sealed class ActionData { + + fun serialize() = Json.encodeToString(serializer(), this) + + companion object { + + fun deserialize(json: String) = Json.decodeFromString(serializer(), json) + } + // Wear -> Mobile + @Serializable + data class Pong(val timeStamp: Long) : ActionData() + @Serializable + data class Bolus(val insulin: Double, val carbs: Int) : ActionData() + @Serializable + data class ProfileSwitch(val timeShift: Int, val percentage: Int) : ActionData() + + @Serializable + data class OpenProfileSwitch(val timeShift: Int, val percentage: Int) : ActionData() + + // Mobile -> Wear + @Serializable + data class Ping(val timeStamp: Long) : ActionData() + @Serializable + data class ConfirmAction(val title: String, val message: String, val originalCommand: ActionData) : ActionData() + @Serializable + data class ChangeAction(val title: String, val message: String, val originalCommand: ActionData) : ActionData() +} \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt b/shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt new file mode 100644 index 0000000000..7d5558d5f8 --- /dev/null +++ b/shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt @@ -0,0 +1,61 @@ +package info.nightscout.shared.weardata + +import android.content.Context +import info.nightscout.shared.R +import javax.inject.Inject +import javax.inject.Singleton + +@Suppress("PropertyName") +@Singleton +class WearConstants @Inject constructor(private val context: Context) { + + // Paths must be defined in manifest + // mobile -> wear (data) + val M_W_DATA get() = context.getString(R.string.path_watch_data) + val M_W_STATUS get() = context.getString(R.string.path_status) + val M_W_PREFERENCES get() = context.getString(R.string.path_preferences) + val M_W_QUICK_WIZARD get() = context.getString(R.string.path_quick_wizard) + val M_W_BASAL get() = context.getString(R.string.path_basal) + val M_W_BOLUS_PROGRESS get() = context.getString(R.string.path_bolus_progress) + val M_W_ACTION_CONFIRMATION_REQUEST get() = context.getString(R.string.path_action_confirmation) + val M_W_ACTION_CHANGE_CONFIRMATION_REQUEST get() = context.getString(R.string.path_change_confirmation_request) + val M_W_ACTION_CANCEL_NOTIFICATION_REQUEST get() = context.getString(R.string.path_cancel_notification_request) + + // mobile -> wear (message) + val M_W_OPEN_SETTINGS get() = context.getString(R.string.path_open_wear_setting) + val M_W_PING get() = context.getString(R.string.path_ping) + + // wear -> mobile (message) + val W_M_RESEND_DATA get() = context.getString(R.string.path_resend_data_request) + val W_M_CANCEL_BOLUS get() = context.getString(R.string.path_cancel_bolus_on_phone) + val W_M_CONFIRM_ACTION get() = context.getString(R.string.path_confirm_action) + val W_M_INITIATE_ACTION get() = context.getString(R.string.path_initiate_action_on_phone) + val W_M_PONG get() = context.getString(R.string.path_pong) + + companion object { + + // actions for WEAR_INITIATE_ACTION_ON_PHONE + // used by + // DataLayerListenerService::initiateAction + // ActionStringHandler::handleInitiateActionOnPhone + // EventWearInitiateAction + const val ACTION_FILL_PRESET = "fillpreset" + const val ACTION_FILL = "fill" + const val ACTION_BOLUS = "bolus" + const val ACTION_TEMPORARY_TARGET = "temptarget" + const val ACTION_STATUS = "status" + const val ACTION_WIZARD = "wizard" + const val ACTION_WIZARD2 = "wizard2" + const val ACTION_QUICK_WIZARD = "quick_wizard" + const val ACTION_OPEN_CPP = "opencpp" + const val ACTION_CPP_SET = "cppset" + const val ACTION_TDD_STATS = "tddstats" + const val ACTION_E_CARBS = "ecarbs" + const val ACTION_CHANGE_REQUEST = "changeRequest" + const val ACTION_CANCEL_CHANGE_REQUEST = "cancelChangeRequest" + const val ACTION_DISMISS_OVERVIEW_NOTIF = "dismissoverviewnotification" + + //data keys + const val KEY_ACTION_DATA = "actionData" + } +} 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/wear_paths.xml b/shared/src/main/res/values/wear_paths.xml new file mode 100644 index 0000000000..1bf7203905 --- /dev/null +++ b/shared/src/main/res/values/wear_paths.xml @@ -0,0 +1,19 @@ + + + /ping + /pong + /openwearsettings + /nightscout_watch_data_resend + /nightscout_watch_initiateactionstring + /nightscout_watch_cancel_bolus + /nightscout_watch_confirmactionstring + /nightscout_watch_data + /sendstatustowear + /sendpreferencestowear + /send_quick_wizard + /nightscout_watch_basal + /nightscout_watch_bolusprogress + /nightscout_watch_actionconfirmationrequest + /nightscout_watch_changeconfirmationrequest + /nightscout_watch_cancelnotificationrequest + \ 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..93d9e3281b 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 @@ -112,8 +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 "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 "androidx.core:core-ktx:$core_version" implementation "androidx.wear.tiles:tiles:1.0.1" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 0bd323b107..95ff23dc3f 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -17,6 +17,11 @@ android:icon="@drawable/ic_icon" android:label="@string/app_name" android:theme="@android:style/Theme.DeviceDefault"> + + + @@ -25,7 +30,8 @@ android:name=".watchfaces.BIGChart" android:allowEmbedded="true" android:label="@string/label_xdrip_big_chart" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -46,7 +52,8 @@ android:name=".watchfaces.NOChart" android:allowEmbedded="true" android:label="@string/label_xdrip_no_chart" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -67,7 +74,8 @@ android:name=".watchfaces.Home" android:allowEmbedded="true" android:label="@string/label_xdrip" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -91,7 +99,8 @@ android:name=".watchfaces.Home2" android:allowEmbedded="true" android:label="@string/label_xdrip_v2" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -115,7 +124,8 @@ android:name=".watchfaces.Cockpit" android:allowEmbedded="true" android:label="@string/label_xdrip_cockpit" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -139,7 +149,8 @@ android:name=".watchfaces.Steampunk" android:allowEmbedded="true" android:label="@string/label_xdrip_steampunk" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -163,7 +174,8 @@ android:name=".watchfaces.LargeHome" android:allowEmbedded="true" android:label="@string/label_xdrip_large" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -186,7 +198,8 @@ android:name=".watchfaces.CircleWatchface" android:allowEmbedded="true" android:label="@string/label_xdrip_circle" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -207,7 +220,8 @@ android:name=".watchfaces.DigitalStyle" android:allowEmbedded="true" android:label="@string/label_digitalstyle" - android:permission="android.permission.BIND_WALLPAPER"> + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -227,68 +241,73 @@ - + - - + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - @@ -466,7 +485,7 @@ @@ -483,7 +502,7 @@ @@ -500,7 +519,7 @@ @@ -623,7 +642,7 @@ - + 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..565ddf002e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/Aaps.kt +++ b/wear/src/main/java/info/nightscout/androidaps/Aaps.kt @@ -8,11 +8,17 @@ import androidx.preference.PreferenceManager import dagger.android.AndroidInjector import dagger.android.DaggerApplication import info.nightscout.androidaps.di.DaggerWearComponent +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 + override fun onCreate() { super.onCreate() + aapsLogger.debug(LTag.WEAR, "onCreate") PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this) } diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java index 8c5a3d2c47..7d65be3080 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java @@ -22,7 +22,7 @@ import javax.inject.Inject; import dagger.android.AndroidInjection; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.data.RawDisplayData; import info.nightscout.androidaps.interaction.utils.Constants; import info.nightscout.androidaps.interaction.utils.DisplayFormat; @@ -205,7 +205,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid localBroadcastManager = LocalBroadcastManager.getInstance(this); localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - ListenerService.requestData(this); + DataLayerListenerService.Companion.requestData(this); checkIfUpdateNeeded(); } diff --git a/wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt b/wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt new file mode 100644 index 0000000000..7cf6bb7840 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt @@ -0,0 +1,552 @@ +/* + * Copyright 2021 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +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.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.HandlerThread +import android.os.SystemClock +import android.util.Base64 +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.tasks.Tasks +import com.google.android.gms.wearable.* +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobileAction +import info.nightscout.androidaps.events.EventWearToMobileChange +import info.nightscout.androidaps.events.EventWearToMobileConfirm +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.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.SafeParse.stringToInt +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.ActionData +import info.nightscout.shared.weardata.WearConstants +import info.nightscout.shared.weardata.WearConstants.Companion.KEY_ACTION_DATA +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 DataLayerListenerService : 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 + @Inject lateinit var wearConstants: WearConstants + + 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() + + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + handler.post { updateTranscriptionCapability() } + disposable += rxBus + .toObservable(EventWearToMobileAction::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { sendMessage(wearConstants.W_M_INITIATE_ACTION, it.actionData.serialize().toByteArray()) } + disposable += rxBus + .toObservable(EventWearToMobileConfirm::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + NotificationManagerCompat.from(this).cancel(CONFIRM_NOTIF_ID) + sendMessage(wearConstants.W_M_CONFIRM_ACTION, it.actionData.serialize().toByteArray()) + } + disposable += rxBus + .toObservable(EventWearToMobileChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + NotificationManagerCompat.from(this).cancel(CHANGE_NOTIF_ID) + sendMessage(wearConstants.W_M_CONFIRM_ACTION, it.actionData.serialize().toByteArray()) + } + } + + 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 { + when (path) { + wearConstants.M_W_BOLUS_PROGRESS -> { + val progress = DataMapItem.fromDataItem(event.dataItem).dataMap.getInt("progresspercent", 0) + val status = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("progressstatus", "") + showBolusProgress(progress, status) + } + // remove when finished -> converted to message + wearConstants.M_W_ACTION_CONFIRMATION_REQUEST -> { + val title = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("title") ?: return@forEach + val message = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("message") ?: return@forEach + val actionstring = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("actionstring") ?: return@forEach + if ("opencpp" == title && actionstring.startsWith("opencpp")) { + val act = actionstring.split("\\s+").toTypedArray() + startActivity(Intent(this@DataLayerListenerService, CPPActivity::class.java).also { intent -> + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + intent.putExtras(Bundle().also { + it.putInt("percentage", stringToInt(act[1])) + it.putInt("timeshift", stringToInt(act[2])) + }) + }) + } else { + showConfirmationDialog(title, message, actionstring) + } + } + + wearConstants.M_W_STATUS -> { + val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap + val messageIntent = Intent() + messageIntent.action = Intent.ACTION_SEND + messageIntent.putExtra("status", dataMap.toBundle()) + persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMap) + LocalBroadcastManager.getInstance(this@DataLayerListenerService).sendBroadcast(messageIntent) + } + + wearConstants.M_W_BASAL -> { + val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap + val messageIntent = Intent() + messageIntent.action = Intent.ACTION_SEND + messageIntent.putExtra("basals", dataMap.toBundle()) + persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMap) + LocalBroadcastManager.getInstance(this@DataLayerListenerService).sendBroadcast(messageIntent) + } + + wearConstants.M_W_PREFERENCES -> { + val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap + val keyControl = getString(R.string.key_wear_control) + if (dataMap.containsKey(keyControl)) { + val previousWearControl = sp.getBoolean(keyControl, false) + val wearControl: Boolean = dataMap.getBoolean(keyControl, false) + sp.putBoolean(keyControl, wearControl) + if (wearControl != previousWearControl) { + updateTiles() + } + } + val keyPercentage = getString(R.string.key_boluswizard_percentage) + if (dataMap.containsKey(keyPercentage)) { + val wpercentage: Int = dataMap.getInt(keyPercentage, 100) + sp.putInt(keyPercentage, wpercentage) + } + val keyUnits = getString(R.string.key_units_mgdl) + if (dataMap.containsKey(keyUnits)) { + val mgdl: Boolean = dataMap.getBoolean(keyUnits, true) + sp.putBoolean(keyUnits, mgdl) + } + val keyMaxCarbs = getString(R.string.key_treatmentssafety_maxcarbs) + if (dataMap.containsKey(keyMaxCarbs)) { + val maxCarbs: Int = dataMap.getInt(keyMaxCarbs, 48) + sp.putInt(keyMaxCarbs, maxCarbs) + } + val keyMaxBolus = getString(R.string.key_treatmentssafety_maxbolus) + if (dataMap.containsKey(keyMaxBolus)) { + sp.putDouble(keyMaxBolus, dataMap.getDouble(keyMaxBolus, 3.0)) + } + } + + wearConstants.M_W_QUICK_WIZARD -> { + val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap + aapsLogger.info(LTag.WEAR, "onDataChanged: QUICK_WIZARD_PATH$dataMap") + dataMap.remove("timestamp") + val key = getString(R.string.key_quick_wizard_data_map) + val dataString = Base64.encodeToString(dataMap.toByteArray(), Base64.DEFAULT) + if (dataString != sp.getString(key, "")) { + sp.putString(key, dataString) + // Todo maybe add debounce function, due to 20 seconds update limit? + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + TileService.getUpdater(this@DataLayerListenerService).requestUpdate(QuickWizardTileService::class.java) + } + aapsLogger.info(LTag.WEAR, "onDataChanged: updated QUICK_WIZARD") + } else { + aapsLogger.info(LTag.WEAR, "onDataChanged: ignore update") + } + } + + wearConstants.M_W_ACTION_CHANGE_CONFIRMATION_REQUEST -> { + val title = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("title") ?: return@forEach + val message = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("message") ?: return@forEach + val actionstring = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("actionstring") ?: return@forEach + notifyChangeRequest(title, message, actionstring) + } + + wearConstants.M_W_ACTION_CANCEL_NOTIFICATION_REQUEST -> { + //val actionstring = DataMapItem.fromDataItem(event.getDataItem()).dataMap.getString("actionstring") ?: return@forEach + cancelNotificationRequest() + } + + wearConstants.M_W_DATA -> { + val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap + val messageIntent = Intent() + messageIntent.action = Intent.ACTION_SEND + messageIntent.putExtra("data", dataMap.toBundle()) + persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMap) + LocalBroadcastManager.getInstance(this@DataLayerListenerService).sendBroadcast(messageIntent) + } + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, "onDataChanged failed", exception) + } + } + } + super.onDataChanged(dataEvents) + } + + override fun onMessageReceived(messageEvent: MessageEvent) { + super.onMessageReceived(messageEvent) + aapsLogger.debug(LTag.WEAR, "onMessageReceived: $messageEvent") + + when (messageEvent.path) { + wearConstants.M_W_PING -> sendMessage(wearConstants.W_M_PONG, byteArrayOf()) + wearConstants.M_W_OPEN_SETTINGS -> startActivity(Intent(this@DataLayerListenerService, AAPSPreferences::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + + wearConstants.M_W_ACTION_CONFIRMATION_REQUEST -> { + val command = ActionData.deserialize(String(messageEvent.data)) as ActionData.ConfirmAction + if (command.originalCommand is ActionData.OpenProfileSwitch) { + val originalCommand = command.originalCommand as ActionData.OpenProfileSwitch + startActivity(Intent(this, CPPActivity::class.java).also { intent -> + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + intent.putExtras(Bundle().also { + it.putInt("percentage", originalCommand.percentage) + it.putInt("timeshift", originalCommand.timeShift) + }) + }) + } else { + startActivity( + Intent(this, AcceptActivity::class.java).also { intent -> + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + intent.putExtras( + Bundle().also { bundle -> + bundle.putString("title", command.title) + bundle.putString("message", command.message) + bundle.putString(KEY_ACTION_DATA, command.originalCommand.serialize()) + } + ) + }) + } + } + } + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_RESEND -> sendMessage(wearConstants.W_M_RESEND_DATA, byteArrayOf()) + + ACTION_CANCEL_BOLUS -> { + //dismiss notification + val notificationManager = NotificationManagerCompat.from(this) + notificationManager.cancel(BOLUS_PROGRESS_NOTIF_ID) + //send cancel-request to phone. + sendMessage(wearConstants.W_M_CANCEL_BOLUS, byteArrayOf()) + } + + ACTION_CONFIRMATION -> { + //dismiss notification + val notificationManager = NotificationManagerCompat.from(this) + notificationManager.cancel(CONFIRM_NOTIF_ID) + intent.getStringExtra("actionstring")?.let { actionString -> + sendMessage(wearConstants.W_M_CONFIRM_ACTION, actionString.toByteArray()) + } + } + + ACTION_CONFIRM_CHANGE -> { + //dismiss notification + val notificationManager = NotificationManagerCompat.from(this) + notificationManager.cancel(CHANGE_NOTIF_ID) + intent.getStringExtra("actionstring")?.let { actionString -> + sendMessage(wearConstants.W_M_CONFIRM_ACTION, actionString.toByteArray()) + } + } + + ACTION_INITIATE_ACTION -> + if (intent.hasExtra("actionstring")) + intent.getStringExtra("actionstring")?.let { actionString -> + sendMessage(wearConstants.W_M_INITIATE_ACTION, actionString.toByteArray()) + } + else if (intent.hasExtra(KEY_ACTION_DATA)) + intent.getStringExtra(KEY_ACTION_DATA)?.let { actionData -> + sendMessage(wearConstants.W_M_INITIATE_ACTION, actionData.toByteArray()) + } + } + 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 + ")" }}") + transcriptionNodeId = pickBestNodeId(capabilityInfo.nodes) + 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 + + 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: 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") + } + } + } + } + + private fun updateTiles() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + TileService.getUpdater(this) + .requestUpdate(ActionsTileService::class.java) + TileService.getUpdater(this) + .requestUpdate(TempTargetTileService::class.java) + TileService.getUpdater(this) + .requestUpdate(QuickWizardTileService::class.java) + } + } + + private fun notifyChangeRequest(title: String, message: String, actionstring: String) { + // 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(AAPS_NOTIFY_CHANNEL_ID_OPENLOOP, 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 + val notificationManager = getSystemService(NotificationManager::class.java) + notificationManager.createNotificationChannel(channel) + } + var builder = NotificationCompat.Builder(this, AAPS_NOTIFY_CHANNEL_ID_OPENLOOP) + builder = builder.setSmallIcon(R.drawable.notif_icon) + .setContentTitle(title) + .setContentText(message) + .setPriority(Notification.PRIORITY_HIGH) + .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000)) + + // Creates an explicit intent for an Activity in your app + val intent = Intent(this, AcceptActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val params = Bundle() + params.putString("title", title) + params.putString("message", message) + params.putString("actionstring", actionstring) + intent.putExtras(params) + val resultPendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + builder = builder.setContentIntent(resultPendingIntent) + val mNotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager + // mId allows you to update the notification later on. + mNotificationManager.notify(CHANGE_NOTIF_ID, builder.build()) + } + + private fun cancelNotificationRequest() { + (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).cancel(CHANGE_NOTIF_ID) + } + + private fun showBolusProgress(progressPercent: Int, progresStatus: String) { + 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(this, DataLayerListenerService::class.java) + cancelIntent.action = ACTION_CANCEL_BOLUS + val cancelPendingIntent = PendingIntent.getService(this, 0, cancelIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val notificationBuilder: NotificationCompat.Builder = + NotificationCompat.Builder(this, if (vibrate) AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS else 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) + val 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 fun createBolusProgressChannels() { + createNotificationChannel( + longArrayOf(0, 50, 1000), + AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS, + getString(R.string.bolus_progress_channel_name), + getString(R.string.bolus_progress_channel_description) + ) + createNotificationChannel( + longArrayOf(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 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 + val notificationManager = getSystemService(NotificationManager::class.java) + notificationManager.createNotificationChannel(channel) + } + + private fun showConfirmationDialog(title: String, message: String, actionstring: String) { + val intent = Intent(this, AcceptActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val params = Bundle() + params.putString("title", title) + params.putString("message", message) + params.putString("actionstring", actionstring) + intent.putExtras(params) + startActivity(intent) + } + + @Suppress("SameParameterValue") + private fun scheduleDismissBolusProgress(seconds: Int) { + Thread { + SystemClock.sleep(seconds * 1000L) + NotificationManagerCompat.from(this@DataLayerListenerService) + .cancel(BOLUS_PROGRESS_NOTIF_ID) + }.start() + } + + companion object { + + const val PHONE_CAPABILITY = "androidaps_mobile" + + const val ACTION_RESEND = "com.dexdrip.stephenblack.nightwatch.RESEND_DATA" + const val ACTION_CANCEL_BOLUS = "com.dexdrip.stephenblack.nightwatch.CANCELBOLUS" + const val ACTION_CONFIRMATION = "com.dexdrip.stephenblack.nightwatch.CONFIRMACTION" + const val ACTION_CONFIRM_CHANGE = "com.dexdrip.stephenblack.nightwatch.CONFIRMCHANGE" + val ACTION_INITIATE_ACTION = DataLayerListenerService::class.java.name + ".INITIATE_ACTION" + + 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_OPENLOOP = "AndroidAPS-OpenLoop" + const val AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS = "bolus progress vibration" + const val AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT = "bolus progress silent" + + fun initiateAction(context: Context, actionstring: String) { + context.startService( + Intent(context, DataLayerListenerService::class.java).also { + it.putExtra("actionstring", actionstring) + it.action = ACTION_INITIATE_ACTION + }) + } + + fun requestData(context: Context) { + context.startService( + Intent(context, DataLayerListenerService::class.java).also { it.action = ACTION_RESEND }) + } + + fun confirmAction(context: Context, actionstring: String) { + context.startService( + Intent(context, DataLayerListenerService::class.java).also { + it.putExtra("actionstring", actionstring) + if (actionstring == "changeRequest") it.action = ACTION_CONFIRM_CHANGE + else it.action = ACTION_CONFIRMATION + }) + } + } +} 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 index ecadbd7d4f..a13c347a10 100644 --- a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java +++ b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java @@ -174,7 +174,7 @@ public class RawDisplayData { wearUtil.releaseWakeLock(wl); } - public DataMap updateBasalsFromMessage(Intent intent, PowerManager.WakeLock wakeLock) { + public DataMap updateBasalsFromMessage(Intent intent) { Bundle bundle = intent.getBundleExtra("basals"); if (bundle != null) { DataMap dataMap = wearUtil.bundleToDataMap(bundle); 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..253935147e --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.interaction.actions.* + +@Module +@Suppress("unused") +abstract class WearActivitiesModule { + + @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 contributesCPPActivity(): CPPActivity + @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 +} \ 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..de47454131 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt @@ -3,14 +3,15 @@ package info.nightscout.androidaps.di import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.complications.* -import info.nightscout.androidaps.data.ListenerService +import info.nightscout.androidaps.data.DataLayerListenerService +import info.nightscout.androidaps.interaction.actions.BackgroundActionActivity import info.nightscout.androidaps.watchfaces.* @Module @Suppress("unused") abstract class WearServicesModule { - @ContributesAndroidInjector abstract fun contributesListenerService(): ListenerService + @ContributesAndroidInjector abstract fun contributesDataLayerListenerService(): DataLayerListenerService @ContributesAndroidInjector abstract fun contributesBaseComplicationProviderService(): BaseComplicationProviderService @ContributesAndroidInjector abstract fun contributesBrCobIobComplication(): BrCobIobComplication 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 index 1b3c1ba0f2..413bf0ee26 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.interaction.actions; +import static info.nightscout.shared.weardata.WearConstants.KEY_ACTION_DATA; + import android.content.Context; import android.content.Intent; import android.os.Bundle; @@ -19,7 +21,10 @@ import androidx.core.view.MotionEventCompat; import androidx.core.view.ViewConfigurationCompat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobileChange; +import info.nightscout.androidaps.events.EventWearToMobileConfirm; +import info.nightscout.shared.weardata.ActionData; /** * Created by adrian on 09/02/17. @@ -29,6 +34,7 @@ public class AcceptActivity extends ViewSelectorActivity { String message = ""; String actionstring = ""; + String actionKey = ""; private DismissThread dismissThread; @Override @@ -41,8 +47,9 @@ public class AcceptActivity extends ViewSelectorActivity { Bundle extras = getIntent().getExtras(); message = extras.getString("message", ""); actionstring = extras.getString("actionstring", ""); + actionKey = extras.getString(KEY_ACTION_DATA, ""); - if ("".equals(message) || "".equals(actionstring)) { + if (message.isEmpty() || (actionstring.isEmpty() && actionKey.isEmpty())) { finish(); return; } @@ -60,6 +67,7 @@ public class AcceptActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -74,48 +82,53 @@ public class AcceptActivity extends ViewSelectorActivity { @Override public Object instantiateItem(ViewGroup container, int row, int col) { + final View view; if (col == 0) { - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_confirm_text, container, false); + 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)); + scrollView.setOnGenericMotionListener((v, 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; + 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); + 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 (!actionstring.isEmpty()) + DataLayerListenerService.Companion.confirmAction(AcceptActivity.this, actionstring); + else { + ActionData actionData = ActionData.Companion.deserialize(actionKey); + if (actionData instanceof ActionData.ConfirmAction) + rxBus.send(new EventWearToMobileConfirm(actionData)); + if (actionData instanceof ActionData.ChangeAction) + rxBus.send(new EventWearToMobileChange(actionData)); + } finishAffinity(); }); container.addView(view); - return 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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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..4d0ecbc0a9 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,26 @@ 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.data.DataLayerListenerService +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import javax.inject.Inject -const val TAG = "QuickWizard" +class BackgroundActionActivity : DaggerActivity() { -class BackgroundActionActivity : Activity() { + @Inject lateinit var aapsLogger: AAPSLogger 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("actionString")?.let { actionString -> + aapsLogger.info(LTag.WEAR, "QuickWizardActivity.onCreate: actionString=$actionString") + DataLayerListenerService.initiateAction(this, actionString) + intent.extras?.getString("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 index 0814ac6a52..55109a352f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java @@ -1,8 +1,6 @@ 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; @@ -12,21 +10,21 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.events.EventWearToMobileAction; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.ActionData; public class BolusActivity extends ViewSelectorActivity { PlusMinusEditText editInsulin; - float maxBolus; + double 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); + maxBolus = sp.getDouble(getString(R.string.key_treatmentssafety_maxbolus), 3.0); } @Override @@ -35,6 +33,7 @@ public class BolusActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -49,30 +48,29 @@ public class BolusActivity extends ViewSelectorActivity { @Override public Object instantiateItem(ViewGroup container, int row, int col) { + final View view; if (col == 0) { - final View view = getInflatedPlusMinusView(container); + 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); + editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 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); + view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); + final ImageView confirmButton = view.findViewById(R.id.confirmbutton); + confirmButton.setOnClickListener((View v) -> { + ActionData.Bolus bolus = new ActionData.Bolus(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), 0); + rxBus.send(new EventWearToMobileAction(bolus)); + showToast(BolusActivity.this, R.string.action_bolus_confirmation); finishAffinity(); }); container.addView(view); - return view; } + return view; } @Override 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 index d5c488f185..dde240c015 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java @@ -10,9 +10,11 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobileAction; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.ActionData; /** * Created by adrian on 09/02/17. @@ -88,15 +90,14 @@ public class CPPActivity extends ViewSelectorActivity { } 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? + final ImageView confirmButton = view.findViewById(R.id.confirmbutton); + confirmButton.setOnClickListener((View v) -> { + //check if it can happen that the fragment 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); + ActionData.ProfileSwitch ps = + new ActionData.ProfileSwitch(SafeParse.stringToInt(editTimeshift.editText.getText().toString()), SafeParse.stringToInt(editPercentage.editText.getText().toString())); + rxBus.send(new EventWearToMobileAction(ps)); + showToast(CPPActivity.this, R.string.action_cpp_confirmation); finishAffinity(); }); container.addView(view); 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 index f5a6b95d08..d9c9298236 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java @@ -1,8 +1,6 @@ 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; @@ -12,7 +10,7 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; @@ -25,7 +23,6 @@ public class CarbActivity extends ViewSelectorActivity { 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); } @@ -66,8 +63,8 @@ public class CarbActivity extends ViewSelectorActivity { 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); + DataLayerListenerService.Companion.initiateAction(CarbActivity.this, actionstring); + showToast(CarbActivity.this, R.string.action_ecarb_confirmation); finishAffinity(); }); 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 index 61d0882d70..cc36635961 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java @@ -1,8 +1,6 @@ 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; @@ -12,7 +10,7 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; @@ -31,7 +29,6 @@ public class ECarbActivity extends ViewSelectorActivity { 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); } @@ -92,14 +89,14 @@ public class ECarbActivity extends ViewSelectorActivity { 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? + //check if it can happen that the fragment 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); + DataLayerListenerService.Companion.initiateAction(ECarbActivity.this, actionstring); + showToast(ECarbActivity.this, R.string.action_ecarb_confirmation); finishAffinity(); }); 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 index b76829182e..28493146ca 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java @@ -10,7 +10,7 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; @@ -64,13 +64,13 @@ public class FillActivity extends ViewSelectorActivity { 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) + //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(); + String actionstring = "fill " + SafeParse.stringToDouble(editInsulin.editText.getText().toString()); + DataLayerListenerService.Companion.initiateAction(FillActivity.this, actionstring); + showToast(FillActivity.this, R.string.action_fill_confirmation); + finishAffinity(); }); container.addView(view); return view; 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 index df2db8fafa..4bab152cb5 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java @@ -1,8 +1,6 @@ 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; @@ -12,7 +10,7 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; @@ -34,7 +32,6 @@ public class TempTargetActivity extends ViewSelectorActivity { setAdapter(new MyGridViewPagerAdapter()); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); isMGDL = sp.getBoolean("units_mgdl", true); isSingleTarget = sp.getBoolean("singletarget", true); } @@ -126,8 +123,8 @@ public class TempTargetActivity extends ViewSelectorActivity { + " " + 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); + DataLayerListenerService.Companion.initiateAction(TempTargetActivity.this, actionstring); + showToast(TempTargetActivity.this, R.string.action_tempt_confirmation); finishAffinity(); }); container.addView(view); 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 index 7929dc2299..2b0f0dd4a6 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java @@ -1,8 +1,6 @@ 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; @@ -12,9 +10,11 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobileAction; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.ActionData; /** * Created by adrian on 09/02/17. @@ -25,15 +25,14 @@ public class TreatmentActivity extends ViewSelectorActivity { PlusMinusEditText editCarbs; PlusMinusEditText editInsulin; int maxCarbs; - float maxBolus; + double 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); + maxBolus = sp.getDouble(getString(R.string.key_treatmentssafety_maxbolus), 3.0); } @Override @@ -63,7 +62,7 @@ public class TreatmentActivity extends ViewSelectorActivity { 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); + 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(); @@ -74,7 +73,7 @@ public class TreatmentActivity extends ViewSelectorActivity { 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); + 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; @@ -83,13 +82,12 @@ public class TreatmentActivity extends ViewSelectorActivity { 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(); + //check if it can happen that the fragment is never created that hold data? + // (you have to swipe past them anyways - but still) + ActionData.Bolus bolus = new ActionData.Bolus(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), SafeParse.stringToInt(editCarbs.editText.getText().toString())); + rxBus.send(new EventWearToMobileAction(bolus)); + showToast(TreatmentActivity.this, R.string.action_treatment_confirmation); + finishAffinity(); }); container.addView(view); return view; 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 index 068cca59f7..a5aaa18768 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java @@ -1,10 +1,7 @@ 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; @@ -16,13 +13,21 @@ import android.widget.Toast; import androidx.wear.widget.CurvedTextView; +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 13/02/17. */ -public class ViewSelectorActivity extends Activity { +public class ViewSelectorActivity extends DaggerActivity { + + @Inject SP sp; + @Inject RxBus rxBus; private GridViewPager pager; @@ -81,9 +86,7 @@ public class ViewSelectorActivity extends Activity { } View getInflatedPlusMinusView(ViewGroup container) { - SharedPreferences sharedPrefs = PreferenceManager - .getDefaultSharedPreferences(this); - int design = Integer.parseInt(sharedPrefs.getString("input_design", "1")); + int design = sp.getInt("input_design", 1); if (design == 2) { return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_quickrighty, container, false); @@ -102,7 +105,7 @@ public class ViewSelectorActivity extends Activity { textView.setText(labelText); } - void confirmAction(Context context, int text) { + void showToast(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/WizardActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java index 0d7be17da4..ac2ecb30fe 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java @@ -1,8 +1,6 @@ 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; @@ -12,7 +10,7 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; @@ -33,7 +31,6 @@ public class WizardActivity extends ViewSelectorActivity { 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); @@ -93,8 +90,8 @@ public class WizardActivity extends ViewSelectorActivity { String actionstring = "wizard2 " + SafeParse.stringToInt(editCarbs.editText.getText().toString()) + " " + percentage; - ListenerService.initiateAction(WizardActivity.this, actionstring); - confirmAction(WizardActivity.this, R.string.action_wizard_confirmation); + DataLayerListenerService.Companion.initiateAction(WizardActivity.this, actionstring); + showToast(WizardActivity.this, R.string.action_wizard_confirmation); finishAffinity(); }); container.addView(view); 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 index 92f557268f..f11c887130 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java @@ -7,7 +7,7 @@ import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.actions.FillActivity; import info.nightscout.androidaps.interaction.utils.MenuListActivity; @@ -37,11 +37,11 @@ public class FillMenuActivity extends MenuListActivity { @Override protected void doAction(String action) { if (getString(R.string.action_preset_1).equals(action)) { - ListenerService.initiateAction(this, "fillpreset 1"); + DataLayerListenerService.Companion.initiateAction(this, "fillpreset 1"); } else if (getString(R.string.action_preset_2).equals(action)) { - ListenerService.initiateAction(this, "fillpreset 2"); + DataLayerListenerService.Companion.initiateAction(this, "fillpreset 2"); } else if (getString(R.string.action_preset_3).equals(action)) { - ListenerService.initiateAction(this, "fillpreset 3"); + DataLayerListenerService.Companion.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); 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 index fcc21cee0d..92f82f5920 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.java @@ -9,11 +9,11 @@ import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; 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.TreatmentActivity; import info.nightscout.androidaps.interaction.actions.WizardActivity; import info.nightscout.androidaps.interaction.utils.MenuListActivity; @@ -30,7 +30,7 @@ public class MainMenuActivity extends MenuListActivity { sp = PreferenceManager.getDefaultSharedPreferences(this); setTitle(R.string.label_actions_activity); super.onCreate(savedInstanceState); - ListenerService.requestData(this); + DataLayerListenerService.Companion.requestData(this); } @Override @@ -68,7 +68,7 @@ public class MainMenuActivity extends MenuListActivity { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); } else if (getString(R.string.menu_resync).equals(action)) { - ListenerService.requestData(this); + DataLayerListenerService.Companion.requestData(this); } else if (getString(R.string.menu_tempt).equals(action)) { intent = new Intent(this, TempTargetActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 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 index 8861e45ed6..6f9c5586c8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.java @@ -6,7 +6,7 @@ import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.interaction.utils.MenuListActivity; /** @@ -35,13 +35,13 @@ public class StatusMenuActivity extends MenuListActivity { @Override protected void doAction(String action) { if (getString(R.string.status_pump).equals(action)) { - ListenerService.initiateAction(this, "status pump"); + DataLayerListenerService.Companion.initiateAction(this, "status pump"); } else if (getString(R.string.status_loop).equals(action)) { - ListenerService.initiateAction(this, "status loop"); + DataLayerListenerService.Companion.initiateAction(this, "status loop"); } else if (getString(R.string.status_cpp).equals(action)) { - ListenerService.initiateAction(this, "opencpp"); + DataLayerListenerService.Companion.initiateAction(this, "opencpp"); } else if (getString(R.string.status_tdd).equals(action)) { - ListenerService.initiateAction(this, "tddstats"); + DataLayerListenerService.Companion.initiateAction(this, "tddstats"); } } } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java index 73fcac445a..618dc68998 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java @@ -44,7 +44,7 @@ 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.DataLayerListenerService; import info.nightscout.androidaps.data.TempWatchData; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; import lecho.lib.hellocharts.view.LineChartView; @@ -158,7 +158,7 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre mRelativeLayout.getMeasuredHeight()); } }); - ListenerService.requestData(this); + DataLayerListenerService.Companion.requestData(this); wakeLock.acquire(50); } @@ -634,9 +634,9 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } 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 + int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); + if (minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { + DataLayerListenerService.Companion.requestData(this); // attempt endTime recover missing data } } @@ -690,7 +690,7 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre chart.setViewportCalculationEnabled(true); chart.setMaximumViewport(chart.getMaximumViewport()); } else { - ListenerService.requestData(this); + DataLayerListenerService.Companion.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 index c28ac459ea..6765a751bb 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java @@ -44,7 +44,7 @@ import javax.inject.Inject; import dagger.android.AndroidInjection; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; +import info.nightscout.androidaps.data.DataLayerListenerService; import info.nightscout.androidaps.data.RawDisplayData; import info.nightscout.androidaps.interaction.utils.Persistence; import info.nightscout.androidaps.interaction.utils.WearUtil; @@ -678,7 +678,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { setupBatteryReceiver(); if ("delta_granularity".equals(key)) { - ListenerService.requestData(this); + DataLayerListenerService.Companion.requestData(this); } if (layoutSet) { setDataFields(); @@ -695,7 +695,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc 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 + DataLayerListenerService.Companion.requestData(this); // Attempt endTime recover missing data } } @@ -728,7 +728,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc setupCharts(); } rawData.updateStatusFromMessage(intent, wakeLock); - rawData.updateBasalsFromMessage(intent, wakeLock); + rawData.updateBasalsFromMessage(intent); if (isSimpleUi()) { if (needUpdate()) { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java index 9e56a8aa21..ed773c68d9 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java @@ -43,7 +43,7 @@ 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.DataLayerListenerService; import info.nightscout.androidaps.data.TempWatchData; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; @@ -137,7 +137,7 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref mRelativeLayout.getMeasuredHeight()); } }); - ListenerService.requestData(this); + DataLayerListenerService.Companion.requestData(this); wakeLock.acquire(50); } @@ -518,7 +518,7 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref 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 + DataLayerListenerService.Companion.requestData(this); // attempt endTime recover missing data } } } 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/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java index 960eeacee5..f6fefeefd6 100644 --- a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java +++ b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java @@ -220,7 +220,7 @@ public class RawDisplayDataBasalsTest extends TestBase { RawDisplayData newRaw = new RawDisplayData(getWearUtil()); // WHEN - newRaw.updateBasalsFromMessage(intent, null); + newRaw.updateBasalsFromMessage(intent); // THEN assertBasalsOk(newRaw); @@ -233,7 +233,7 @@ public class RawDisplayDataBasalsTest extends TestBase { RawDisplayData newRaw = new RawDisplayData(getWearUtil()); // WHEN - newRaw.updateBasalsFromMessage(intent, null); + newRaw.updateBasalsFromMessage(intent); // THEN assertBasalsEmpty(newRaw); From 2ebaffa4ad7e7a7a614154f79cfbac902c085590 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Apr 2022 22:19:10 +0200 Subject: [PATCH 02/54] Wear: migrate to RxBus comm and data classes --- app/src/main/AndroidManifest.xml | 20 +- .../androidaps/di/ServicesModule.kt | 4 +- .../androidaps/events/EventBolusRequested.kt | 3 - .../androidaps/plugins/aps/loop/LoopPlugin.kt | 24 +- .../general/overview/OverviewFragment.kt | 4 +- .../general/wear/ActionStringHandler.kt | 841 ------------ .../plugins/general/wear/WearFragment.kt | 8 +- .../plugins/general/wear/WearPlugin.kt | 147 +-- .../wear/events/EventWearConfirmAction.kt | 5 - .../wear/events/EventWearInitiateAction.kt | 5 - .../wear/wearintegration/DataHandlerMobile.kt | 1173 +++++++++++++++++ .../DataLayerListenerServiceMobile.kt | 200 +++ .../wearintegration/WatchUpdaterService.kt | 633 --------- .../wearintegration/WatchUpdaterService1.java | 778 ----------- .../queue/CommandQueueImplementation.kt | 9 +- .../androidaps/utils/wizard/BolusWizard.kt | 6 +- .../androidaps/utils/wizard/QuickWizard.kt | 6 + app/src/main/res/values/strings.xml | 1 + .../queue/CommandQueueImplementationTest.kt | 3 +- .../utils/wizard/BolusWizardTest.kt | 1 + .../androidaps/events/EventMobileToWear.kt | 5 + .../androidaps/events/EventWearToMobile.kt | 5 + .../events/EventWearToMobileAction.kt | 7 - .../events/EventWearToMobileChange.kt | 7 - .../events/EventWearToMobileConfirm.kt | 7 - .../nightscout/shared/weardata/ActionData.kt | 33 - .../nightscout/shared/weardata/EventData.kt | 237 ++++ .../shared/weardata/WearConstants.kt | 61 - shared/src/main/res/values/wear_paths.xml | 17 +- wear/src/main/AndroidManifest.xml | 50 +- .../java/info/nightscout/androidaps/Aaps.kt | 11 +- .../androidaps/comm/DataHandlerWear.kt | 301 +++++ .../comm/DataLayerListenerServiceWear.kt | 210 +++ .../BaseComplicationProviderService.java | 27 +- .../complications/BrCobIobComplication.java | 7 +- .../complications/CobIconComplication.java | 2 +- .../complications/CobIobComplication.java | 4 +- .../complications/IobIconComplication.java | 2 +- .../complications/SgvComplication.java | 3 +- ....java => UploaderBatteryComplication.java} | 10 +- .../androidaps/data/BasalWatchData.java | 11 - .../androidaps/data/BgWatchData.java | 49 - .../androidaps/data/BolusWatchData.java | 13 - .../data/DataLayerListenerService.kt | 552 -------- .../androidaps/data/RawDisplayData.java | 281 ---- .../androidaps/data/RawDisplayData.kt | 95 ++ .../androidaps/data/TempWatchData.java | 13 - .../androidaps/di/WearActivitiesModule.kt | 9 + .../androidaps/di/WearServicesModule.kt | 18 +- .../events/EventWearPreferenceChange.kt | 22 + .../interaction/actions/AcceptActivity.java | 24 +- .../actions/BackgroundActionActivity.kt | 14 +- .../interaction/actions/BolusActivity.java | 7 +- .../interaction/actions/CPPActivity.java | 14 +- .../interaction/actions/CarbActivity.java | 29 +- .../interaction/actions/ECarbActivity.java | 21 +- .../interaction/actions/FillActivity.java | 7 +- .../actions/TempTargetActivity.java | 28 +- .../actions/TreatmentActivity.java | 16 +- .../interaction/actions/WizardActivity.java | 18 +- .../interaction/menus/FillMenuActivity.java | 51 - .../interaction/menus/FillMenuActivity.kt | 34 + .../interaction/menus/MainMenuActivity.java | 98 -- .../interaction/menus/MainMenuActivity.kt | 56 + .../interaction/menus/StatusMenuActivity.java | 47 - .../interaction/menus/StatusMenuActivity.kt | 32 + .../interaction/utils/DisplayFormat.java | 41 +- .../interaction/utils/MenuListActivity.java | 15 +- .../interaction/utils/Persistence.java | 86 +- .../androidaps/tile/QuickWizardSource.kt | 90 +- .../androidaps/tile/StaticTileSource.kt | 11 +- .../androidaps/tile/TempTargetSource.kt | 14 +- .../nightscout/androidaps/tile/TileBase.kt | 57 +- .../androidaps/watchfaces/BIGChart.java | 596 +++------ .../androidaps/watchfaces/BaseWatchFace.java | 265 ++-- .../androidaps/watchfaces/BgGraphBuilder.java | 302 ++--- .../watchfaces/CircleWatchface.java | 442 ++----- .../androidaps/watchfaces/Cockpit.java | 11 +- .../androidaps/watchfaces/DigitalStyle.java | 25 +- .../androidaps/watchfaces/Home.java | 23 +- .../androidaps/watchfaces/Home2.java | 25 +- .../androidaps/watchfaces/LargeHome.java | 29 +- .../androidaps/watchfaces/NOChart.java | 401 ++---- .../androidaps/watchfaces/Steampunk.java | 104 +- wear/src/main/res/values/strings.xml | 17 +- .../androidaps/data/BgWatchDataTest.java | 97 -- .../data/RawDataSgvDisplayDataTest.java | 123 -- .../data/RawDisplayDataBasalsTest.java | 242 ---- .../data/RawDisplayDataBgEntriesTest.java | 135 -- .../data/RawDisplayDataStatusTest.java | 160 --- .../interaction/utils/DisplayFormatTest.java | 4 +- .../interaction/utils/PersistenceTest.java | 61 - .../interaction/utils/WearUtilTest.kt | 5 +- .../testing/mockers/RawDataMocker.java | 122 +- .../testing/utils/BasalWatchDataExt.java | 59 - .../testing/utils/BgWatchDataExt.java | 68 - .../testing/utils/BolusWatchDataExt.java | 65 - .../androidaps/testing/utils/ExtUtil.java | 27 - .../testing/utils/TempWatchDataExt.java | 67 - 99 files changed, 3716 insertions(+), 6509 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearConfirmAction.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearInitiateAction.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataHandlerMobile.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService1.java create mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventMobileToWear.kt create mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobile.kt delete mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt delete mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt delete mode 100644 shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt delete mode 100644 shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt create mode 100644 shared/src/main/java/info/nightscout/shared/weardata/EventData.kt delete mode 100644 shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt create mode 100644 wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt create mode 100644 wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt rename wear/src/main/java/info/nightscout/androidaps/complications/{UploaderBattery.java => UploaderBatteryComplication.java} (95%) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.kt delete mode 100644 wear/src/test/java/info/nightscout/androidaps/data/BgWatchDataTest.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/utils/BasalWatchDataExt.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/utils/BgWatchDataExt.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/utils/BolusWatchDataExt.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/utils/ExtUtil.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/utils/TempWatchDataExt.java diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 3069f7d830..668d69029d 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -167,7 +167,7 @@ @@ -185,23 +185,7 @@ - - - - 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/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/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index fa8c085404..0cb9545d61 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 @@ -58,6 +57,7 @@ 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/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index efcc0c154e..21a8ee9f95 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 @@ -76,6 +75,7 @@ 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.* @@ -408,7 +408,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/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt deleted file mode 100644 index 52a2a5ce27..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ /dev/null @@ -1,841 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear - -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.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.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.androidaps.utils.wizard.BolusWizard -import info.nightscout.androidaps.utils.wizard.QuickWizard -import info.nightscout.shared.SafeParse -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.shared.logging.LTag -import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.shared.weardata.ActionData -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_BOLUS -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_CANCEL_CHANGE_REQUEST -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_CHANGE_REQUEST -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_CPP_SET -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_DISMISS_OVERVIEW_NOTIF -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_E_CARBS -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_FILL -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_FILL_PRESET -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_OPEN_CPP -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_QUICK_WIZARD -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_STATUS -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_TDD_STATS -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_TEMPORARY_TARGET -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_WIZARD -import info.nightscout.shared.weardata.WearConstants.Companion.ACTION_WIZARD2 -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({ handleInitiateActionOnPhone(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 handleInitiateActionOnPhone(actionString: String) { - //TODO: i18n - aapsLogger.debug(LTag.WEAR, "handleInitiateActionOnPhone 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 = "" - - if (actionString.startsWith("{")) { - when (val command = ActionData.deserialize(actionString)) { - is ActionData.Bolus -> { - 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 - } - rMessage += rh.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" - rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" - if (insulinAfterConstraints - command.insulin != 0.0 || carbsAfterConstraints - command.carbs != 0) { - rMessage += "\n" + rh.gs(R.string.constraintapllied) - } - rAction += "bolus $insulinAfterConstraints $carbsAfterConstraints" - } - is ActionData.ProfileSwitch -> { - val activeProfileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() - if (activeProfileSwitch is ValueWrapper.Existing) { - rMessage = "Profile:" + "\n\n" + - "Timeshift: " + command.timeShift + "\n" + - "Percentage: " + command.percentage + "%" - rAction = actionString - } else { // read CPP values - sendError("No active profile switch!") - return - } - } - } - } else { - // do the parsing and check constraints - val act = actionString.split("\\s+".toRegex()).toTypedArray() - when (act[0]) { - ACTION_FILL_PRESET -> { ///////////////////////////////////// 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" - } - - ACTION_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" - } - - ACTION_TEMPORARY_TARGET -> { - 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 - } - } - } - - ACTION_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" - } - } - - ACTION_WIZARD -> { - sendError("Update APP on Watch!") - return - } - - ACTION_WIZARD2 -> { - 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 - } - - ACTION_QUICK_WIZARD -> { - 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() - - } - - ACTION_OPEN_CPP -> { - 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 - } - } - - ACTION_TDD_STATS -> { - 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) - } - } - - ACTION_E_CARBS -> { - 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" - } - - ACTION_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 - } - - ACTION_CANCEL_CHANGE_REQUEST -> { - 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() - when (act[0]) { - ACTION_FILL -> { - 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) - } - - ACTION_TEMPORARY_TARGET -> { - val duration = SafeParse.stringToInt(act[2]) - val low = SafeParse.stringToDouble(act[3]) - val high = SafeParse.stringToDouble(act[4]) - generateTempTarget(duration, low, high) - } - - ACTION_WIZARD2 -> { - if (lastBolusWizard != null) { //use last calculation as confirmed string matches - doBolus(lastBolusWizard!!.calculatedTotalInsulin, lastBolusWizard!!.carbs, null, 0) - lastBolusWizard = null - } - } - - ACTION_BOLUS -> { - val insulin = SafeParse.stringToDouble(act[1]) - val carbs = SafeParse.stringToInt(act[2]) - doBolus(insulin, carbs, null, 0) - } - - ACTION_CPP_SET -> { - val timeshift = SafeParse.stringToInt(act[1]) - val percentage = SafeParse.stringToInt(act[2]) - setCPP(timeshift, percentage) - } - - ACTION_E_CARBS -> { - val carbs = SafeParse.stringToInt(act[1]) - val starttime = SafeParse.stringToLong(act[2]) - val duration = SafeParse.stringToInt(act[3]) - doECarbs(carbs, starttime, duration) - } - - ACTION_DISMISS_OVERVIEW_NOTIF -> { - rxBus.send(EventDismissNotification(SafeParse.stringToInt(act[1]))) - } - - ACTION_CHANGE_REQUEST -> { - 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 95e21f730d..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,10 +6,13 @@ 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 @@ -20,6 +23,7 @@ class WearFragment : DaggerFragment() { @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 @@ -37,8 +41,8 @@ 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() { 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 ead6df3277..3ac1f5adbb 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,24 +2,26 @@ 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.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.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.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 @@ -32,10 +34,10 @@ class WearPlugin @Inject constructor( rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val sp: SP, - private val ctx: Context, private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBus, - private val actionStringHandler: Lazy + private val context: Context, + private val dataHandlerMobile: DataHandlerMobile ) : PluginBase( PluginDescription() @@ -55,136 +57,43 @@ class WearPlugin @Inject constructor( override fun onStart() { super.onStart() - disposable += rxBus - .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) - - disposable += rxBus - .toObservable(EventExtendedBolusChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) - disposable += rxBus - .toObservable(EventTempBasalChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) - disposable += rxBus - .toObservable(EventTreatmentChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException) - disposable += rxBus - .toObservable(EventEffectiveProfileSwitchChanged::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = false, basals = true, bgValue = false) }, fabricPrivacy::logException) - disposable += rxBus - .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = true) }, fabricPrivacy::logException) - disposable += 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 += rxBus - .toObservable(EventLoopUpdateGui::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - sendDataToWatch(status = true, basals = false, bgValue = false) - }, fabricPrivacy::logException) - disposable += 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_BOLUS_PROGRESS) - intent.putExtra("progresspercent", 0) - intent.putExtra("progressstatus", status) - ctx.startService(intent) - }, fabricPrivacy::logException) + 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) + 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))) } - val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUS_PROGRESS) - intent.putExtra("progresspercent", 100) - intent.putExtra("progressstatus", status) - ctx.startService(intent) }, 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_BOLUS_PROGRESS) - intent.putExtra("progresspercent", event.percent) - intent.putExtra("progressstatus", event.status) - ctx.startService(intent) + if (isEnabled()) rxBus.send(EventMobileToWear(EventData.BolusProgress(percent = event.percent, status = event.status))) } }, fabricPrivacy::logException) - actionStringHandler.get().setup() + 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) { - // only start service when this plugin is enabled - if (isEnabled()) { - 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() { - ctx.startService(Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_RESEND)) - } - - fun openSettings() { - ctx.startService(Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_OPEN_SETTINGS)) - } - - fun requestNotificationCancel(actionString: String?) { - ctx.startService( - Intent(ctx, WatchUpdaterService::class.java) - .setAction(WatchUpdaterService.ACTION_CANCEL_NOTIFICATION) - .also { - it.putExtra("actionstring", actionString) - }) - } - - fun requestActionConfirmation(title: String, message: String, actionString: String) { - ctx.startService( - Intent(ctx, WatchUpdaterService::class.java) - .setAction(WatchUpdaterService.ACTION_SEND_ACTION_CONFIRMATION_REQUEST) - .also { - it.putExtra("title", title) - it.putExtra("message", message) - it.putExtra("actionstring", actionString) - }) - } - - fun requestChangeConfirmation(title: String, message: String, actionString: String) { - ctx.startService( - Intent(ctx, WatchUpdaterService::class.java) - .setAction(WatchUpdaterService.ACTION_SEND_CHANGE_CONFIRMATION_REQUEST) - .also { - it.putExtra("title", title) - it.putExtra("message", message) - it.putExtra("actionstring", actionString) - }) + 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/EventWearConfirmAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearConfirmAction.kt deleted file mode 100644 index 211836d27d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearConfirmAction.kt +++ /dev/null @@ -1,5 +0,0 @@ -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 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/wearintegration/DataHandlerMobile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataHandlerMobile.kt new file mode 100644 index 0000000000..16db4f7241 --- /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.utils.resources.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..b8305a981b --- /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.utils.resources.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/WatchUpdaterService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.kt deleted file mode 100644 index c3a37d4f61..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.kt +++ /dev/null @@ -1,633 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear.wearintegration - -import android.content.Intent -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.Constants -import info.nightscout.androidaps.R -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.convertedToAbsolute -import info.nightscout.androidaps.extensions.toStringShort -import info.nightscout.androidaps.extensions.valueToUnitsString -import info.nightscout.androidaps.interfaces.* -import info.nightscout.androidaps.interfaces.Profile.Companion.fromMgdlToUnits -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.general.wear.events.EventWearUpdateGui -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.to0Decimal -import info.nightscout.androidaps.utils.DecimalFormatter.to1Decimal -import info.nightscout.androidaps.utils.DecimalFormatter.to2Decimal -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.WearConstants -import io.reactivex.rxjava3.disposables.CompositeDisposable -import kotlinx.coroutines.* -import kotlinx.coroutines.tasks.await -import java.util.function.Consumer -import java.util.stream.Collectors -import javax.inject.Inject -import kotlin.math.abs - -class WatchUpdaterService : 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 glucoseStatusProvider: GlucoseStatusProvider - @Inject lateinit var trendCalculator: TrendCalculator - @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var rxBus: RxBus - @Inject lateinit var wearConstants: WearConstants - - 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() - - override fun onCreate() { - AndroidInjection.inject(this) - super.onCreate() - aapsLogger.debug(LTag.WEAR, "onCreate") - handler.post { updateTranscriptionCapability() } - } - - 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() - } - - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - aapsLogger.debug(LTag.WEAR, "onStartCommand ${intent?.action}") - if (wearPlugin.isEnabled()) { - handler.post { - when (intent?.action) { - ACTION_RESEND -> resendData() - ACTION_OPEN_SETTINGS -> sendMessage(wearConstants.M_W_OPEN_SETTINGS, byteArrayOf()) - ACTION_SEND_STATUS -> sendStatus() - ACTION_SEND_BASALS -> sendBasals() - ACTION_SEND_BOLUS_PROGRESS -> sendBolusProgress( - intent.getIntExtra("progresspercent", 0), - intent.getStringExtra("progressstatus") - ) - ACTION_SEND_ACTION_CONFIRMATION_REQUEST -> sendActionConfirmationRequest( - intent.getStringExtra("title"), - intent.getStringExtra("message"), - intent.getStringExtra("actionstring") - ) - ACTION_SEND_CHANGE_CONFIRMATION_REQUEST -> sendChangeConfirmationRequest( - intent.getStringExtra("title"), - intent.getStringExtra("message"), - intent.getStringExtra("actionstring") - ) - ACTION_CANCEL_NOTIFICATION -> sendCancelNotificationRequest(intent.getStringExtra("actionstring")) - - null -> {} - - else -> sendData() - } - } - } - return START_STICKY - } - - @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) - aapsLogger.debug(LTag.WEAR, "onMessageReceived: $messageEvent") - - if (wearPlugin.isEnabled()) { - when (messageEvent.path) { - wearConstants.W_M_RESEND_DATA -> resendData() - wearConstants.W_M_CANCEL_BOLUS -> activePlugin.activePump.stopBolusDelivering() - - wearConstants.W_M_INITIATE_ACTION -> - String(messageEvent.data).also { actionstring -> - aapsLogger.debug(LTag.WEAR, "Initiate action: $actionstring") - rxBus.send(EventWearInitiateAction(actionstring)) - } - - wearConstants.W_M_CONFIRM_ACTION -> - String(messageEvent.data).also { actionstring -> - aapsLogger.debug(LTag.WEAR, "Wear confirm action: $actionstring") - rxBus.send(EventWearConfirmAction(actionstring)) - } - - wearConstants.W_M_PONG -> aapsLogger.debug(LTag.WEAR, "Pong response from ${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") - sendMessage(wearConstants.M_W_PING, byteArrayOf()) - } - - // Find a nearby node or pick one arbitrarily - private fun pickBestNodeId(nodes: Set): Node? = - nodes.firstOrNull { it.isNearby } ?: nodes.firstOrNull() - - 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: ByteArray) { - if (wearPlugin.isEnabled()) { - aapsLogger.debug(LTag.WEAR, "sendMessage: $path") - transcriptionNodeId?.also { nodeId -> - messageClient - .sendMessage(nodeId, path, data).apply { - addOnSuccessListener { } - addOnFailureListener { - aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure") - } - } - } - } - } - - private fun sendData() { - val lastBG = iobCobCalculator.ads.lastBg() ?: return - val glucoseStatus = glucoseStatusProvider.glucoseStatusData - aapsLogger.debug(LTag.WEAR, "Sending bg data to wear") - sendData( - wearConstants.M_W_DATA, - dataMapSingleBG(lastBG, glucoseStatus) - ) - } - - private fun resendData() { - sendPreferences() - sendQuickWizard() - val startTime = System.currentTimeMillis() - (60000 * 60 * 5.5).toLong() - val lastBg = iobCobCalculator.ads.lastBg() ?: return - val graphBgs = repository.compatGetBgReadingsDataFromTime(startTime, true).blockingGet() - val glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(true) - if (graphBgs.isNotEmpty()) { - val entries = dataMapSingleBG(lastBg, glucoseStatus) - val dataMaps = ArrayList(graphBgs.size) - for (bg in graphBgs) { - val dataMap: DataMap = dataMapSingleBG(bg, glucoseStatus) - dataMaps.add(dataMap) - } - entries.putDataMapArrayList("entries", dataMaps) - aapsLogger.debug(LTag.WEAR, "Sending graph bg data to wear") - sendData( - wearConstants.M_W_DATA, - entries - ) - } - sendBasals() - sendStatus() - } - - private fun sendBasals() { - val now = System.currentTimeMillis() - val startTimeWindow = now - (60000 * 60 * 5.5).toLong() - val basals = java.util.ArrayList() - val temps = java.util.ArrayList() - val boluses = java.util.ArrayList() - val predictions = java.util.ArrayList() - 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(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(tempMap(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(tempMap(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(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(tempMap(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(tempMap(tbStart, tbBefore, now, tbAmount, tbAmount)) - temps.add(tempMap(now, tbAmount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)) - } else { - temps.add(tempMap(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(tempMap(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(treatmentMap(timestamp, amount, 0.0, type === Bolus.Type.SMB, isValid)) } - repository.getCarbsDataFromTimeExpanded(startTimeWindow, true).blockingGet() - .forEach(Consumer { (_, _, _, isValid, _, _, timestamp, _, _, amount) -> boluses.add(treatmentMap(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(predictionMap(bg.data.timestamp, bg.data.value, bg.color(null))) - } - aapsLogger.debug(LTag.WEAR, "Sending basal data to wear") - sendData( - wearConstants.M_W_BASAL, - DataMap().apply { - putDataMapArrayList("basals", basals) - putDataMapArrayList("temps", temps) - putDataMapArrayList("boluses", boluses) - putDataMapArrayList("predictions", predictions) - }) - } - - 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) to1Decimal(abs(deltaMGDL)) else to0Decimal(abs(deltaMGDL)) - } else { - if (detailed) to2Decimal(abs(deltaMMOL)) else to1Decimal(abs(deltaMMOL)) - } - return deltaString - } - - private fun dataMapSingleBG(lastBG: GlucoseValue, glucoseStatus: GlucoseStatus?): DataMap { - val units = profileFunction.getUnits() - val lowLine = Profile.toMgdl(defaultValueHelper.determineLowLine(), units) - val highLine = Profile.toMgdl(defaultValueHelper.determineHighLine(), units) - val sgvLevel = if (lastBG.value > highLine) 1L else if (lastBG.value < lowLine) -1L else 0L - val dataMap = DataMap() - dataMap.putString("sgvString", lastBG.valueToUnitsString(units)) - dataMap.putString("glucoseUnits", units.asText) - dataMap.putLong("timestamp", lastBG.timestamp) - if (glucoseStatus == null) { - dataMap.putString("slopeArrow", "") - dataMap.putString("delta", "--") - dataMap.putString("avgDelta", "--") - } else { - dataMap.putString("slopeArrow", trendCalculator.getTrendArrow(lastBG).symbol) - dataMap.putString("delta", deltaString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)) - dataMap.putString("avgDelta", deltaString(glucoseStatus.shortAvgDelta, glucoseStatus.shortAvgDelta * Constants.MGDL_TO_MMOLL, units)) - } - dataMap.putLong("sgvLevel", sgvLevel) - dataMap.putDouble("sgvDouble", lastBG.value) - dataMap.putDouble("high", highLine) - dataMap.putDouble("low", lowLine) - return dataMap - } - - private fun tempMap(startTime: Long, startBasal: Double, to: Long, toBasal: Double, amount: Double) = - DataMap().apply { - putLong("starttime", startTime) - putDouble("startBasal", startBasal) - putLong("endtime", to) - putDouble("endbasal", toBasal) - putDouble("amount", amount) - } - - private fun basalMap(startTime: Long, endTime: Long, amount: Double) = - DataMap().apply { - putLong("starttime", startTime) - putLong("endtime", endTime) - putDouble("amount", amount) - } - - private fun treatmentMap(date: Long, bolus: Double, carbs: Double, isSMB: Boolean, isValid: Boolean) = - DataMap().apply { - putLong("date", date) - putDouble("bolus", bolus) - putDouble("carbs", carbs) - putBoolean("isSMB", isSMB) - putBoolean("isValid", isValid) - } - - private fun predictionMap(timestamp: Long, sgv: Double, color: Int) = - DataMap().apply { - putLong("timestamp", timestamp) - putDouble("sgv", sgv) - putInt("color", color) - } - - private fun quickMap(q: QuickWizardEntry) = - DataMap().apply { - putString("guid", q.guid()) - putString("button_text", q.buttonText()) - putInt("carbs", q.carbs()) - putInt("from", q.validFrom()) - putInt("to", q.validTo()) - } - - private fun sendBolusProgress(progressPercent: Int?, status: String?) { - progressPercent ?: return - aapsLogger.debug(LTag.WEAR, "Sending bolus progress: $progressPercent $status") - sendData( - wearConstants.M_W_BOLUS_PROGRESS, - DataMap().apply { - putLong("timestamp", System.currentTimeMillis()) - putString("bolusProgress", "bolusProgress") - putString("progressstatus", status ?: "") - putInt("progresspercent", progressPercent) - }) - } - - private fun sendActionConfirmationRequest(title: String?, message: String?, actionstring: String?) { - title ?: message ?: actionstring ?: return - aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: $actionstring") - sendData( - wearConstants.M_W_ACTION_CONFIRMATION_REQUEST, - DataMap().apply { - putLong("timestamp", System.currentTimeMillis()) - putString("actionConfirmationRequest", "actionConfirmationRequest") - putString("title", title) - putString("message", message) - putString("actionstring", actionstring) - }) - } - - private fun sendChangeConfirmationRequest(title: String?, message: String?, actionstring: String?) { - title ?: message ?: actionstring ?: return - aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: $actionstring") - sendData( - wearConstants.M_W_ACTION_CHANGE_CONFIRMATION_REQUEST, - DataMap().apply { - putLong("timestamp", System.currentTimeMillis()) - putString("changeConfirmationRequest", "changeConfirmationRequest") - putString("title", title) - putString("message", message) - putString("actionstring", actionstring) - }) - } - - private fun sendCancelNotificationRequest(actionstring: String?) { - actionstring ?: return - aapsLogger.debug(LTag.WEAR, "Canceling notification on wear: $actionstring") - sendData( - wearConstants.M_W_ACTION_CANCEL_NOTIFICATION_REQUEST, - DataMap().apply { - putLong("timestamp", System.currentTimeMillis()) - putString("cancelNotificationRequest", "cancelNotificationRequest") - putString("actionstring", actionstring) - }) - } - - private fun sendStatus() { - aapsLogger.debug(LTag.WEAR, "Updating status on wear") - 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 = to2Decimal(bolusIob.iob + basalIob.basaliob) - iobDetail = "(" + to2Decimal(bolusIob.iob) + "|" + to2Decimal(basalIob.basaliob) + ")" - cobString = iobCobCalculator.getCobInfo(false, "WatcherUpdaterService").generateCOBString() - currentBasal = generateBasalString() - - //bgi - val bgi = -(bolusIob.activity + basalIob.activity) * 5 * fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()) - bgiString = "" + (if (bgi >= 0) "+" else "") + 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 - - sendData( - wearConstants.M_W_STATUS, - DataMap().apply { - //unique content - putString("externalStatusString", status) - putString("iobSum", iobSum) - putString("iobDetail", iobDetail) - putBoolean("detailedIob", sp.getBoolean(R.string.key_wear_detailediob, false)) - putString("cob", cobString) - putString("currentBasal", currentBasal) - putString("battery", "" + phoneBattery) - putString("rigBattery", rigBattery) - putLong("openApsStatus", openApsStatus) - putString("bgi", bgiString) - putBoolean("showBgi", sp.getBoolean(R.string.key_wear_showbgi, false)) - putInt("batteryLevel", if (phoneBattery >= 30) 1 else 0) - }) - } - - private fun sendPreferences() { - sendData( - wearConstants.M_W_PREFERENCES, - DataMap().apply { - putLong("timestamp", System.currentTimeMillis()) - putBoolean(rh.gs(R.string.key_wear_control), sp.getBoolean(R.string.key_wear_control, false)) - putBoolean(rh.gs(R.string.key_units_mgdl), profileFunction.getUnits() == GlucoseUnit.MGDL) - putInt(rh.gs(R.string.key_boluswizard_percentage), sp.getInt(R.string.key_boluswizard_percentage, 100)) - putInt(rh.gs(R.string.key_treatmentssafety_maxcarbs), sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48)) - putDouble(rh.gs(R.string.key_treatmentssafety_maxbolus), sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0)) - }) - } - - private fun sendQuickWizard() { - val entities = ArrayList() - for (i in 0 until quickWizard.size()) { - val q = quickWizard[i] - if (q.forDevice(QuickWizardEntry.DEVICE_WATCH)) entities.add(quickMap(q)) - } - sendData( - wearConstants.M_W_QUICK_WIZARD, - DataMap().apply { - putLong("timestamp", System.currentTimeMillis()) - putDataMapArrayList("quick_wizard", entities) - }) - } - - private fun generateStatusString(profile: Profile?, currentBasal: String, iobSum: String, iobDetail: String, bgiString: String): String { - var status = "" - if (profile == null) 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 generateBasalString(): String { - val profile: Profile = profileFunction.getProfile() ?: return "" - return iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())?.toStringShort() ?: to2Decimal(profile.getBasal()) + "U/h" - } - - companion object { - - const val WEAR_CAPABILITY = "androidaps_wear" - - val ACTION_RESEND = WatchUpdaterService::class.java.name + ".Resend" - val ACTION_OPEN_SETTINGS = WatchUpdaterService::class.java.name + ".OpenSettings" - val ACTION_SEND_STATUS = WatchUpdaterService::class.java.name + ".SendStatus" - val ACTION_SEND_BASALS = WatchUpdaterService::class.java.name + ".SendBasals" - val ACTION_SEND_BOLUS_PROGRESS = WatchUpdaterService::class.java.name + ".BolusProgress" - val ACTION_SEND_ACTION_CONFIRMATION_REQUEST = WatchUpdaterService::class.java.name + ".ActionConfirmationRequest" - val ACTION_SEND_CHANGE_CONFIRMATION_REQUEST = WatchUpdaterService::class.java.name + ".ChangeConfirmationRequest" - val ACTION_CANCEL_NOTIFICATION = WatchUpdaterService::class.java.name + ".CancelNotification" - - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService1.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService1.java deleted file mode 100644 index 95a2419d4a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService1.java +++ /dev/null @@ -1,778 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear.wearintegration; - -/* -public class WatchUpdaterService1 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); - } -} -*/ \ No newline at end of file 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..4f9b16efcc 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 @@ -40,7 +38,10 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.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/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 4b691ec932..581e201deb 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 @@ -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..450ce43d46 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 @@ -9,6 +9,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 +56,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) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index a8f8bf0efd..316ef63054 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1212,4 +1212,5 @@ Hide loop records AndroidAPS widget Configure opacity + Loop status 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 1f49ca02a5..c16f8a52bb 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 @@ -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..420f062103 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 @@ -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/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/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt deleted file mode 100644 index 1d5ca463e9..0000000000 --- a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileAction.kt +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.events - -import info.nightscout.shared.weardata.ActionData -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json - -class EventWearToMobileAction(val actionData: ActionData) : Event() \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt deleted file mode 100644 index 49ae662e82..0000000000 --- a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileChange.kt +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.events - -import info.nightscout.shared.weardata.ActionData -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json - -class EventWearToMobileChange(val actionData: ActionData) : Event() \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt deleted file mode 100644 index c999248cde..0000000000 --- a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobileConfirm.kt +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.events - -import info.nightscout.shared.weardata.ActionData -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json - -class EventWearToMobileConfirm(val actionData: ActionData) : Event() \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt b/shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt deleted file mode 100644 index 042edc0d6f..0000000000 --- a/shared/src/main/java/info/nightscout/shared/weardata/ActionData.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.shared.weardata - -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json - -@Serializable -sealed class ActionData { - - fun serialize() = Json.encodeToString(serializer(), this) - - companion object { - - fun deserialize(json: String) = Json.decodeFromString(serializer(), json) - } - // Wear -> Mobile - @Serializable - data class Pong(val timeStamp: Long) : ActionData() - @Serializable - data class Bolus(val insulin: Double, val carbs: Int) : ActionData() - @Serializable - data class ProfileSwitch(val timeShift: Int, val percentage: Int) : ActionData() - - @Serializable - data class OpenProfileSwitch(val timeShift: Int, val percentage: Int) : ActionData() - - // Mobile -> Wear - @Serializable - data class Ping(val timeStamp: Long) : ActionData() - @Serializable - data class ConfirmAction(val title: String, val message: String, val originalCommand: ActionData) : ActionData() - @Serializable - data class ChangeAction(val title: String, val message: String, val originalCommand: ActionData) : ActionData() -} \ No newline at end of file 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/WearConstants.kt b/shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt deleted file mode 100644 index 7d5558d5f8..0000000000 --- a/shared/src/main/java/info/nightscout/shared/weardata/WearConstants.kt +++ /dev/null @@ -1,61 +0,0 @@ -package info.nightscout.shared.weardata - -import android.content.Context -import info.nightscout.shared.R -import javax.inject.Inject -import javax.inject.Singleton - -@Suppress("PropertyName") -@Singleton -class WearConstants @Inject constructor(private val context: Context) { - - // Paths must be defined in manifest - // mobile -> wear (data) - val M_W_DATA get() = context.getString(R.string.path_watch_data) - val M_W_STATUS get() = context.getString(R.string.path_status) - val M_W_PREFERENCES get() = context.getString(R.string.path_preferences) - val M_W_QUICK_WIZARD get() = context.getString(R.string.path_quick_wizard) - val M_W_BASAL get() = context.getString(R.string.path_basal) - val M_W_BOLUS_PROGRESS get() = context.getString(R.string.path_bolus_progress) - val M_W_ACTION_CONFIRMATION_REQUEST get() = context.getString(R.string.path_action_confirmation) - val M_W_ACTION_CHANGE_CONFIRMATION_REQUEST get() = context.getString(R.string.path_change_confirmation_request) - val M_W_ACTION_CANCEL_NOTIFICATION_REQUEST get() = context.getString(R.string.path_cancel_notification_request) - - // mobile -> wear (message) - val M_W_OPEN_SETTINGS get() = context.getString(R.string.path_open_wear_setting) - val M_W_PING get() = context.getString(R.string.path_ping) - - // wear -> mobile (message) - val W_M_RESEND_DATA get() = context.getString(R.string.path_resend_data_request) - val W_M_CANCEL_BOLUS get() = context.getString(R.string.path_cancel_bolus_on_phone) - val W_M_CONFIRM_ACTION get() = context.getString(R.string.path_confirm_action) - val W_M_INITIATE_ACTION get() = context.getString(R.string.path_initiate_action_on_phone) - val W_M_PONG get() = context.getString(R.string.path_pong) - - companion object { - - // actions for WEAR_INITIATE_ACTION_ON_PHONE - // used by - // DataLayerListenerService::initiateAction - // ActionStringHandler::handleInitiateActionOnPhone - // EventWearInitiateAction - const val ACTION_FILL_PRESET = "fillpreset" - const val ACTION_FILL = "fill" - const val ACTION_BOLUS = "bolus" - const val ACTION_TEMPORARY_TARGET = "temptarget" - const val ACTION_STATUS = "status" - const val ACTION_WIZARD = "wizard" - const val ACTION_WIZARD2 = "wizard2" - const val ACTION_QUICK_WIZARD = "quick_wizard" - const val ACTION_OPEN_CPP = "opencpp" - const val ACTION_CPP_SET = "cppset" - const val ACTION_TDD_STATS = "tddstats" - const val ACTION_E_CARBS = "ecarbs" - const val ACTION_CHANGE_REQUEST = "changeRequest" - const val ACTION_CANCEL_CHANGE_REQUEST = "cancelChangeRequest" - const val ACTION_DISMISS_OVERVIEW_NOTIF = "dismissoverviewnotification" - - //data keys - const val KEY_ACTION_DATA = "actionData" - } -} diff --git a/shared/src/main/res/values/wear_paths.xml b/shared/src/main/res/values/wear_paths.xml index 1bf7203905..36d7325849 100644 --- a/shared/src/main/res/values/wear_paths.xml +++ b/shared/src/main/res/values/wear_paths.xml @@ -1,19 +1,4 @@ - /ping - /pong - /openwearsettings - /nightscout_watch_data_resend - /nightscout_watch_initiateactionstring - /nightscout_watch_cancel_bolus - /nightscout_watch_confirmactionstring - /nightscout_watch_data - /sendstatustowear - /sendpreferencestowear - /send_quick_wizard - /nightscout_watch_basal - /nightscout_watch_bolusprogress - /nightscout_watch_actionconfirmationrequest - /nightscout_watch_changeconfirmationrequest - /nightscout_watch_cancelnotificationrequest + /rx_bridge \ No newline at end of file diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 95ff23dc3f..cd0fd89207 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -241,7 +241,7 @@ - @@ -252,42 +252,6 @@ - - - - - - - - - @@ -299,15 +263,7 @@ - - @@ -466,7 +422,7 @@ diff --git a/wear/src/main/java/info/nightscout/androidaps/Aaps.kt b/wear/src/main/java/info/nightscout/androidaps/Aaps.kt index 565ddf002e..ef5ca19d11 100644 --- a/wear/src/main/java/info/nightscout/androidaps/Aaps.kt +++ b/wear/src/main/java/info/nightscout/androidaps/Aaps.kt @@ -7,7 +7,11 @@ 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 @@ -15,11 +19,15 @@ 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 = @@ -30,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..67a4b7afe4 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt @@ -0,0 +1,301 @@ +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.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.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("title", it.title) + bundle.putString("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, AAPSPreferences::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, CPPActivity::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).apply { + putExtra(DataLayerListenerServiceWear.KEY_STATUS_DATA, it.serialize()) + } + ) + } + disposable += rxBus + .toObservable(EventData.SingleBg::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "SingleBg received from ${it.sourceNodeId}") + persistence.store(it) + LocalBroadcastManager.getInstance(context).sendBroadcast( + Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { + putExtra(DataLayerListenerServiceWear.KEY_SINGLE_BG_DATA, it.serialize()) + } + ) + } + disposable += rxBus + .toObservable(EventData.GraphData::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "GraphData received from ${it.sourceNodeId}") + persistence.store(it) + LocalBroadcastManager.getInstance(context).sendBroadcast( + Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { + putExtra(DataLayerListenerServiceWear.KEY_GRAPH_DATA, it.serialize()) + } + ) + } + disposable += rxBus + .toObservable(EventData.TreatmentData::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "TreatmentData received from ${it.sourceNodeId}") + persistence.store(it) + LocalBroadcastManager.getInstance(context).sendBroadcast( + Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { + putExtra(DataLayerListenerServiceWear.KEY_TREATMENTS_DATA, it.serialize()) + } + ) + } + 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_boluswizard_percentage, it.bolusPercentage) + sp.putInt(R.string.key_treatmentssafety_maxcarbs, it.maxCarbs) + sp.putDouble(R.string.key_treatmentssafety_maxbolus, 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 + val notificationManager = context.getSystemService(NotificationManager::class.java) + notificationManager.createNotificationChannel(channel) + } + var builder = NotificationCompat.Builder(context, DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_OPEN_LOOP) + builder = builder.setSmallIcon(R.drawable.notif_icon) + .setContentTitle(command.title) + .setContentText(command.message) + .setPriority(Notification.PRIORITY_HIGH) + .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000)) + + // 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("title", command.title) + bundle.putString("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..3950cd0c10 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt @@ -0,0 +1,210 @@ +package info.nightscout.androidaps.comm + +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 }) + } + } + } + + 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()))) + } + + } + 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 + ")" }}") + transcriptionNodeId = pickBestNodeId(capabilityInfo.nodes) + 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?) { + 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 PHONE_CAPABILITY = "androidaps_mobile" + + // Accepted intents + val INTENT_CANCEL_BOLUS = DataLayerListenerServiceWear::class.java.name + ".CancelBolus" + val INTENT_NEW_DATA = DataLayerListenerServiceWear::class.java.name + ".NewData" + + //data keys + const val KEY_ACTION_DATA = "actionData" + const val KEY_ACTION = "action" + const val KEY_MESSAGE = "message" + const val KEY_SINGLE_BG_DATA = "single_bg_data" + const val KEY_TREATMENTS_DATA = "treatments_data" + const val KEY_GRAPH_DATA = "graph_data" + const val KEY_STATUS_DATA = "status_data" + + 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/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java index 7d65be3080..9593474390 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java @@ -22,15 +22,18 @@ import javax.inject.Inject; import dagger.android.AndroidInjection; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear; 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; /** * Base class for all complications @@ -44,6 +47,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid @Inject DisplayFormat displayFormat; @Inject Persistence persistence; @Inject AAPSLogger aapsLogger; + @Inject RxBus rxBus; // Not derived from DaggerService, do injection here @Override @@ -199,13 +203,13 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid persistence.putBoolean("complication_" + complicationId + "_since", usesSinceField()); persistence.addToSet(KEY_COMPLICATIONS, "complication_" + complicationId); - IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND); + IntentFilter messageFilter = new IntentFilter(DataLayerListenerServiceWear.Companion.getINTENT_NEW_DATA()); messageReceiver = new MessageReceiver(); localBroadcastManager = LocalBroadcastManager.getInstance(this); localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - DataLayerListenerService.Companion.requestData(this); + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BaseComplicationProviderService"))); checkIfUpdateNeeded(); } @@ -232,12 +236,13 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid ComplicationTapBroadcastReceiver.getTapActionIntent( getApplicationContext(), thisProvider, complicationId, getComplicationAction()); - final RawDisplayData raw = new RawDisplayData(wearUtil); + final RawDisplayData raw = new RawDisplayData(); 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)); + persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, + displayFormat.shortTimeSince(raw.getSingleBg().getTimeStamp())); // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round persistence.putBoolean(KEY_STALE_REPORTED, false); @@ -249,11 +254,11 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid 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) { + } else if (wearUtil.msSince(raw.getSingleBg().getTimeStamp()) > 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); + getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.getSingleBg().getTimeStamp()); + complicationData = buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.getSingleBg().getTimeStamp()); } else { // data is up-to-date, we can render standard complication complicationData = buildComplicationData(dataType, raw, complicationPendingIntent); @@ -310,13 +315,13 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid * is up-to-date or need to be changed (a minute or more elapsed) */ private void requestUpdateIfSinceChanged() { - final RawDisplayData raw = new RawDisplayData(wearUtil); + final RawDisplayData raw = new RawDisplayData(); raw.updateForComplicationsFromPersistence(persistence); final String lastSince = persistence.getString(KEY_LAST_SHOWN_SINCE_VALUE, "-"); - final String calcSince = displayFormat.shortTimeSince(raw.datetime); + final String calcSince = displayFormat.shortTimeSince(raw.getSingleBg().getTimeStamp()); final boolean isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) - || (wearUtil.msSince(raw.datetime) > Constants.STALE_MS); + || (wearUtil.msSince(raw.getSingleBg().getTimeStamp()) > Constants.STALE_MS); final boolean staleWasRefreshed = persistence.getBoolean(KEY_STALE_REPORTED, false); final boolean sinceWasChanged = !lastSince.equals(calcSince); diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java index 10295844c4..bdbc079793 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java @@ -3,7 +3,6 @@ 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; @@ -32,11 +31,11 @@ public class BrCobIobComplication extends BaseComplicationProviderService { 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 String cob = new SmallestDoubleString(raw.getStatus().getCob(), SmallestDoubleString.Units.USE).minimise(displayFormat.MIN_FIELD_LEN_COB); + final String iob = new SmallestDoubleString(raw.getStatus().getIobSum(), 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)) + .setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.getStatus().getCurrentBasal())) .setShortTitle(ComplicationText.plainText(cob + " " + iob)) .setTapAction(complicationPendingIntent); diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java index 98ffdb1e56..c679635e4c 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java @@ -20,7 +20,7 @@ public class CobIconComplication extends BaseComplicationProviderService { if (dataType == ComplicationData.TYPE_SHORT_TEXT) { final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(raw.sCOB2)) + .setShortText(ComplicationText.plainText(raw.getStatus().getCob())) .setIcon( Icon.createWithResource( this, R.drawable.ic_carbs)) diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java index 62109b1dfc..411b1e943b 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java @@ -18,8 +18,8 @@ public class CobIobComplication extends BaseComplicationProviderService { 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 String cob = raw.getStatus().getCob(); + final String iob = new SmallestDoubleString(raw.getStatus().getIobSum(), SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT); final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) .setShortText(ComplicationText.plainText(cob)) diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java index ce76524fb9..632ac70c05 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java @@ -20,7 +20,7 @@ public class IobIconComplication extends BaseComplicationProviderService { 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 String iob = new SmallestDoubleString(raw.getStatus().getIobSum(), SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT); final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) .setShortText(ComplicationText.plainText(iob)) diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java index d09a58a7ea..62d08ad8ba 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java @@ -32,7 +32,8 @@ public class SgvComplication extends BaseComplicationProviderService { 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")) + .setShortText(ComplicationText.plainText(raw.getSingleBg().getSgvString() + raw.getSingleBg().getSlopeArrow() + + "\uFE0E")) .setShortTitle(ComplicationText.plainText(displayFormat.shortTrend(raw))) .setTapAction(complicationPendingIntent); diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java similarity index 95% rename from wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java rename to wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java index 10f214ee33..6211641bb8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java @@ -14,7 +14,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ -public class UploaderBattery extends BaseComplicationProviderService { +public class UploaderBatteryComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { @@ -25,9 +25,9 @@ public class UploaderBattery extends BaseComplicationProviderService { int level = 0; String levelStr = "???"; - if (raw.sUploaderBattery.matches("^[0-9]+$")) { + if (raw.getStatus().getBattery().matches("^[0-9]+$")) { try { - level = Integer.parseInt(raw.sUploaderBattery); + level = Integer.parseInt(raw.getStatus().getBattery()); level = Math.max(Math.min(level, 100), 0); levelStr = level + "%"; int iconNo = (int) Math.floor(level / 10.0); @@ -112,7 +112,7 @@ public class UploaderBattery extends BaseComplicationProviderService { } catch (NumberFormatException ex) { - aapsLogger.error(LTag.WEAR, "Cannot parse battery level of: " + raw.sUploaderBattery); + aapsLogger.error(LTag.WEAR, "Cannot parse battery level of: " + raw.getStatus().getBattery()); } } @@ -147,7 +147,7 @@ public class UploaderBattery extends BaseComplicationProviderService { @Override public String getProviderCanonicalName() { - return UploaderBattery.class.getCanonicalName(); + return UploaderBatteryComplication.class.getCanonicalName(); } @Override 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/DataLayerListenerService.kt b/wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt deleted file mode 100644 index 7cf6bb7840..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/DataLayerListenerService.kt +++ /dev/null @@ -1,552 +0,0 @@ -/* - * Copyright 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -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.os.Build -import android.os.Bundle -import android.os.Handler -import android.os.HandlerThread -import android.os.SystemClock -import android.util.Base64 -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.tasks.Tasks -import com.google.android.gms.wearable.* -import dagger.android.AndroidInjection -import info.nightscout.androidaps.R -import info.nightscout.androidaps.events.EventWearToMobileAction -import info.nightscout.androidaps.events.EventWearToMobileChange -import info.nightscout.androidaps.events.EventWearToMobileConfirm -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.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.SafeParse.stringToInt -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.shared.logging.LTag -import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.shared.weardata.ActionData -import info.nightscout.shared.weardata.WearConstants -import info.nightscout.shared.weardata.WearConstants.Companion.KEY_ACTION_DATA -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 DataLayerListenerService : 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 - @Inject lateinit var wearConstants: WearConstants - - 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() - - override fun onCreate() { - AndroidInjection.inject(this) - super.onCreate() - handler.post { updateTranscriptionCapability() } - disposable += rxBus - .toObservable(EventWearToMobileAction::class.java) - .observeOn(aapsSchedulers.io) - .subscribe { sendMessage(wearConstants.W_M_INITIATE_ACTION, it.actionData.serialize().toByteArray()) } - disposable += rxBus - .toObservable(EventWearToMobileConfirm::class.java) - .observeOn(aapsSchedulers.io) - .subscribe { - NotificationManagerCompat.from(this).cancel(CONFIRM_NOTIF_ID) - sendMessage(wearConstants.W_M_CONFIRM_ACTION, it.actionData.serialize().toByteArray()) - } - disposable += rxBus - .toObservable(EventWearToMobileChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe { - NotificationManagerCompat.from(this).cancel(CHANGE_NOTIF_ID) - sendMessage(wearConstants.W_M_CONFIRM_ACTION, it.actionData.serialize().toByteArray()) - } - } - - 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 { - when (path) { - wearConstants.M_W_BOLUS_PROGRESS -> { - val progress = DataMapItem.fromDataItem(event.dataItem).dataMap.getInt("progresspercent", 0) - val status = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("progressstatus", "") - showBolusProgress(progress, status) - } - // remove when finished -> converted to message - wearConstants.M_W_ACTION_CONFIRMATION_REQUEST -> { - val title = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("title") ?: return@forEach - val message = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("message") ?: return@forEach - val actionstring = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("actionstring") ?: return@forEach - if ("opencpp" == title && actionstring.startsWith("opencpp")) { - val act = actionstring.split("\\s+").toTypedArray() - startActivity(Intent(this@DataLayerListenerService, CPPActivity::class.java).also { intent -> - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - intent.putExtras(Bundle().also { - it.putInt("percentage", stringToInt(act[1])) - it.putInt("timeshift", stringToInt(act[2])) - }) - }) - } else { - showConfirmationDialog(title, message, actionstring) - } - } - - wearConstants.M_W_STATUS -> { - val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap - val messageIntent = Intent() - messageIntent.action = Intent.ACTION_SEND - messageIntent.putExtra("status", dataMap.toBundle()) - persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMap) - LocalBroadcastManager.getInstance(this@DataLayerListenerService).sendBroadcast(messageIntent) - } - - wearConstants.M_W_BASAL -> { - val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap - val messageIntent = Intent() - messageIntent.action = Intent.ACTION_SEND - messageIntent.putExtra("basals", dataMap.toBundle()) - persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMap) - LocalBroadcastManager.getInstance(this@DataLayerListenerService).sendBroadcast(messageIntent) - } - - wearConstants.M_W_PREFERENCES -> { - val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap - val keyControl = getString(R.string.key_wear_control) - if (dataMap.containsKey(keyControl)) { - val previousWearControl = sp.getBoolean(keyControl, false) - val wearControl: Boolean = dataMap.getBoolean(keyControl, false) - sp.putBoolean(keyControl, wearControl) - if (wearControl != previousWearControl) { - updateTiles() - } - } - val keyPercentage = getString(R.string.key_boluswizard_percentage) - if (dataMap.containsKey(keyPercentage)) { - val wpercentage: Int = dataMap.getInt(keyPercentage, 100) - sp.putInt(keyPercentage, wpercentage) - } - val keyUnits = getString(R.string.key_units_mgdl) - if (dataMap.containsKey(keyUnits)) { - val mgdl: Boolean = dataMap.getBoolean(keyUnits, true) - sp.putBoolean(keyUnits, mgdl) - } - val keyMaxCarbs = getString(R.string.key_treatmentssafety_maxcarbs) - if (dataMap.containsKey(keyMaxCarbs)) { - val maxCarbs: Int = dataMap.getInt(keyMaxCarbs, 48) - sp.putInt(keyMaxCarbs, maxCarbs) - } - val keyMaxBolus = getString(R.string.key_treatmentssafety_maxbolus) - if (dataMap.containsKey(keyMaxBolus)) { - sp.putDouble(keyMaxBolus, dataMap.getDouble(keyMaxBolus, 3.0)) - } - } - - wearConstants.M_W_QUICK_WIZARD -> { - val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap - aapsLogger.info(LTag.WEAR, "onDataChanged: QUICK_WIZARD_PATH$dataMap") - dataMap.remove("timestamp") - val key = getString(R.string.key_quick_wizard_data_map) - val dataString = Base64.encodeToString(dataMap.toByteArray(), Base64.DEFAULT) - if (dataString != sp.getString(key, "")) { - sp.putString(key, dataString) - // Todo maybe add debounce function, due to 20 seconds update limit? - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - TileService.getUpdater(this@DataLayerListenerService).requestUpdate(QuickWizardTileService::class.java) - } - aapsLogger.info(LTag.WEAR, "onDataChanged: updated QUICK_WIZARD") - } else { - aapsLogger.info(LTag.WEAR, "onDataChanged: ignore update") - } - } - - wearConstants.M_W_ACTION_CHANGE_CONFIRMATION_REQUEST -> { - val title = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("title") ?: return@forEach - val message = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("message") ?: return@forEach - val actionstring = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("actionstring") ?: return@forEach - notifyChangeRequest(title, message, actionstring) - } - - wearConstants.M_W_ACTION_CANCEL_NOTIFICATION_REQUEST -> { - //val actionstring = DataMapItem.fromDataItem(event.getDataItem()).dataMap.getString("actionstring") ?: return@forEach - cancelNotificationRequest() - } - - wearConstants.M_W_DATA -> { - val dataMap = DataMapItem.fromDataItem(event.dataItem).dataMap - val messageIntent = Intent() - messageIntent.action = Intent.ACTION_SEND - messageIntent.putExtra("data", dataMap.toBundle()) - persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMap) - LocalBroadcastManager.getInstance(this@DataLayerListenerService).sendBroadcast(messageIntent) - } - } - } catch (exception: Exception) { - aapsLogger.error(LTag.WEAR, "onDataChanged failed", exception) - } - } - } - super.onDataChanged(dataEvents) - } - - override fun onMessageReceived(messageEvent: MessageEvent) { - super.onMessageReceived(messageEvent) - aapsLogger.debug(LTag.WEAR, "onMessageReceived: $messageEvent") - - when (messageEvent.path) { - wearConstants.M_W_PING -> sendMessage(wearConstants.W_M_PONG, byteArrayOf()) - wearConstants.M_W_OPEN_SETTINGS -> startActivity(Intent(this@DataLayerListenerService, AAPSPreferences::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) - - wearConstants.M_W_ACTION_CONFIRMATION_REQUEST -> { - val command = ActionData.deserialize(String(messageEvent.data)) as ActionData.ConfirmAction - if (command.originalCommand is ActionData.OpenProfileSwitch) { - val originalCommand = command.originalCommand as ActionData.OpenProfileSwitch - startActivity(Intent(this, CPPActivity::class.java).also { intent -> - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - intent.putExtras(Bundle().also { - it.putInt("percentage", originalCommand.percentage) - it.putInt("timeshift", originalCommand.timeShift) - }) - }) - } else { - startActivity( - Intent(this, AcceptActivity::class.java).also { intent -> - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - intent.putExtras( - Bundle().also { bundle -> - bundle.putString("title", command.title) - bundle.putString("message", command.message) - bundle.putString(KEY_ACTION_DATA, command.originalCommand.serialize()) - } - ) - }) - } - } - } - } - - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - when (intent?.action) { - ACTION_RESEND -> sendMessage(wearConstants.W_M_RESEND_DATA, byteArrayOf()) - - ACTION_CANCEL_BOLUS -> { - //dismiss notification - val notificationManager = NotificationManagerCompat.from(this) - notificationManager.cancel(BOLUS_PROGRESS_NOTIF_ID) - //send cancel-request to phone. - sendMessage(wearConstants.W_M_CANCEL_BOLUS, byteArrayOf()) - } - - ACTION_CONFIRMATION -> { - //dismiss notification - val notificationManager = NotificationManagerCompat.from(this) - notificationManager.cancel(CONFIRM_NOTIF_ID) - intent.getStringExtra("actionstring")?.let { actionString -> - sendMessage(wearConstants.W_M_CONFIRM_ACTION, actionString.toByteArray()) - } - } - - ACTION_CONFIRM_CHANGE -> { - //dismiss notification - val notificationManager = NotificationManagerCompat.from(this) - notificationManager.cancel(CHANGE_NOTIF_ID) - intent.getStringExtra("actionstring")?.let { actionString -> - sendMessage(wearConstants.W_M_CONFIRM_ACTION, actionString.toByteArray()) - } - } - - ACTION_INITIATE_ACTION -> - if (intent.hasExtra("actionstring")) - intent.getStringExtra("actionstring")?.let { actionString -> - sendMessage(wearConstants.W_M_INITIATE_ACTION, actionString.toByteArray()) - } - else if (intent.hasExtra(KEY_ACTION_DATA)) - intent.getStringExtra(KEY_ACTION_DATA)?.let { actionData -> - sendMessage(wearConstants.W_M_INITIATE_ACTION, actionData.toByteArray()) - } - } - 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 + ")" }}") - transcriptionNodeId = pickBestNodeId(capabilityInfo.nodes) - 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 - - 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: 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") - } - } - } - } - - private fun updateTiles() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - TileService.getUpdater(this) - .requestUpdate(ActionsTileService::class.java) - TileService.getUpdater(this) - .requestUpdate(TempTargetTileService::class.java) - TileService.getUpdater(this) - .requestUpdate(QuickWizardTileService::class.java) - } - } - - private fun notifyChangeRequest(title: String, message: String, actionstring: String) { - // 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(AAPS_NOTIFY_CHANNEL_ID_OPENLOOP, 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 - val notificationManager = getSystemService(NotificationManager::class.java) - notificationManager.createNotificationChannel(channel) - } - var builder = NotificationCompat.Builder(this, AAPS_NOTIFY_CHANNEL_ID_OPENLOOP) - builder = builder.setSmallIcon(R.drawable.notif_icon) - .setContentTitle(title) - .setContentText(message) - .setPriority(Notification.PRIORITY_HIGH) - .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000)) - - // Creates an explicit intent for an Activity in your app - val intent = Intent(this, AcceptActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - val params = Bundle() - params.putString("title", title) - params.putString("message", message) - params.putString("actionstring", actionstring) - intent.putExtras(params) - val resultPendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - builder = builder.setContentIntent(resultPendingIntent) - val mNotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager - // mId allows you to update the notification later on. - mNotificationManager.notify(CHANGE_NOTIF_ID, builder.build()) - } - - private fun cancelNotificationRequest() { - (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).cancel(CHANGE_NOTIF_ID) - } - - private fun showBolusProgress(progressPercent: Int, progresStatus: String) { - 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(this, DataLayerListenerService::class.java) - cancelIntent.action = ACTION_CANCEL_BOLUS - val cancelPendingIntent = PendingIntent.getService(this, 0, cancelIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) - val notificationBuilder: NotificationCompat.Builder = - NotificationCompat.Builder(this, if (vibrate) AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS else 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) - val 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 fun createBolusProgressChannels() { - createNotificationChannel( - longArrayOf(0, 50, 1000), - AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS, - getString(R.string.bolus_progress_channel_name), - getString(R.string.bolus_progress_channel_description) - ) - createNotificationChannel( - longArrayOf(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 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 - val notificationManager = getSystemService(NotificationManager::class.java) - notificationManager.createNotificationChannel(channel) - } - - private fun showConfirmationDialog(title: String, message: String, actionstring: String) { - val intent = Intent(this, AcceptActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - val params = Bundle() - params.putString("title", title) - params.putString("message", message) - params.putString("actionstring", actionstring) - intent.putExtras(params) - startActivity(intent) - } - - @Suppress("SameParameterValue") - private fun scheduleDismissBolusProgress(seconds: Int) { - Thread { - SystemClock.sleep(seconds * 1000L) - NotificationManagerCompat.from(this@DataLayerListenerService) - .cancel(BOLUS_PROGRESS_NOTIF_ID) - }.start() - } - - companion object { - - const val PHONE_CAPABILITY = "androidaps_mobile" - - const val ACTION_RESEND = "com.dexdrip.stephenblack.nightwatch.RESEND_DATA" - const val ACTION_CANCEL_BOLUS = "com.dexdrip.stephenblack.nightwatch.CANCELBOLUS" - const val ACTION_CONFIRMATION = "com.dexdrip.stephenblack.nightwatch.CONFIRMACTION" - const val ACTION_CONFIRM_CHANGE = "com.dexdrip.stephenblack.nightwatch.CONFIRMCHANGE" - val ACTION_INITIATE_ACTION = DataLayerListenerService::class.java.name + ".INITIATE_ACTION" - - 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_OPENLOOP = "AndroidAPS-OpenLoop" - const val AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS = "bolus progress vibration" - const val AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT = "bolus progress silent" - - fun initiateAction(context: Context, actionstring: String) { - context.startService( - Intent(context, DataLayerListenerService::class.java).also { - it.putExtra("actionstring", actionstring) - it.action = ACTION_INITIATE_ACTION - }) - } - - fun requestData(context: Context) { - context.startService( - Intent(context, DataLayerListenerService::class.java).also { it.action = ACTION_RESEND }) - } - - fun confirmAction(context: Context, actionstring: String) { - context.startService( - Intent(context, DataLayerListenerService::class.java).also { - it.putExtra("actionstring", actionstring) - if (actionstring == "changeRequest") it.action = ACTION_CONFIRM_CHANGE - else it.action = ACTION_CONFIRMATION - }) - } - } -} 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 a13c347a10..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) { - 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..ece27dee0d --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt @@ -0,0 +1,95 @@ +package info.nightscout.androidaps.data + +import android.content.Intent +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear +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 + */ +class RawDisplayData { + + // bg data bundle + var singleBg = EventData.SingleBg( + timeStamp = 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 + ) + + // basals bundle + 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 } + } + + /* + * Since complications do not need Basals, we skip them for performance + */ + fun updateForComplicationsFromPersistence(persistence: Persistence) { + persistence.readSingleBg()?.let { singleBg = it } + persistence.readGraphData()?.let { graphData = it } + persistence.readStatus()?.let { status = it } + } + + fun updateFromMessage(intent: Intent) { + intent.getStringExtra(DataLayerListenerServiceWear.KEY_SINGLE_BG_DATA)?.let{ + singleBg = EventData.deserialize(it) as EventData.SingleBg + } + intent.getStringExtra(DataLayerListenerServiceWear.KEY_STATUS_DATA)?.let{ + status = EventData.deserialize(it) as EventData.Status + } + intent.getStringExtra(DataLayerListenerServiceWear.KEY_TREATMENTS_DATA)?.let{ + treatmentData = EventData.deserialize(it) as EventData.TreatmentData + } + intent.getStringExtra(DataLayerListenerServiceWear.KEY_GRAPH_DATA)?.let{ + graphData = EventData.deserialize(it) as EventData.GraphData + } + } + + companion object { + + const val BG_DATA_PERSISTENCE_KEY = "raw_data" + const val GRAPH_DATA_PERSISTENCE_KEY = "raw_data" + const val BASALS_PERSISTENCE_KEY = "raw_basals" + const val STATUS_PERSISTENCE_KEY = "raw_status" + } +} \ 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 index 253935147e..90ef38717e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt @@ -3,6 +3,10 @@ package info.nightscout.androidaps.di import dagger.Module import dagger.android.ContributesAndroidInjector 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") @@ -20,4 +24,9 @@ abstract class WearActivitiesModule { @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/WearServicesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt index de47454131..800aa4205a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt @@ -2,16 +2,18 @@ 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.DataLayerListenerService -import info.nightscout.androidaps.interaction.actions.BackgroundActionActivity +import info.nightscout.androidaps.tile.QuickWizardTileService +import info.nightscout.androidaps.tile.TempTargetTileService +import info.nightscout.androidaps.tile.TileBase import info.nightscout.androidaps.watchfaces.* @Module @Suppress("unused") abstract class WearServicesModule { - @ContributesAndroidInjector abstract fun contributesDataLayerListenerService(): DataLayerListenerService + @ContributesAndroidInjector abstract fun contributesDataLayerListenerService(): DataLayerListenerServiceWear @ContributesAndroidInjector abstract fun contributesBaseComplicationProviderService(): BaseComplicationProviderService @ContributesAndroidInjector abstract fun contributesBrCobIobComplication(): BrCobIobComplication @@ -24,7 +26,7 @@ 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 @@ -34,4 +36,12 @@ abstract class WearServicesModule { @ContributesAndroidInjector abstract fun contributesSteampunk(): Steampunk @ContributesAndroidInjector abstract fun contributesDigitalStyle(): DigitalStyle @ContributesAndroidInjector abstract fun contributesCockpit(): Cockpit + + @ContributesAndroidInjector abstract fun contributesBIGChart(): BIGChart + @ContributesAndroidInjector abstract fun contributesNOChart(): NOChart + @ContributesAndroidInjector abstract fun contributesCircleWatchface(): CircleWatchface + + @ContributesAndroidInjector abstract fun contributesTileBase(): TileBase + @ContributesAndroidInjector abstract fun contributesQuickWizardTileService(): QuickWizardTileService + @ContributesAndroidInjector abstract fun contributesTempTargetTileService(): TempTargetTileService } \ 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/actions/AcceptActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java index 413bf0ee26..a5feccda80 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java @@ -1,6 +1,6 @@ package info.nightscout.androidaps.interaction.actions; -import static info.nightscout.shared.weardata.WearConstants.KEY_ACTION_DATA; +import static info.nightscout.androidaps.comm.DataLayerListenerServiceWear.KEY_ACTION_DATA; import android.content.Context; import android.content.Intent; @@ -21,10 +21,8 @@ import androidx.core.view.MotionEventCompat; import androidx.core.view.ViewConfigurationCompat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; -import info.nightscout.androidaps.events.EventWearToMobileChange; -import info.nightscout.androidaps.events.EventWearToMobileConfirm; -import info.nightscout.shared.weardata.ActionData; +import info.nightscout.androidaps.events.EventWearToMobile; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 09/02/17. @@ -33,7 +31,6 @@ import info.nightscout.shared.weardata.ActionData; public class AcceptActivity extends ViewSelectorActivity { String message = ""; - String actionstring = ""; String actionKey = ""; private DismissThread dismissThread; @@ -46,10 +43,9 @@ public class AcceptActivity extends ViewSelectorActivity { Bundle extras = getIntent().getExtras(); message = extras.getString("message", ""); - actionstring = extras.getString("actionstring", ""); actionKey = extras.getString(KEY_ACTION_DATA, ""); - if (message.isEmpty() || (actionstring.isEmpty() && actionKey.isEmpty())) { + if (message.isEmpty() || actionKey.isEmpty()) { finish(); return; } @@ -109,15 +105,9 @@ public class AcceptActivity extends ViewSelectorActivity { 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 (!actionstring.isEmpty()) - DataLayerListenerService.Companion.confirmAction(AcceptActivity.this, actionstring); - else { - ActionData actionData = ActionData.Companion.deserialize(actionKey); - if (actionData instanceof ActionData.ConfirmAction) - rxBus.send(new EventWearToMobileConfirm(actionData)); - if (actionData instanceof ActionData.ChangeAction) - rxBus.send(new EventWearToMobileChange(actionData)); - } + EventData returnCommand = EventData.Companion.deserialize(actionKey); + rxBus.send(new EventWearToMobile(returnCommand)); + rxBus.send(new EventData.CancelNotification(System.currentTimeMillis())); finishAffinity(); }); container.addView(view); 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 4d0ecbc0a9..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 @@ -3,21 +3,25 @@ package info.nightscout.androidaps.interaction.actions import android.os.Bundle import android.widget.Toast import dagger.android.DaggerActivity -import info.nightscout.androidaps.data.DataLayerListenerService +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 class BackgroundActionActivity : DaggerActivity() { @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBus override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - intent.extras?.getString("actionString")?.let { actionString -> - aapsLogger.info(LTag.WEAR, "QuickWizardActivity.onCreate: actionString=$actionString") - DataLayerListenerService.initiateAction(this, actionString) - intent.extras?.getString("message")?.let { message -> + 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() } } ?: aapsLogger.error(LTag.WEAR, "BackgroundActionActivity.onCreate extras 'actionString' required") 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 index 55109a352f..372330ca7f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java @@ -10,10 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventWearToMobileAction; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.ActionData; +import info.nightscout.shared.weardata.EventData; public class BolusActivity extends ViewSelectorActivity { @@ -63,8 +63,7 @@ public class BolusActivity extends ViewSelectorActivity { view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); final ImageView confirmButton = view.findViewById(R.id.confirmbutton); confirmButton.setOnClickListener((View v) -> { - ActionData.Bolus bolus = new ActionData.Bolus(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), 0); - rxBus.send(new EventWearToMobileAction(bolus)); + rxBus.send(new EventWearToMobile(new EventData.ActionBolusPreCheck(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), 0))); showToast(BolusActivity.this, R.string.action_bolus_confirmation); finishAffinity(); }); 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 index dde240c015..c0b6cedb33 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java @@ -10,11 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; -import info.nightscout.androidaps.events.EventWearToMobileAction; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.ActionData; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 09/02/17. @@ -52,6 +51,7 @@ public class CPPActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -94,9 +94,9 @@ public class CPPActivity extends ViewSelectorActivity { confirmButton.setOnClickListener((View v) -> { //check if it can happen that the fragment is never created that hold data? // (you have to swipe past them anyways - but still) - ActionData.ProfileSwitch ps = - new ActionData.ProfileSwitch(SafeParse.stringToInt(editTimeshift.editText.getText().toString()), SafeParse.stringToInt(editPercentage.editText.getText().toString())); - rxBus.send(new EventWearToMobileAction(ps)); + EventData.ActionProfileSwitchPreCheck ps = + new EventData.ActionProfileSwitchPreCheck(SafeParse.stringToInt(editTimeshift.editText.getText().toString()), SafeParse.stringToInt(editPercentage.editText.getText().toString())); + rxBus.send(new EventWearToMobile(ps)); showToast(CPPActivity.this, R.string.action_cpp_confirmation); finishAffinity(); }); @@ -108,7 +108,7 @@ public class CPPActivity extends ViewSelectorActivity { @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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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 index d9c9298236..fe6f9c6767 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java @@ -10,9 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.EventData; public class CarbActivity extends ViewSelectorActivity { @@ -32,6 +33,7 @@ public class CarbActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -46,37 +48,42 @@ public class CarbActivity extends ViewSelectorActivity { @Override public Object instantiateItem(ViewGroup container, int row, int col) { + final View view; if (col == 0) { - final View view = getInflatedPlusMinusView(container); + 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); + 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) -> { + 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"; - DataLayerListenerService.Companion.initiateAction(CarbActivity.this, actionstring); + EventData.ActionECarbsPreCheck bolus = + new EventData.ActionECarbsPreCheck( + SafeParse.stringToInt(editCarbs.editText.getText().toString()), + 0, + 0 + ); + rxBus.send(new EventWearToMobile(bolus)); showToast(CarbActivity.this, R.string.action_ecarb_confirmation); finishAffinity(); }); container.addView(view); - return 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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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 index cc36635961..3b8f548c59 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java @@ -10,9 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 04/08/18. @@ -38,6 +39,7 @@ public class ECarbActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -86,16 +88,19 @@ public class ECarbActivity extends ViewSelectorActivity { } 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) -> { + final ImageView confirmButton = view.findViewById(R.id.confirmbutton); + confirmButton.setOnClickListener((View v) -> { //check if it can happen that the fragment 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()); - DataLayerListenerService.Companion.initiateAction(ECarbActivity.this, actionstring); + EventData.ActionECarbsPreCheck bolus = + new EventData.ActionECarbsPreCheck( + SafeParse.stringToInt(editCarbs.editText.getText().toString()), + SafeParse.stringToInt(editStartTime.editText.getText().toString()), + SafeParse.stringToInt(editDuration.editText.getText().toString()) + ); + rxBus.send(new EventWearToMobile(bolus)); showToast(ECarbActivity.this, R.string.action_ecarb_confirmation); finishAffinity(); @@ -108,7 +113,7 @@ public class ECarbActivity extends ViewSelectorActivity { @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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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 index 28493146ca..c7cbb892ce 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java @@ -10,9 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 09/02/17. @@ -34,6 +35,7 @@ public class FillActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -67,8 +69,7 @@ public class FillActivity extends ViewSelectorActivity { //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()); - DataLayerListenerService.Companion.initiateAction(FillActivity.this, actionstring); + rxBus.send(new EventWearToMobile(new EventData.ActionFillPreCheck(SafeParse.stringToDouble(editInsulin.editText.getText().toString())))); showToast(FillActivity.this, R.string.action_fill_confirmation); finishAffinity(); }); 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 index 4bab152cb5..22cb47811f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java @@ -10,9 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 09/02/17. @@ -42,6 +43,7 @@ public class TempTargetActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -112,18 +114,20 @@ public class TempTargetActivity extends ViewSelectorActivity { } 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? + final ImageView confirmButton = view.findViewById(R.id.confirmbutton); + confirmButton.setOnClickListener((View v) -> { + //check if it can happen that the fragment 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())); - - DataLayerListenerService.Companion.initiateAction(TempTargetActivity.this, actionstring); + EventData.ActionTempTargetPreCheck action = new EventData.ActionTempTargetPreCheck( + EventData.ActionTempTargetPreCheck.TempTargetCommand.MANUAL, + 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())) + ); + rxBus.send(new EventWearToMobile(action)); showToast(TempTargetActivity.this, R.string.action_tempt_confirmation); finishAffinity(); }); @@ -135,7 +139,7 @@ public class TempTargetActivity extends ViewSelectorActivity { @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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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 index 2b0f0dd4a6..fa353128ba 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java @@ -10,11 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; -import info.nightscout.androidaps.events.EventWearToMobileAction; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.ActionData; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 09/02/17. @@ -42,6 +41,7 @@ public class TreatmentActivity extends ViewSelectorActivity { } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -80,12 +80,12 @@ public class TreatmentActivity extends ViewSelectorActivity { } 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) -> { + final ImageView confirmButton = view.findViewById(R.id.confirmbutton); + confirmButton.setOnClickListener((View v) -> { //check if it can happen that the fragment is never created that hold data? // (you have to swipe past them anyways - but still) - ActionData.Bolus bolus = new ActionData.Bolus(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), SafeParse.stringToInt(editCarbs.editText.getText().toString())); - rxBus.send(new EventWearToMobileAction(bolus)); + EventData.ActionBolusPreCheck bolus = new EventData.ActionBolusPreCheck(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), SafeParse.stringToInt(editCarbs.editText.getText().toString())); + rxBus.send(new EventWearToMobile(bolus)); showToast(TreatmentActivity.this, R.string.action_treatment_confirmation); finishAffinity(); }); @@ -97,7 +97,7 @@ public class TreatmentActivity extends ViewSelectorActivity { @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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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 index ac2ecb30fe..698c3fc59d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java @@ -10,9 +10,10 @@ import android.widget.ImageView; import java.text.DecimalFormat; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.EventData; /** * Created by adrian on 09/02/17. @@ -42,6 +43,7 @@ public class WizardActivity extends ViewSelectorActivity { finish(); } + @SuppressWarnings("deprecation") private class MyGridViewPagerAdapter extends GridPagerAdapter { @Override public int getColumnCount(int arg0) { @@ -82,15 +84,17 @@ public class WizardActivity extends ViewSelectorActivity { } 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) -> { + 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; - DataLayerListenerService.Companion.initiateAction(WizardActivity.this, actionstring); + EventData.ActionWizardPreCheck action = new EventData.ActionWizardPreCheck( + SafeParse.stringToInt(editCarbs.editText.getText().toString()), + percentage + ); + rxBus.send(new EventWearToMobile(action)); showToast(WizardActivity.this, R.string.action_wizard_confirmation); finishAffinity(); }); @@ -102,7 +106,7 @@ public class WizardActivity extends ViewSelectorActivity { @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? + // Object should still be kept by this, just setup for re-init? container.removeView((View) view); } 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 f11c887130..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.DataLayerListenerService; -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)) { - DataLayerListenerService.Companion.initiateAction(this, "fillpreset 1"); - } else if (getString(R.string.action_preset_2).equals(action)) { - DataLayerListenerService.Companion.initiateAction(this, "fillpreset 2"); - } else if (getString(R.string.action_preset_3).equals(action)) { - DataLayerListenerService.Companion.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 92f82f5920..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.DataLayerListenerService; -import info.nightscout.androidaps.interaction.AAPSPreferences; -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; - -/** - * 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); - DataLayerListenerService.Companion.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)) { - DataLayerListenerService.Companion.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..4f37ea33dd --- /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.AAPSPreferences +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_cpp))) + 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, AAPSPreferences::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_resync) -> rxBus.send(EventWearToMobile(ActionResendData("Re-Sync"))) + getString(R.string.status_cpp) -> 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 6f9c5586c8..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.DataLayerListenerService; -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)) { - DataLayerListenerService.Companion.initiateAction(this, "status pump"); - } else if (getString(R.string.status_loop).equals(action)) { - DataLayerListenerService.Companion.initiateAction(this, "status loop"); - } else if (getString(R.string.status_cpp).equals(action)) { - DataLayerListenerService.Companion.initiateAction(this, "opencpp"); - } else if (getString(R.string.status_tdd).equals(action)) { - DataLayerListenerService.Companion.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/DisplayFormat.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java index bbdfa0aa04..966b921db5 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 @@ -65,27 +65,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,40 +95,41 @@ 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) { @@ -144,7 +145,7 @@ public class DisplayFormat { } 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) { 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/Persistence.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java index afb2b42bd2..a0856395d9 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java @@ -3,22 +3,20 @@ 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.androidaps.data.RawDisplayData; import info.nightscout.shared.logging.AAPSLogger; import info.nightscout.shared.logging.LTag; +import info.nightscout.shared.weardata.EventData; /** * Created by dlvoy on 2019-11-12 @@ -26,7 +24,6 @@ import info.nightscout.shared.logging.LTag; @Singleton public class Persistence { - private final Context context; private final AAPSLogger aapsLogger; private final WearUtil wearUtil; private final SharedPreferences preferences; @@ -35,7 +32,6 @@ public class Persistence { @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); @@ -51,24 +47,6 @@ public class Persistence { 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); } @@ -109,11 +87,67 @@ public class Persistence { putString(key, joinSet(set, "|")); } - public void storeDataMap(String key, DataMap dataMap) { - putDataMap(key, dataMap); + public void store(EventData.SingleBg singleBg) { + putString(RawDisplayData.BG_DATA_PERSISTENCE_KEY, singleBg.serialize()); markDataUpdated(); } + @Nullable + public EventData.SingleBg readSingleBg() { + try { + String s = getString(RawDisplayData.BG_DATA_PERSISTENCE_KEY, null); + if (s != null) { + return (EventData.SingleBg) EventData.Companion.deserialize(s); + } + } catch (Exception ignored) {} + return null; + } + + @Nullable + public EventData.Status readStatus() { + try { + String s = getString(RawDisplayData.STATUS_PERSISTENCE_KEY, null); + if (s != null) { + return (EventData.Status) EventData.Companion.deserialize(s); + } + } catch (Exception ignored) {} + return null; + } + + @Nullable + public EventData.TreatmentData readTreatments() { + try { + String s = getString(RawDisplayData.BASALS_PERSISTENCE_KEY, null); + if (s != null) { + return (EventData.TreatmentData) EventData.Companion.deserialize(s); + } + } catch (Exception ignored) {} + return null; + } + + @Nullable + public EventData.GraphData readGraphData() { + try { + String s = getString(RawDisplayData.BG_DATA_PERSISTENCE_KEY, null); + if (s != null) { + return (EventData.GraphData) EventData.Companion.deserialize(s); + } + } catch (Exception ignored) {} + return null; + } + + public void store(EventData.GraphData graphData) { + putString(RawDisplayData.GRAPH_DATA_PERSISTENCE_KEY, graphData.serialize()); + } + + public void store(EventData.TreatmentData treatmentData) { + putString(RawDisplayData.BASALS_PERSISTENCE_KEY, treatmentData.serialize()); + } + + public void store(EventData.Status status) { + putString(RawDisplayData.STATUS_PERSISTENCE_KEY, status.serialize()); + } + public String joinSet(Set set, String separator) { StringBuilder sb = new StringBuilder(); int i = 0; 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..b03123076f 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,64 @@ 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.* object QuickWizardSource : TileSource { - override fun getSelectedActions(context: Context): List { + override fun getSelectedActions(context: Context, sp: SP, aapsLogger: AAPSLogger): 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(sp: SP): 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 +72,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/StaticTileSource.kt b/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt index c1f369275c..5f27d2e367 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt @@ -5,6 +5,9 @@ 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, @@ -12,9 +15,9 @@ class StaticAction( buttonTextSub: String? = null, activityClass: String, @DrawableRes iconRes: Int, - actionString: String? = null, + action: EventData? = null, message: String? = null, -) : Action(buttonText, buttonTextSub, activityClass, iconRes, actionString, message) +) : Action(buttonText, buttonTextSub, activityClass, iconRes, action, message) abstract class StaticTileSource : TileSource { @@ -23,7 +26,7 @@ abstract class StaticTileSource : TileSource { abstract val preferencePrefix: String abstract fun getDefaultConfig(): Map - override fun getSelectedActions(context: Context): List { + override fun getSelectedActions(context: Context, sp: SP, aapsLogger: AAPSLogger): List { val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context) setDefaultSettings(sharedPrefs) @@ -40,7 +43,7 @@ abstract class StaticTileSource : TileSource { return actionList } - override fun getValidFor(context: Context): Long? = null + override fun getValidFor(sp: SP): Long? = null private fun getActionFromPreference(resources: Resources, sharedPrefs: SharedPreferences, index: Int): Action? { val actionPref = sharedPrefs.getString(preferencePrefix + index, "none") 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..48c39de5de 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetSource.kt @@ -4,6 +4,7 @@ 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.weardata.EventData object TempTargetSource : StaticTileSource() { @@ -19,7 +20,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 +30,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 +40,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 +56,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/TileBase.kt b/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt index 031dbf223e..7fd3cbf5c9 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt @@ -5,11 +5,10 @@ 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 +28,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 +49,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(context: Context, sp: SP, aapsLogger: AAPSLogger): List + fun getValidFor(sp: SP): Long? } open class Action( @@ -53,7 +58,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 +68,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 +107,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(this, sp, aapsLogger) } private fun validFor(): Long? { - return source.getValidFor(this) + return source.getValidFor(sp) } @RequiresApi(Build.VERSION_CODES.N) @@ -172,13 +186,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 +211,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 +249,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 +261,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 +289,10 @@ abstract class TileBase : TileService() { } private fun getWearControl(): WearControl { - val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this) - if (!sharedPrefs.contains("wearcontrol")) { + if (!sp.contains("wearcontrol")) { return WearControl.NO_DATA } - val wearControlPref = sharedPrefs.getBoolean("wearcontrol", false) + val wearControlPref = sp.getBoolean("wearcontrol", false) if (wearControlPref) { return WearControl.ENABLED } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java index 618dc68998..cd56d3fd0a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java @@ -1,29 +1,18 @@ package info.nightscout.androidaps.watchfaces; -import android.content.BroadcastReceiver; +import android.annotation.SuppressLint; 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; @@ -32,7 +21,8 @@ import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.TextView; -import com.google.android.gms.wearable.DataMap; +import androidx.core.content.ContextCompat; + import com.ustwo.clockwise.common.WatchFaceTime; import com.ustwo.clockwise.common.WatchMode; import com.ustwo.clockwise.common.WatchShape; @@ -40,25 +30,43 @@ import com.ustwo.clockwise.wearable.WatchFace; import java.util.ArrayList; +import javax.inject.Inject; + +import dagger.android.AndroidInjection; 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.DataLayerListenerService; -import info.nightscout.androidaps.data.TempWatchData; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; +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 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; +@SuppressWarnings("deprecation") +public class BIGChart extends WatchFace { + + @Inject RxBus rxBus; + @Inject AapsSchedulers aapsSchedulers; + @Inject AAPSLogger aapsLogger; + @Inject SP sp; + + CompositeDisposable disposable = new CompositeDisposable(); + + private EventData.SingleBg singleBg; + private EventData.Status status; + private EventData.TreatmentData treatmentData; + private EventData.GraphData graphData; + + private static final int SCREEN_SIZE_SMALL = 280; + private TextView mTime, mSgv, mTimestamp, mDelta, mAvgDelta; + private RelativeLayout mRelativeLayout; + public int ageLevel = 1; public int highColor = Color.YELLOW; public int lowColor = Color.RED; @@ -73,36 +81,21 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre 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 ArrayList bgDataList = 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; + @SuppressLint("InflateParams") @Override public void onCreate() { + AndroidInjection.inject(this); super.onCreate(); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); @@ -113,17 +106,71 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre 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){ + if (metrics.widthPixels < SCREEN_SIZE_SMALL || metrics.heightPixels < SCREEN_SIZE_SMALL) { layoutView = inflater.inflate(R.layout.activity_bigchart_small, null); } else { layoutView = inflater.inflate(R.layout.activity_bigchart, null); } performViewSetup(); + disposable.add(rxBus + .toObservable(EventData.SingleBg.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + aapsLogger.debug(LTag.WEAR, "SingleBg received"); + singleBg = event; + + mSgv.setText(singleBg.getSgvString()); + 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())); + mDelta.setText(singleBg.getDelta()); + mAvgDelta.setText(singleBg.getAvgDelta()); + }) + ); + disposable.add(rxBus + .toObservable(EventData.TreatmentData.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> treatmentData = event) + ); + disposable.add(rxBus + .toObservable(EventData.GraphData.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> graphData = event) + ); + disposable.add(rxBus + .toObservable(EventData.Status.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received"); + status = event; + showAgeAndStatus(); + addToWatchSet(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), + mRelativeLayout.getMeasuredHeight()); + invalidate(); + setColor(); + }) + ); + disposable.add(rxBus + .toObservable(EventData.Preferences.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + setColor(); + if (layoutSet) { + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), + mRelativeLayout.getMeasuredHeight()); + } + invalidate(); + }) + ); } @Override @@ -134,54 +181,46 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre 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()); - } + stub.setOnLayoutInflatedListener(stub1 -> { + mTime = stub1.findViewById(R.id.watch_time); + mSgv = stub1.findViewById(R.id.sgv); + mTimestamp = stub1.findViewById(R.id.timestamp); + mDelta = stub1.findViewById(R.id.delta); + mAvgDelta = stub1.findViewById(R.id.avgdelta); + mRelativeLayout = stub1.findViewById(R.id.main_layout); + chart = stub1.findViewById(R.id.chart); + statusView = stub1.findViewById(R.id.aps_status); + layoutSet = true; + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), + mRelativeLayout.getMeasuredHeight()); }); - DataLayerListenerService.Companion.requestData(this); + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:performViewSetup"))); 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; + int extra = mSgv != null ? (mSgv.getRight() - mSgv.getLeft()) / 2 : 0; - if (tapType == TAP_TYPE_TAP&& - x >=chart.getLeft() && - x <= chart.getRight()&& + if (tapType == TAP_TYPE_TAP && + x >= chart.getLeft() && + x <= chart.getRight() && y >= chart.getTop() && - y <= chart.getBottom()){ - if (eventTime - chartTapTime < 800){ + y <= chart.getBottom()) { + if (eventTime - chartTapTime < 800) { changeChartTimeframe(); } chartTapTime = eventTime; - } else if (tapType == TAP_TYPE_TAP&& - x + extra >=mSgv.getLeft() && - x - extra <= mSgv.getRight()&& + } else if (tapType == TAP_TYPE_TAP && + x + extra >= mSgv.getLeft() && + x - extra <= mSgv.getRight() && y >= mSgv.getTop() && - y <= mSgv.getBottom()){ - if (eventTime - sgvTapTime < 800){ + y <= mSgv.getBottom()) { + if (eventTime - sgvTapTime < 800) { Intent intent = new Intent(this, MainMenuActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); @@ -191,17 +230,17 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - timeframe = (timeframe%5) + 1; - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); + int timeframe = sp.getInt("chart_timeframe", 3); + timeframe = (timeframe % 5) + 1; + sp.putInt("chart_timeframe", timeframe); } protected void onWatchModeChanged(WatchMode watchMode) { - if(lowResMode ^ isLowRes(watchMode)){ //if there was a change in lowResMode + if (lowResMode ^ isLowRes(watchMode)) { //if there was a change in lowResMode lowResMode = isLowRes(watchMode); setColor(); - } else if (! sharedPrefs.getBoolean("dark", true)){ + } else if (!sp.getBoolean("dark", true)) { //in bright mode: different colours if active: setColor(); } @@ -213,14 +252,13 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre @Override - protected WatchFaceStyle getWatchFaceStyle(){ + protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); } - public int ageLevel() { - if(timeSince() <= (1000 * 60 * 12)) { + if (timeSince() <= (1000 * 60 * 12)) { return 1; } else { return 0; @@ -228,40 +266,30 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } public double timeSince() { - return System.currentTimeMillis() - datetime; + return System.currentTimeMillis() - singleBg.getTimeStamp(); } 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"); + if (singleBg == null || singleBg.getTimeStamp() == 0) { + return shortString ? "--'" : "-- Minute ago"; } - return minutesAgo + (shortString?"'":" Minutes 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); - } + disposable.clear(); 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) { + if (layoutSet) { this.mRelativeLayout.draw(canvas); - Log.d("onDraw", "draw"); } } @@ -273,7 +301,7 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre mTime.setText(timeFormat.format(System.currentTimeMillis())); showAgeAndStatus(); - if(ageLevel()<=0) { + if (ageLevel() <= 0) { mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); @@ -286,173 +314,25 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } } - 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){ + if (mTimestamp != null) { mTimestamp.setText(readingAge(true)); } - boolean showStatus = sharedPrefs.getBoolean("showExternalStatus", true); - boolean showAvgDelta = sharedPrefs.getBoolean("showAvgDelta", true); + boolean showStatus = sp.getBoolean("showExternalStatus", true); + boolean showAvgDelta = sp.getBoolean("showAvgDelta", true); - if(showAvgDelta){ + 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; + if (showStatus && status != null) { + String status = this.status.getExternalStatus(); + if (sp.getBoolean("show_cob", true)) { + status += " " + this.status.getCob(); } statusView.setText(status); @@ -463,9 +343,9 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } public void setColor() { - if(lowResMode){ + if (lowResMode) { setColorLowRes(); - } else if (sharedPrefs.getBoolean("dark", true)) { + } else if (sp.getBoolean("dark", true)) { setColorDark(); } else { setColorBright(); @@ -473,66 +353,6 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } - - - @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)); @@ -555,40 +375,41 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre } 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 (singleBg != null) { + 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 (singleBg.getSgvLevel() == 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 (singleBg.getSgvLevel() == 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 (singleBg.getSgvLevel() == -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 (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(); + 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(); + } } - } @@ -598,15 +419,15 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre 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) { + if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == -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)); @@ -636,61 +457,36 @@ public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPre public void missedReadingAlert() { int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); if (minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - DataLayerListenerService.Companion.requestData(this); // attempt endTime recover missing data + // attempt endTime recover missing data + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:missedReadingAlert"))); } } - 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)); - } + public void addToWatchSet() { + if (graphData != null) { + bgDataList = graphData.getEntries(); } 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; - } + if (size > 0 && bgDataList.get(size - 1).getTimeStamp() == singleBg.getTimeStamp()) + return; // Ignore duplicates. + bgDataList.add(singleBg); } } 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 (bgDataList.size() > 0) { + int timeframe = sp.getInt("chart_timeframe", 3); if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); + bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), 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); + bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); } chart.setLineChartData(bgGraphBuilder.lineData()); chart.setViewportCalculationEnabled(true); chart.setMaximumViewport(chart.getMaximumViewport()); } else { - DataLayerListenerService.Companion.requestData(this); + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:setupCharts"))); } } } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java index 6765a751bb..8c44241e6b 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java @@ -4,7 +4,6 @@ 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; @@ -15,7 +14,6 @@ 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; @@ -28,15 +26,14 @@ 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.ArrayList; import java.util.Date; import java.util.Locale; @@ -44,12 +41,17 @@ import javax.inject.Inject; import dagger.android.AndroidInjection; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DataLayerListenerService; -import info.nightscout.androidaps.data.RawDisplayData; +import info.nightscout.androidaps.events.EventWearPreferenceChange; +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 lecho.lib.hellocharts.view.LineChartView; /** @@ -58,20 +60,27 @@ import lecho.lib.hellocharts.view.LineChartView; * Refactored by dlvoy on 2019-11-2019 */ -public abstract class BaseWatchFace extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { +public abstract class BaseWatchFace extends WatchFace { @Inject WearUtil wearUtil; @Inject Persistence persistence; @Inject AAPSLogger aapsLogger; + @Inject RxBus rxBus; + @Inject AapsSchedulers aapsSchedulers; + @Inject SP sp; - public final static IntentFilter INTENT_FILTER; + CompositeDisposable disposable = new CompositeDisposable(); - 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); - } + protected EventData.SingleBg singleBg = new EventData.SingleBg(0, "---", "-", "--", "--", "--" + , 0, 0.0, 0.0, 0.0, 0); + protected EventData.Status status = new EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1); + protected EventData.TreatmentData treatmentData = new EventData.TreatmentData( + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>() + ); + protected EventData.GraphData graphData = new EventData.GraphData(new ArrayList<>()); static IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); @@ -96,7 +105,6 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc public int pointSize = 2; public BgGraphBuilder bgGraphBuilder; public LineChartView chart; - public RawDisplayData rawData; public PowerManager.WakeLock wakeLock; // related endTime manual layout public View layoutView; @@ -104,9 +112,6 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc 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; @@ -126,7 +131,6 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc 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"); @@ -137,8 +141,49 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } else { specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY); } - sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - sharedPrefs.registerOnSharedPreferenceChangeListener(this); + + disposable.add(rxBus + .toObservable(EventWearPreferenceChange.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + setupBatteryReceiver(); + if (event.getChangedKey() != null && event.getChangedKey().equals("delta_granularity")) + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BaseWatchFace:onSharedPreferenceChanged"))); + if (layoutSet) setDataFields(); + invalidate(); + }) + ); + disposable.add(rxBus + .toObservable(EventData.SingleBg.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> singleBg = event) + ); + disposable.add(rxBus + .toObservable(EventData.TreatmentData.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> treatmentData = event) + ); + disposable.add(rxBus + .toObservable(EventData.GraphData.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> graphData = event) + ); + disposable.add(rxBus + .toObservable(EventData.Status.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + // this event is received as last batch of data + if (isSimpleUi()) { + if (needUpdate()) { + invalidate(); + } + } else { + setupCharts(); + setDataFields(); + invalidate(); + } + }) + ); persistence.turnOff(); @@ -148,7 +193,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } private void setupBatteryReceiver() { - String setting = sharedPrefs.getString("simplify_ui", "off"); + String setting = sp.getString("simplify_ui", "off"); if ((setting.equals("charging") || setting.equals("ambient_charging")) && batteryReceiver == null) { IntentFilter intentBatteryFilter = new IntentFilter(); intentBatteryFilter.addAction(BatteryManager.ACTION_CHARGING); @@ -215,11 +260,6 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc 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); @@ -274,11 +314,11 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } public double timeSince() { - return System.currentTimeMillis() - rawData.datetime; + return System.currentTimeMillis() - singleBg.getTimeStamp(); } public String readingAge(boolean shortString) { - if (rawData.datetime == 0) { + if (singleBg.getTimeStamp() == 0) { return shortString ? "--" : "-- Minute ago"; } int minutesAgo = (int) Math.floor(timeSince() / (1000 * 60)); @@ -290,12 +330,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc @Override public void onDestroy() { - if (localBroadcastManager != null && messageReceiver != null) { - localBroadcastManager.unregisterReceiver(messageReceiver); - } - if (sharedPrefs != null) { - sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - } + disposable.clear(); if (batteryReceiver != null) { unregisterReceiver(batteryReceiver); } @@ -326,16 +361,16 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc float xHalf = displaySize.x / 2f; float yThird = displaySize.y / 3f; - boolean isOutdated = rawData.datetime > 0 && ageLevel() <= 0; + boolean isOutdated = singleBg.getTimeStamp() > 0 && ageLevel() <= 0; mSvgPaint.setStrikeThruText(isOutdated); - mSvgPaint.setColor(getBgColour(rawData.sgvLevel)); - mDirectionPaint.setColor(getBgColour(rawData.sgvLevel)); + mSvgPaint.setColor(getBgColour(singleBg.getSgvLevel())); + mDirectionPaint.setColor(getBgColour(singleBg.getSgvLevel())); - String sSvg = rawData.sSgv; + String sSvg = singleBg.getSgvString(); float svgWidth = mSvgPaint.measureText(sSvg); - String sDirection = " " + rawData.sDirection + "\uFE0E"; + String sDirection = " " + singleBg.getSgvString() + "\uFE0E"; float directionWidth = mDirectionPaint.measureText(sDirection); float xSvg = xHalf - (svgWidth + directionWidth) / 2; @@ -382,7 +417,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } private void checkVibrateHourly(WatchFaceTime oldTime, WatchFaceTime newTime) { - boolean hourlyVibratePref = sharedPrefs.getBoolean("vibrate_Hourly", false); + boolean hourlyVibratePref = sp.getBoolean("vibrate_Hourly", false); if (hourlyVibratePref && layoutSet && newTime.hasHourChanged(oldTime)) { aapsLogger.info(LTag.WEAR, "hourlyVibratePref", "true --> " + newTime); Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); @@ -394,8 +429,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc public void setDataFields() { setDateAndTime(); if (mSgv != null) { - if (sharedPrefs.getBoolean("showBG", true)) { - mSgv.setText(rawData.sSgv); + if (sp.getBoolean("showBG", true)) { + mSgv.setText(singleBg.getSgvString()); mSgv.setVisibility(View.VISIBLE); } else { // Leave the textview there but invisible, as a height holder for the empty space above the white line @@ -407,8 +442,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc strikeThroughSgvIfNeeded(); if (mDirection != null) { - if (sharedPrefs.getBoolean("show_direction", true)) { - mDirection.setText(rawData.sDirection + "\uFE0E"); + if (sp.getBoolean("show_direction", true)) { + mDirection.setText(singleBg.getSgvString() + "\uFE0E"); mDirection.setVisibility(View.VISIBLE); } else { mDirection.setVisibility(View.GONE); @@ -416,8 +451,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mDelta != null) { - if (sharedPrefs.getBoolean("showDelta", true)) { - mDelta.setText(rawData.sDelta); + if (sp.getBoolean("showDelta", true)) { + mDelta.setText(singleBg.getDelta()); mDelta.setVisibility(View.VISIBLE); } else { mDelta.setVisibility(View.GONE); @@ -425,8 +460,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mAvgDelta != null) { - if (sharedPrefs.getBoolean("showAvgDelta", true)) { - mAvgDelta.setText(rawData.sAvgDelta); + if (sp.getBoolean("showAvgDelta", true)) { + mAvgDelta.setText(singleBg.getAvgDelta()); mAvgDelta.setVisibility(View.VISIBLE); } else { mAvgDelta.setVisibility(View.GONE); @@ -434,8 +469,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mCOB1 != null && mCOB2 != null) { - mCOB2.setText(rawData.sCOB2); - if (sharedPrefs.getBoolean("show_cob", true)) { + mCOB2.setText(status.getCob()); + if (sp.getBoolean("show_cob", true)) { mCOB1.setVisibility(View.VISIBLE); mCOB2.setVisibility(View.VISIBLE); } else { @@ -444,8 +479,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } // 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.setText(status.getCob()); + if (sp.getBoolean("show_cob", true)) { mCOB2.setVisibility(View.VISIBLE); } else { mCOB2.setVisibility(View.GONE); @@ -453,15 +488,15 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mIOB1 != null && mIOB2 != null) { - if (sharedPrefs.getBoolean("show_iob", true)) { + if (sp.getBoolean("show_iob", true)) { mIOB1.setVisibility(View.VISIBLE); mIOB2.setVisibility(View.VISIBLE); - if (rawData.detailedIOB) { - mIOB1.setText(rawData.sIOB1); - mIOB2.setText(rawData.sIOB2); + if (status.getDetailedIob()) { + mIOB1.setText(status.getIobSum()); + mIOB2.setText(status.getIobDetail()); } else { mIOB1.setText(getString(R.string.activity_IOB)); - mIOB2.setText(rawData.sIOB1); + mIOB2.setText(status.getIobSum()); } } else { mIOB1.setVisibility(View.GONE); @@ -469,12 +504,12 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } // 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)) { + if (sp.getBoolean("show_iob", true)) { mIOB2.setVisibility(View.VISIBLE); - if (rawData.detailedIOB) { - mIOB2.setText(rawData.sIOB2); + if (status.getDetailedIob()) { + mIOB2.setText(status.getIobDetail()); } else { - mIOB2.setText(rawData.sIOB1); + mIOB2.setText(status.getIobSum()); } } else { mIOB2.setText(""); @@ -482,11 +517,11 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mTimestamp != null) { - if (sharedPrefs.getBoolean("showAgo", true)) { + if (sp.getBoolean("showAgo", true)) { if (isAAPSv2 != null) { mTimestamp.setText(readingAge(true)); } else { - boolean shortString = sharedPrefs.getBoolean("showExternalStatus", true); + boolean shortString = sp.getBoolean("showExternalStatus", true); mTimestamp.setText(readingAge(shortString)); } mTimestamp.setVisibility(View.VISIBLE); @@ -496,15 +531,15 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mUploaderBattery != null) { - if (sharedPrefs.getBoolean("show_uploader_battery", true)) { + if (sp.getBoolean("show_uploader_battery", true)) { if (isAAPSv2 != null) { - mUploaderBattery.setText(rawData.sUploaderBattery + "%"); + mUploaderBattery.setText(status.getBattery() + "%"); mUploaderBattery.setVisibility(View.VISIBLE); } else { - if (sharedPrefs.getBoolean("showExternalStatus", true)) { - mUploaderBattery.setText("U: " + rawData.sUploaderBattery + "%"); + if (sp.getBoolean("showExternalStatus", true)) { + mUploaderBattery.setText("U: " + status.getBattery() + "%"); } else { - mUploaderBattery.setText("Uploader: " + rawData.sUploaderBattery + "%"); + mUploaderBattery.setText("Uploader: " + status.getBattery() + "%"); } } } else { @@ -513,8 +548,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mRigBattery != null) { - if (sharedPrefs.getBoolean("show_rig_battery", false)) { - mRigBattery.setText(rawData.sRigBattery); + if (sp.getBoolean("show_rig_battery", false)) { + mRigBattery.setText(status.getRigBattery()); mRigBattery.setVisibility(View.VISIBLE); } else { mRigBattery.setVisibility(View.GONE); @@ -522,8 +557,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mBasalRate != null) { - if (sharedPrefs.getBoolean("show_temp_basal", true)) { - mBasalRate.setText(rawData.sBasalRate); + if (sp.getBoolean("show_temp_basal", true)) { + mBasalRate.setText(status.getCurrentBasal()); mBasalRate.setVisibility(View.VISIBLE); } else { mBasalRate.setVisibility(View.GONE); @@ -531,8 +566,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mBgi != null) { - if (rawData.showBGI) { - mBgi.setText(rawData.sBgi); + if (status.getShowBgi()) { + mBgi.setText(status.getBgi()); mBgi.setVisibility(View.VISIBLE); } else { mBgi.setVisibility(View.GONE); @@ -540,8 +575,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mStatus != null) { - if (sharedPrefs.getBoolean("showExternalStatus", true)) { - mStatus.setText(rawData.externalStatusString); + if (sp.getBoolean("showExternalStatus", true)) { + mStatus.setText(status.getExternalStatus()); mStatus.setVisibility(View.VISIBLE); } else { mStatus.setVisibility(View.GONE); @@ -549,10 +584,10 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mLoop != null) { - if (sharedPrefs.getBoolean("showExternalStatus", true)) { + if (sp.getBoolean("showExternalStatus", true)) { mLoop.setVisibility(View.VISIBLE); - if (rawData.openApsStatus != -1) { - int mins = (int) ((System.currentTimeMillis() - rawData.openApsStatus) / 1000 / 60); + if (status.getOpenApsStatus() != -1) { + int mins = (int) ((System.currentTimeMillis() - status.getOpenApsStatus()) / 1000 / 60); mLoop.setText(mins + "'"); if (mins > 14) { loopLevel = 0; @@ -605,7 +640,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } if (mDate != null && mDay != null && mMonth != null) { - if (sharedPrefs.getBoolean("show_date", false)) { + if (sp.getBoolean("show_date", false)) { if (mDayName != null) { mDayName.setText(sdfDayName.format(mDateTime)); } @@ -620,10 +655,10 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } public void setColor() { - dividerMatchesBg = sharedPrefs.getBoolean("match_divider", false); + dividerMatchesBg = sp.getBoolean("match_divider", false); if (lowResMode) { setColorLowRes(); - } else if (sharedPrefs.getBoolean("dark", true)) { + } else if (sp.getBoolean("dark", true)) { setColorDark(); } else { setColorBright(); @@ -632,8 +667,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc public void strikeThroughSgvIfNeeded() { if (mSgv != null) { - if (sharedPrefs.getBoolean("showBG", true)) { - if (ageLevel() <= 0 && rawData.datetime > 0) { + if (sp.getBoolean("showBG", true)) { + if (ageLevel() <= 0 && singleBg.getTimeStamp() > 0) { mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); @@ -664,7 +699,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } private boolean isSimpleUi() { - String simplify = sharedPrefs.getString("simplify_ui", "off"); + String simplify = sp.getString("simplify_ui", "off"); if (simplify.equals("off")) { return false; } @@ -674,18 +709,6 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc return (simplify.equals("charging") || simplify.equals("ambient_charging")) && isCharging(); } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - setupBatteryReceiver(); - if ("delta_granularity".equals(key)) { - DataLayerListenerService.Companion.requestData(this); - } - if (layoutSet) { - setDataFields(); - } - invalidate(); - } - protected abstract void setColorDark(); protected abstract void setColorBright(); @@ -694,8 +717,9 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc public void missedReadingAlert() { int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); - if (rawData.datetime == 0 || minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - DataLayerListenerService.Companion.requestData(this); // Attempt endTime recover missing data + if (singleBg.getTimeStamp() == 0 || minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { + // Attempt endTime recover missing data + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BaseWatchFace:missedReadingAlert"))); } } @@ -703,12 +727,12 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc 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 (chart != null && graphData.getEntries().size() > 0) { + int timeframe = sp.getInt("chart_timeframe", 3); if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), rawData, pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); + bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), graphData.getEntries(), treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), 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); + bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), graphData.getEntries(), treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); } chart.setLineChartData(bgGraphBuilder.lineData()); @@ -717,39 +741,12 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferenc } } - 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); - - if (isSimpleUi()) { - if (needUpdate()) { - invalidate(); - } - } else { - setupCharts(); - setDataFields(); - invalidate(); - } - wearUtil.releaseWakeLock(wl); - } - } - private boolean needUpdate() { - if (mLastSvg.equals(rawData.sSgv) && mLastDirection.equals(rawData.sDirection)) { + if (mLastSvg.equals(singleBg.getSgvString()) && mLastDirection.equals(singleBg.getSgvString())) { return false; } - mLastSvg = rawData.sSgv; - mLastDirection = rawData.sDirection; + mLastSvg = singleBg.getSgvString(); + mLastDirection = singleBg.getSgvString(); return true; } - } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java index 3cae85f962..2dd39c850f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java @@ -14,17 +14,12 @@ 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 info.nightscout.shared.weardata.EventData; 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. @@ -33,10 +28,10 @@ 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 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; @@ -44,7 +39,7 @@ public class BgGraphBuilder { public Context context; public double highMark; public double lowMark; - public List bgDataList = new ArrayList(); + public List bgDataList; public int pointSize; public int highColor; @@ -58,20 +53,24 @@ public class BgGraphBuilder { 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; - + private final List inRangeValues = new ArrayList<>(); + private final List highValues = new ArrayList<>(); + private final List lowValues = new ArrayList<>(); //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 + 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() - (1000L * 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.highMark = aBgList.get(aBgList.size() - 1).getHigh(); + this.lowMark = aBgList.get(aBgList.size() - 1).getLow(); this.pointSize = aPointSize; this.singleLine = false; this.midColor = aMidColor; @@ -80,24 +79,31 @@ public class BgGraphBuilder { this.timespan = timespan; this.tempWatchDataList = tempWatchDataList; this.basalWatchDataList = basalWatchDataList; - this.bolusWatchDataList = (bolusWatchDataList!=null)?bolusWatchDataList:new ArrayList(); + 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.end_time = System.currentTimeMillis() + (1000L * 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; + this.end_time = Math.max(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 + 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() - (1000L * 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.highMark = aBgList.get(aBgList.size() - 1).getHigh(); + this.lowMark = aBgList.get(aBgList.size() - 1).getLow(); this.pointSize = aPointSize; this.highColor = aHighColor; this.lowColor = aLowColor; @@ -105,51 +111,16 @@ public class BgGraphBuilder { this.timespan = timespan; this.tempWatchDataList = tempWatchDataList; this.basalWatchDataList = basalWatchDataList; - this.bolusWatchDataList = (bolusWatchDataList!=null)?bolusWatchDataList:new ArrayList(); + 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.end_time = System.currentTimeMillis() + (1000L * 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); + this.end_time = Math.max(predictionEndTime, end_time); } public LineChartData lineData() { @@ -162,7 +133,7 @@ public class BgGraphBuilder { public List defaultLines() { addBgReadingValues(); - List lines = new ArrayList(); + List lines = new ArrayList<>(); lines.add(highLine()); lines.add(lowLine()); lines.add(inRangeValuesLine()); @@ -172,41 +143,41 @@ public class BgGraphBuilder { double minChart = lowMark; double maxChart = highMark; - for ( BgWatchData bgd:bgDataList) { - if(bgd.sgv > maxChart){ - maxChart = bgd.sgv; + for (EventData.SingleBg bgd : bgDataList) { + if (bgd.getSgv() > maxChart) { + maxChart = bgd.getSgv(); } - if(bgd.sgv < minChart){ - minChart = bgd.sgv; + if (bgd.getSgv() < minChart) { + minChart = bgd.getSgv(); } } double maxBasal = 0.1; - for (BasalWatchData bwd: basalWatchDataList) { - if(bwd.amount > maxBasal){ - maxBasal = bwd.amount; + for (EventData.TreatmentData.Basal bwd : basalWatchDataList) { + if (bwd.getAmount() > maxBasal) { + maxBasal = bwd.getAmount(); } } double maxTemp = maxBasal; - for (TempWatchData twd: tempWatchDataList) { - if(twd.amount > maxTemp){ - maxTemp = twd.amount; + for (EventData.TreatmentData.TempBasal twd : tempWatchDataList) { + if (twd.getAmount() > maxTemp) { + maxTemp = twd.getAmount(); } } - double factor = (maxChart-minChart)/maxTemp; + 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)); + 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){ + for (EventData.TreatmentData.TempBasal twd : tempWatchDataList) { + if (twd.getEndTime() > 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)); } } @@ -224,13 +195,14 @@ public class BgGraphBuilder { private Line basalLine(float offset, double factor, boolean highlight) { - List pointValues = new ArrayList(); + 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))); + for (EventData.TreatmentData.Basal bwd : basalWatchDataList) { + if (bwd.getEndTime() > start_time) { + long begin = Math.max(start_time, bwd.getStartTime()); + pointValues.add(new PointValue(fuzz(begin), offset + (float) (factor * bwd.getAmount()))); + pointValues.add(new PointValue(fuzz(bwd.getEndTime()), + offset + (float) (factor * bwd.getAmount()))); } } @@ -238,7 +210,7 @@ public class BgGraphBuilder { basalLine.setHasPoints(false); basalLine.setColor(basalCenterColor); basalLine.setPathEffect(new DashPathEffect(new float[]{4f, 3f}, 4f)); - basalLine.setStrokeWidth(highlight?2:1); + basalLine.setStrokeWidth(highlight ? 2 : 1); return basalLine; @@ -246,28 +218,28 @@ public class BgGraphBuilder { private Line bolusLine(float offset) { - List pointValues = new ArrayList(); + 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)); + for (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { + if (bwd.getDate() > start_time && bwd.getDate() <= end_time && !bwd.isSMB() && bwd.isValid() && bwd.getBolus() > 0) { + pointValues.add(new PointValue(fuzz(bwd.getDate()), offset - 2)); } } Line line = new Line(pointValues); line.setColor(basalCenterColor); line.setHasLines(false); - line.setPointRadius(pointSize*2); + line.setPointRadius(pointSize * 2); line.setHasPoints(true); return line; } private Line smbLine(float offset) { - List pointValues = new ArrayList(); + 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)); + for (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { + if (bwd.getDate() > start_time && bwd.getDate() <= end_time && bwd.isSMB() && bwd.isValid() && bwd.getBolus() > 0) { + pointValues.add(new PointValue(fuzz(bwd.getDate()), offset - 2)); } } Line line = new Line(pointValues); @@ -280,11 +252,11 @@ public class BgGraphBuilder { private Line bolusInvalidLine(float offset) { - List pointValues = new ArrayList(); + 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)); + for (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { + if (bwd.getDate() > start_time && bwd.getDate() <= end_time && !(bwd.isValid() && (bwd.getBolus() > 0 || bwd.getCarbs() > 0))) { + pointValues.add(new PointValue(fuzz(bwd.getDate()), offset - 2)); } } Line line = new Line(pointValues); @@ -297,17 +269,17 @@ public class BgGraphBuilder { private Line carbsLine(float offset) { - List pointValues = new ArrayList(); + 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)); + for (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { + if (bwd.getDate() > start_time && bwd.getDate() <= end_time && !bwd.isSMB() && bwd.isValid() && bwd.getCarbs() > 0) { + pointValues.add(new PointValue(fuzz(bwd.getDate()), offset + 2)); } } Line line = new Line(pointValues); line.setColor(carbsColor); line.setHasLines(false); - line.setPointRadius(pointSize*2); + line.setPointRadius(pointSize * 2); line.setHasPoints(true); return line; } @@ -316,13 +288,13 @@ public class BgGraphBuilder { 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<>()); + for (EventData.SingleBg bwd : predictionsList) { + if (bwd.getTimeStamp() <= endTime) { + double value = Math.min(bwd.getSgv(), UPPER_CUTOFF_SGV); + if (!values.containsKey(bwd.getColor())) { + values.put(bwd.getColor(), new ArrayList<>()); } - values.get(bwd.color).add(new PointValue(fuzz(bwd.timestamp), (float) value)); + values.get(bwd.getColor()).add(new PointValue(fuzz(bwd.getTimeStamp()), (float) value)); } } for (Map.Entry> entry : values.entrySet()) { @@ -358,7 +330,7 @@ public class BgGraphBuilder { public Line inRangeValuesLine() { Line inRangeValuesLine = new Line(inRangeValues); inRangeValuesLine.setColor(midColor); - if(singleLine) { + if (singleLine) { inRangeValuesLine.setHasLines(true); inRangeValuesLine.setHasPoints(false); inRangeValuesLine.setStrokeWidth(pointSize); @@ -371,19 +343,19 @@ public class BgGraphBuilder { } - 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))); + public Line tempValuesLine(EventData.TreatmentData.TempBasal twd, float offset, double factor, boolean isHighlightLine, int strokeWidth) { + List lineValues = new ArrayList<>(); + long begin = Math.max(start_time, twd.getStartTime()); + lineValues.add(new PointValue(fuzz(begin), offset + (float) (factor * twd.getStartBasal()))); + lineValues.add(new PointValue(fuzz(begin), offset + (float) (factor * twd.getAmount()))); + lineValues.add(new PointValue(fuzz(twd.getEndTime()), offset + (float) (factor * twd.getAmount()))); + lineValues.add(new PointValue(fuzz(twd.getEndTime()), offset + (float) (factor * twd.getEndBasal()))); Line valueLine = new Line(lineValues); valueLine.setHasPoints(false); - if (isHighlightLine){ + if (isHighlightLine) { valueLine.setColor(basalCenterColor); valueLine.setStrokeWidth(1); - }else { + } else { valueLine.setColor(basalBackgroundColor); valueLine.setStrokeWidth(strokeWidth); } @@ -391,38 +363,36 @@ public class BgGraphBuilder { } - - 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)); + if (singleLine) { + for (EventData.SingleBg bgReading : bgDataList) { + if (bgReading.getTimeStamp() > start_time) { + if (bgReading.getSgv() >= 450) { + inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) 450)); + } else if (bgReading.getSgv() >= highMark) { + inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); + } else if (bgReading.getSgv() >= lowMark) { + inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); + } else if (bgReading.getSgv() >= 40) { + inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); + } else if (bgReading.getSgv() >= 11) { + inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (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)); + for (EventData.SingleBg bgReading : bgDataList) { + if (bgReading.getTimeStamp() > start_time) { + if (bgReading.getSgv() >= 450) { + highValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) 450)); + } else if (bgReading.getSgv() >= highMark) { + highValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); + } else if (bgReading.getSgv() >= lowMark) { + inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); + } else if (bgReading.getSgv() >= 40) { + lowValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); + } else if (bgReading.getSgv() >= 11) { + lowValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) 40)); } } } @@ -430,7 +400,7 @@ public class BgGraphBuilder { } public Line highLine() { - List highLineValues = new ArrayList(); + 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); @@ -441,7 +411,7 @@ public class BgGraphBuilder { } public Line lowLine() { - List lowLineValues = new ArrayList(); + 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); @@ -457,7 +427,7 @@ public class BgGraphBuilder { public Axis yAxis() { Axis yAxis = new Axis(); yAxis.setAutoGenerated(true); - List axisValues = new ArrayList(); + List axisValues = new ArrayList<>(); yAxis.setValues(axisValues); yAxis.setHasLines(false); yAxis.setLineColor(gridColour); @@ -466,13 +436,13 @@ public class BgGraphBuilder { public Axis xAxis() { final boolean is24 = DateFormat.is24HourFormat(context); - SimpleDateFormat timeFormat = new SimpleDateFormat(is24? "HH" : "h a"); + 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(); + List xAxisValues = new ArrayList<>(); //get the time-tick at the full hour after start_time GregorianCalendar startGC = new GregorianCalendar(); @@ -484,14 +454,14 @@ public class BgGraphBuilder { long start_hour = startGC.getTimeInMillis(); //Display current time on the graph - SimpleDateFormat longTimeFormat = new SimpleDateFormat(is24? "HH:mm" : "h:mm a"); + 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)){ + 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 @@ -499,7 +469,7 @@ public class BgGraphBuilder { } //increment by one hour - hourTick += 60*60*1000; + hourTick += 60 * 60 * 1000; } xAxis.setValues(xAxisValues); @@ -513,16 +483,16 @@ public class BgGraphBuilder { public long getPredictionEndTime() { long maxPredictionDate = System.currentTimeMillis(); - for (BgWatchData prediction : + for (EventData.SingleBg prediction : predictionsList) { - if (maxPredictionDate < prediction.timestamp) { - maxPredictionDate = prediction.timestamp; + if (maxPredictionDate < prediction.getTimeStamp()) { + maxPredictionDate = prediction.getTimeStamp(); } } - return (long) Math.min(maxPredictionDate, System.currentTimeMillis() + MAX_PREDICTION__TIME_RATIO *timespan*1000*60*60); + 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); + return (float) Math.round(value / fuzzyTimeDenom); } } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java index f4c7d18a90..d80b3e43d5 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java @@ -1,25 +1,15 @@ package info.nightscout.androidaps.watchfaces; -import android.content.BroadcastReceiver; +import android.annotation.SuppressLint; 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; @@ -27,21 +17,40 @@ 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 javax.inject.Inject; + +import dagger.android.AndroidInjection; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.BgWatchData; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; +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; -public class CircleWatchface extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { +public class CircleWatchface extends WatchFace { + + @Inject RxBus rxBus; + @Inject AapsSchedulers aapsSchedulers; + @Inject AAPSLogger aapsLogger; + @Inject SP sp; + + CompositeDisposable disposable = new CompositeDisposable(); + + private EventData.SingleBg singleBg = new EventData.SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0); + private EventData.GraphData graphData; + private EventData.Status status = new EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1); + public final float PADDING = 20f; public final float CIRCLE_WIDTH = 10f; public final int BIG_HAND_WIDTH = 16; @@ -52,43 +61,27 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh //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<>(); + public ArrayList bgDataList = new ArrayList<>(); private int specW; private int specH; private View myLayout; - protected SharedPreferences sharedPrefs; private TextView mSgv; private long sgvTapTime = 0; - @Override + @SuppressLint("InflateParams") @Override public void onCreate() { + AndroidInjection.inject(this); super.onCreate(); PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); @@ -104,19 +97,46 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh 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 + disposable.add(rxBus + .toObservable(EventData.SingleBg.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> singleBg = event) + ); + disposable.add(rxBus + .toObservable(EventData.GraphData.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> graphData = event) + ); + disposable.add(rxBus + .toObservable(EventData.Status.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received"); + status = event; + addToWatchSet(); + prepareLayout(); + prepareDrawTime(); + invalidate(); + }) + ); + disposable.add(rxBus + .toObservable(EventData.Preferences.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + prepareDrawTime(); + prepareLayout(); + invalidate(); + }) + ); + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("CircleWatchFace::onCreate"))); wakeLock.release(); } @@ -124,18 +144,13 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh @Override public void onDestroy() { - if (messageReceiver != null) { - LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver); - } - if (sharedPrefs != null) { - sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - } + disposable.clear(); super.onDestroy(); } @Override protected synchronized void onDraw(Canvas canvas) { - Log.d("CircleWatchface", "start onDraw"); + aapsLogger.debug(LTag.WEAR, "start onDraw"); canvas.drawColor(getBackgroundColor()); drawTime(canvas); drawOtherStuff(canvas); @@ -145,27 +160,25 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh private synchronized void prepareLayout() { - Log.d("CircleWatchface", "start startPrepareLayout"); + aapsLogger.debug(LTag.WEAR, "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()); + if (sp.getBoolean("showBG", true)) { + mSgv.setVisibility(View.VISIBLE); + mSgv.setText(singleBg.getSgvString()); + mSgv.setTextColor(getTextColor()); } else { //Also possible: View.INVISIBLE instead of View.GONE (no layout change) - textView.setVisibility(View.INVISIBLE); + mSgv.setVisibility(View.INVISIBLE); } - textView = myLayout.findViewById(R.id.statusString); - if (sharedPrefs.getBoolean("showExternalStatus", true)) { + TextView textView = myLayout.findViewById(R.id.statusString); + if (sp.getBoolean("showExternalStatus", true)) { textView.setVisibility(View.VISIBLE); - textView.setText(getStatusString()); + textView.setText(status.getExternalStatus()); textView.setTextColor(getTextColor()); } else { @@ -174,10 +187,10 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } textView = myLayout.findViewById(R.id.agoString); - if (sharedPrefs.getBoolean("showAgo", true)) { + if (sp.getBoolean("showAgo", true)) { textView.setVisibility(View.VISIBLE); - if (sharedPrefs.getBoolean("showBigNumbers", false)) { + if (sp.getBoolean("showBigNumbers", false)) { textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); } else { ((TextView) myLayout.findViewById(R.id.agoString)).setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); @@ -190,17 +203,17 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } textView = myLayout.findViewById(R.id.deltaString); - if (sharedPrefs.getBoolean("showDelta", true)) { + if (sp.getBoolean("showDelta", true)) { textView.setVisibility(View.VISIBLE); - textView.setText(getDelta()); + textView.setText(singleBg.getDelta()); textView.setTextColor(getTextColor()); - if (sharedPrefs.getBoolean("showBigNumbers", false)) { + if (sp.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()); + if (sp.getBoolean("showAvgDelta", true)) { + textView.append(" " + singleBg.getAvgDelta()); } } else { @@ -215,8 +228,8 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh public String getMinutes() { String minutes = "--'"; - if (getDatetime() != 0) { - minutes = ((int) Math.floor((System.currentTimeMillis() - getDatetime()) / 60000.0)) + "'"; + if (singleBg.getTimeStamp() != 0) { + minutes = ((int) Math.floor((System.currentTimeMillis() - singleBg.getTimeStamp()) / 60000.0)) + "'"; } return minutes; } @@ -249,16 +262,16 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } private synchronized void prepareDrawTime() { - Log.d("CircleWatchface", "start prepareDrawTime"); + aapsLogger.debug(LTag.WEAR, "start prepareDrawTime"); - hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) % 12; - minute = Calendar.getInstance().get(Calendar.MINUTE); + int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) % 12; + int 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()) { + switch ((int) singleBg.getSgvLevel()) { case -1: color = getLowColor(); break; @@ -271,20 +284,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } - 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.setShader(null); circlePaint.setStyle(Paint.Style.STROKE); circlePaint.setStrokeWidth(CIRCLE_WIDTH); @@ -299,17 +299,10 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh 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"); + aapsLogger.debug(LTag.WEAR, "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 || @@ -338,7 +331,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh // defining color for dark and bright public int getLowColor() { - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.getBoolean("dark", true)) { return Color.argb(255, 255, 120, 120); } else { return Color.argb(255, 255, 80, 80); @@ -346,7 +339,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } public int getInRangeColor() { - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.getBoolean("dark", true)) { return Color.argb(255, 120, 255, 120); } else { return Color.argb(255, 0, 240, 0); @@ -355,7 +348,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } public int getHighColor() { - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.getBoolean("dark", true)) { return Color.argb(255, 255, 255, 120); } else { return Color.argb(255, 255, 200, 0); @@ -364,7 +357,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } public int getBackgroundColor() { - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.getBoolean("dark", true)) { return Color.BLACK; } else { return Color.WHITE; @@ -373,7 +366,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } public int getTextColor() { - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.getBoolean("dark", true)) { return Color.WHITE; } else { return Color.BLACK; @@ -382,23 +375,22 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } public void drawOtherStuff(Canvas canvas) { - Log.d("CircleWatchface", "start onDrawOtherStuff. bgDataList.size(): " + bgDataList.size()); + aapsLogger.debug(LTag.WEAR, "start onDrawOtherStuff. bgDataList.size(): " + bgDataList.size()); - if (isAnimated()) return; // too many repaints when animated - if (sharedPrefs.getBoolean("showRingHistory", false)) { + if (sp.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()); + addIndicator(canvas, (float) bgDataList.iterator().next().getLow(), getLowColor()); + addIndicator(canvas, (float) bgDataList.iterator().next().getHigh(), getHighColor()); - if (sharedPrefs.getBoolean("softRingHistory", true)) { - for (BgWatchData data : bgDataList) { + if (sp.getBoolean("softRingHistory", true)) { + for (EventData.SingleBg data : bgDataList) { addReadingSoft(canvas, data); } } else { - for (BgWatchData data : bgDataList) { + for (EventData.SingleBg data : bgDataList) { addReading(canvas, data); } } @@ -406,202 +398,15 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } } - public int holdInMemory() { - return 6; - } + public synchronized void addToWatchSet() { - //getters & setters + bgDataList.clear(); + if (!sp.getBoolean("showRingHistory", false)) return; - 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(); + double threshold = (System.currentTimeMillis() - (1000L * 60 * 30)); // 30 min + for (EventData.SingleBg entry : graphData.getEntries()) + if (entry.getTimeStamp() >= threshold) bgDataList.add(entry); + aapsLogger.debug(LTag.WEAR, "addToWatchSet size=" + bgDataList.size()); } public int darken(int color, double fraction) { @@ -618,10 +423,7 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh 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); } @@ -659,44 +461,46 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh } - public void addReadingSoft(Canvas canvas, BgWatchData entry) { + public void addReadingSoft(Canvas canvas, EventData.SingleBg entry) { - Log.d("CircleWatchface", "addReadingSoft"); + aapsLogger.debug(LTag.WEAR, "addReadingSoft"); double size; int color = Color.LTGRAY; - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.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); + float offset = (float) Math.max(1, + Math.ceil((System.currentTimeMillis() - entry.getTimeStamp()) / (1000 * 60 * 5.0))); + size = bgToAngle((float) entry.getSgv()); 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"); + public void addReading(Canvas canvas, EventData.SingleBg entry) { + aapsLogger.debug(LTag.WEAR, "addReading"); double size; int color = Color.LTGRAY; int indicatorColor = Color.DKGRAY; - if (sharedPrefs.getBoolean("dark", true)) { + if (sp.getBoolean("dark", true)) { color = Color.DKGRAY; indicatorColor = Color.LTGRAY; } int barColor = Color.GRAY; - if (entry.sgv >= entry.high) { + if (entry.getSgv() >= entry.getHigh()) { indicatorColor = getHighColor(); barColor = darken(getHighColor(), .5); - } else if (entry.sgv <= entry.low) { + } else if (entry.getSgv() <= entry.getLow()) { 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); + float offset = (float) Math.max(1, + Math.ceil((System.currentTimeMillis() - entry.getTimeStamp()) / (1000 * 60 * 5.0))); + size = bgToAngle((float) entry.getSgv()); 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 @@ -705,8 +509,8 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh @Override protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv != null ? (mSgv.getRight() - mSgv.getLeft()) / 2 : 0; + if (mSgv == null) return; + int extra = (mSgv.getRight() - mSgv.getLeft()) / 2; if (tapType == TAP_TYPE_TAP && x + extra >= mSgv.getLeft() && @@ -726,6 +530,4 @@ public class CircleWatchface extends WatchFace implements SharedPreferences.OnSh 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/Cockpit.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java index 3a68158109..9ac98fe0ce 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.watchfaces; +import android.annotation.SuppressLint; import android.content.Intent; import android.support.wearable.watchface.WatchFaceStyle; import android.view.LayoutInflater; @@ -16,7 +17,7 @@ public class Cockpit extends BaseWatchFace { private long sgvTapTime = 0; - @Override + @SuppressLint("InflateParams") @Override public void onCreate() { super.onCreate(); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); @@ -48,13 +49,13 @@ public class Cockpit extends BaseWatchFace { setTextSizes(); if (mHighLight != null && mLowLight != null) { - if (rawData.sgvLevel == 1) { + if (singleBg.getSgvLevel() == 1) { mHighLight.setBackgroundResource(R.drawable.airplane_led_yellow_lit); mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - } else if (rawData.sgvLevel == 0) { + } else if (singleBg.getSgvLevel() == 0) { mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - } else if (rawData.sgvLevel == -1) { + } else if (singleBg.getSgvLevel() == -1) { mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); mLowLight.setBackgroundResource(R.drawable.airplane_led_red_lit); } @@ -84,7 +85,7 @@ public class Cockpit extends BaseWatchFace { protected void setTextSizes() { if (mIOB2 != null) { - if (rawData.detailedIOB) { + if (status.getDetailedIob()) { if (bIsRound) { mIOB2.setTextSize(10); } else { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java index 2b3975e949..b44f3c95dd 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.watchfaces; +import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.ColorStateList; import android.support.wearable.watchface.WatchFaceStyle; @@ -19,10 +20,9 @@ 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 + @SuppressLint("InflateParams") @Override public void onCreate() { super.onCreate(); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); @@ -57,13 +57,13 @@ public class DigitalStyle extends BaseWatchFace { } protected void setColorDark() { - if (rawData.sgvLevel == 1) { + if (singleBg.getSgvLevel() == 1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (rawData.sgvLevel == 0) { + } else if (singleBg.getSgvLevel() == 0) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (rawData.sgvLevel == -1) { + } else if (singleBg.getSgvLevel() == -1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); } @@ -74,7 +74,7 @@ public class DigitalStyle extends BaseWatchFace { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); } else { mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); @@ -99,10 +99,11 @@ public class DigitalStyle extends BaseWatchFace { 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"); + String displayStyle=sp.getString("digitalstyle_frameStyle", "full"); + String displayFrameColor=sp.getString("digitalstyle_frameColor", "red"); + String displayFrameColorSaturation=sp.getString("digitalstyle_frameColorSaturation", + "500"); + String displayFrameColorOpacity=sp.getString("digitalstyle_frameColorOpacity", "1"); // Load image with shapes String styleDrawableName = "digitalstyle_bg_" + displayStyle + "_" + displayFormatType; @@ -133,7 +134,7 @@ public class DigitalStyle extends BaseWatchFace { } /* optimize font-size --> when date is off then increase font-size of time */ - Boolean isShowDate = sharedPrefs.getBoolean("show_date", false); + Boolean isShowDate = sp.getBoolean("show_date", false); if (!isShowDate) { layoutView.findViewById(R.id.date_time).setVisibility(View.GONE); mHour.setTextSize(62); @@ -148,7 +149,7 @@ public class DigitalStyle extends BaseWatchFace { mMinute.setLetterSpacing((float) 0); /* display week number */ - Boolean isShowWeekNumber = sharedPrefs.getBoolean("show_weeknumber", false); + Boolean isShowWeekNumber = sp.getBoolean("show_weeknumber", false); Log.i("---------------------------------","weeknumber refresh "); TextView mWeekNumber= layoutView.findViewById(R.id.weeknumber); if (isShowWeekNumber) { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java index ce84f97e46..fb15053f51 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.watchfaces; +import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import androidx.core.content.ContextCompat; @@ -16,7 +17,7 @@ public class Home extends BaseWatchFace { private long chartTapTime = 0; private long sgvTapTime = 0; - @Override + @SuppressLint("InflateParams") @Override public void onCreate() { super.onCreate(); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); @@ -53,9 +54,9 @@ public class Home extends BaseWatchFace { } private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); + int timeframe = sp.getInt("chart_timeframe", 3); timeframe = (timeframe%5) + 1; - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); + sp.putString("chart_timeframe", "" + timeframe); } @Override @@ -69,15 +70,15 @@ public class Home extends BaseWatchFace { 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) { + if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == -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)); @@ -90,7 +91,7 @@ public class Home extends BaseWatchFace { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); } else { @@ -138,15 +139,15 @@ public class Home extends BaseWatchFace { 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) { + if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == -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)); @@ -158,7 +159,7 @@ public class Home extends BaseWatchFace { mTimestamp.setTextColor(Color.RED); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); } else { mUploaderBattery.setTextColor(Color.RED); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java index 9f1cb75ddd..21a600ce5f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.watchfaces; +import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; @@ -19,7 +20,7 @@ public class Home2 extends BaseWatchFace { private long chartTapTime = 0; private long sgvTapTime = 0; - @Override + @SuppressLint("InflateParams") @Override public void onCreate() { super.onCreate(); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); @@ -57,9 +58,9 @@ public class Home2 extends BaseWatchFace { } private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); + int timeframe = sp.getInt("chart_timeframe", 3); timeframe = (timeframe % 5) + 1; - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); + sp.putString("chart_timeframe", "" + timeframe); } @Override @@ -89,13 +90,13 @@ public class Home2 extends BaseWatchFace { setTextSizes(); - if (rawData.sgvLevel == 1) { + if (singleBg.getSgvLevel() == 1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (rawData.sgvLevel == 0) { + } else if (singleBg.getSgvLevel() == 0) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (rawData.sgvLevel == -1) { + } else if (singleBg.getSgvLevel() == -1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); } @@ -106,7 +107,7 @@ public class Home2 extends BaseWatchFace { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(dividerBatteryOkColor); } else { mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); @@ -200,13 +201,13 @@ public class Home2 extends BaseWatchFace { setTextSizes(); - if (rawData.sgvLevel == 1) { + if (singleBg.getSgvLevel() == 1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - } else if (rawData.sgvLevel == 0) { + } else if (singleBg.getSgvLevel() == 0) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - } else if (rawData.sgvLevel == -1) { + } else if (singleBg.getSgvLevel() == -1) { mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); } @@ -217,7 +218,7 @@ public class Home2 extends BaseWatchFace { mTimestamp.setTextColor(Color.RED); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(dividerTxtColor); } else { mUploaderBattery.setTextColor(Color.RED); @@ -255,7 +256,7 @@ public class Home2 extends BaseWatchFace { if (mIOB1 != null && mIOB2 != null) { - if (rawData.detailedIOB) { + if (status.getDetailedIob()) { mIOB1.setTextSize(14); mIOB2.setTextSize(10); } else { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java index efce6baab7..29774131ef 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.watchfaces; +import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Color; import androidx.core.content.ContextCompat; @@ -15,7 +16,7 @@ public class LargeHome extends BaseWatchFace { private long sgvTapTime = 0; - @Override + @SuppressLint("InflateParams") @Override public void onCreate() { super.onCreate(); LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); @@ -25,8 +26,8 @@ public class LargeHome extends BaseWatchFace { @Override protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; + if (mSgv == null) return; + int extra = (mSgv.getRight() - mSgv.getLeft())/2; if (tapType == TAP_TYPE_TAP&& x + extra >=mSgv.getLeft() && @@ -53,15 +54,15 @@ public class LargeHome extends BaseWatchFace { 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) { + if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == -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)); @@ -74,7 +75,7 @@ public class LargeHome extends BaseWatchFace { mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); } else { @@ -90,15 +91,15 @@ public class LargeHome extends BaseWatchFace { 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) { + if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == 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) { + } else if (singleBg.getSgvLevel() == -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)); @@ -110,7 +111,7 @@ public class LargeHome extends BaseWatchFace { mTimestamp.setTextColor(Color.RED); } - if (rawData.batteryLevel == 1) { + if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); } else { mUploaderBattery.setTextColor(Color.RED); @@ -120,15 +121,15 @@ public class LargeHome extends BaseWatchFace { } else { mRelativeLayout.setBackgroundColor(Color.BLACK); mLinearLayout.setBackgroundColor(dividerMatchesBg ? Color.BLACK : Color.LTGRAY); - if (rawData.sgvLevel == 1) { + if (singleBg.getSgvLevel() == 1) { mSgv.setTextColor(Color.YELLOW); mDirection.setTextColor(Color.YELLOW); mDelta.setTextColor(Color.YELLOW); - } else if (rawData.sgvLevel == 0) { + } else if (singleBg.getSgvLevel() == 0) { mSgv.setTextColor(Color.WHITE); mDirection.setTextColor(Color.WHITE); mDelta.setTextColor(Color.WHITE); - } else if (rawData.sgvLevel == -1) { + } else if (singleBg.getSgvLevel() == -1) { mSgv.setTextColor(Color.RED); mDirection.setTextColor(Color.RED); mDelta.setTextColor(Color.RED); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java index ed773c68d9..4091e9a8db 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java @@ -1,29 +1,17 @@ package info.nightscout.androidaps.watchfaces; -import android.content.BroadcastReceiver; +import android.annotation.SuppressLint; 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; @@ -32,56 +20,60 @@ import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.TextView; -import com.google.android.gms.wearable.DataMap; +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 java.util.ArrayList; +import javax.inject.Inject; +import dagger.android.AndroidInjection; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.BasalWatchData; -import info.nightscout.androidaps.data.BgWatchData; -import info.nightscout.androidaps.data.DataLayerListenerService; -import info.nightscout.androidaps.data.TempWatchData; +import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; +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; /** * Created by adrianLxM. */ -public class NOChart extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { - public final static IntentFilter INTENT_FILTER; +public class NOChart extends WatchFace { + + @Inject RxBus rxBus; + @Inject AapsSchedulers aapsSchedulers; + @Inject AAPSLogger aapsLogger; + @Inject SP sp; + + CompositeDisposable disposable = new CompositeDisposable(); + + private EventData.SingleBg singleBg; + private EventData.Status status; + 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 + @SuppressLint("InflateParams") @Override public void onCreate() { + AndroidInjection.inject(this); super.onCreate(); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); @@ -92,17 +84,60 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref 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){ + 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); } + disposable.add(rxBus + .toObservable(EventData.SingleBg.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + aapsLogger.debug(LTag.WEAR, "SingleBg received"); + singleBg = event; + + mSgv.setText(singleBg.getSgvString()); + 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(this); + mTime.setText(timeFormat.format(System.currentTimeMillis())); + mDelta.setText(singleBg.getDelta()); + mAvgDelta.setText(singleBg.getAvgDelta()); + }) + ); + disposable.add(rxBus + .toObservable(EventData.Status.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received"); + status = event; + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), + mRelativeLayout.getMeasuredHeight()); + invalidate(); + setColor(); + }) + ); + disposable.add(rxBus + .toObservable(EventData.Preferences.class) + .observeOn(aapsSchedulers.getMain()) + .subscribe(event -> { + setColor(); + if (layoutSet) { + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), + mRelativeLayout.getMeasuredHeight()); + } + invalidate(); + }) + ); performViewSetup(); } @@ -114,44 +149,37 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref 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()); - } + stub.setOnLayoutInflatedListener(stub1 -> { + mTime = stub1.findViewById(R.id.watch_time); + mSgv = stub1.findViewById(R.id.sgv); + mTimestamp = stub1.findViewById(R.id.timestamp); + mDelta = stub1.findViewById(R.id.delta); + mAvgDelta = stub1.findViewById(R.id.avgdelta); + mRelativeLayout = stub1.findViewById(R.id.main_layout); + statusView = stub1.findViewById(R.id.aps_status); + layoutSet = true; + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), + mRelativeLayout.getMeasuredHeight()); }); - DataLayerListenerService.Companion.requestData(this); + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("NOChart" + + ":performViewSetup"))); wakeLock.acquire(50); } @Override protected void onTapCommand(int tapType, int x, int y, long eventTime) { + if (mSgv == null) return; + int extra = (mSgv.getRight() - mSgv.getLeft()) / 2; - int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; - - if (tapType == TAP_TYPE_TAP&& - x + extra >=mSgv.getLeft() && - x - extra <= mSgv.getRight()&& + if (tapType == TAP_TYPE_TAP && + x + extra >= mSgv.getLeft() && + x - extra <= mSgv.getRight() && y >= mSgv.getTop() && - y <= mSgv.getBottom()){ - if (eventTime - sgvTapTime < 800){ + y <= mSgv.getBottom()) { + if (eventTime - sgvTapTime < 800) { Intent intent = new Intent(this, MainMenuActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); @@ -162,10 +190,10 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref protected void onWatchModeChanged(WatchMode watchMode) { - if(lowResMode ^ isLowRes(watchMode)){ //if there was a change in lowResMode + if (lowResMode ^ isLowRes(watchMode)) { //if there was a change in lowResMode lowResMode = isLowRes(watchMode); setColor(); - } else if (! sharedPrefs.getBoolean("dark", true)){ + } else if (!sp.getBoolean("dark", true)) { //in bright mode: different colours if active: setColor(); } @@ -177,14 +205,13 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref @Override - protected WatchFaceStyle getWatchFaceStyle(){ + protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); } - public int ageLevel() { - if(timeSince() <= (1000 * 60 * 12)) { + if (timeSince() <= (1000 * 60 * 12)) { return 1; } else { return 0; @@ -192,40 +219,30 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref } public double timeSince() { - return System.currentTimeMillis() - datetime; + return System.currentTimeMillis() - singleBg.getTimeStamp(); } 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"); + if (singleBg == null || singleBg.getTimeStamp() == 0) { + return shortString ? "--'" : "-- Minute ago"; } - return minutesAgo + (shortString?"'":" Minutes 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); - } + disposable.clear(); 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) { + if (layoutSet) { this.mRelativeLayout.draw(canvas); - Log.d("onDraw", "draw"); } } @@ -237,7 +254,7 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref mTime.setText(timeFormat.format(System.currentTimeMillis())); showAgeAndStatus(); - if(ageLevel()<=0) { + if (ageLevel() <= 0) { mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); @@ -250,142 +267,28 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref } } - 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){ + if (mTimestamp != null) { mTimestamp.setText(readingAge(true)); } - boolean showAvgDelta = sharedPrefs.getBoolean("showAvgDelta", true); + boolean showAvgDelta = sp.getBoolean("showAvgDelta", true); - if(showAvgDelta){ + if (showAvgDelta) { mAvgDelta.setVisibility(View.VISIBLE); } else { mAvgDelta.setVisibility(View.GONE); } - statusView.setText(externalStatusString); + if (status != null) { + statusView.setText(status.getExternalStatus()); statusView.setVisibility(View.VISIBLE); + } } public void setColor() { - if(lowResMode){ + if (lowResMode) { setColorLowRes(); - } else if (sharedPrefs.getBoolean("dark", true)) { + } else if (sp.getBoolean("dark", true)) { setColorDark(); } else { setColorBright(); @@ -393,62 +296,6 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref } - - - @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)); @@ -516,9 +363,11 @@ public class NOChart extends WatchFace implements SharedPreferences.OnSharedPref } public void missedReadingAlert() { - int minutes_since = (int) Math.floor(timeSince()/(1000*60)); - if(minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - DataLayerListenerService.Companion.requestData(this); // attempt endTime recover missing data + int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); + if (minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { + // attempt endTime recover missing data + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("NOChart" + + ":missedReadingAlert"))); } } } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java index 644c17668d..13791efd06 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java @@ -1,13 +1,15 @@ package info.nightscout.androidaps.watchfaces; +import android.annotation.SuppressLint; 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 androidx.core.content.ContextCompat; + import info.nightscout.androidaps.R; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; import info.nightscout.shared.SafeParse; @@ -23,7 +25,7 @@ public class Steampunk extends BaseWatchFace { private float lastEndDegrees = 0f; private float deltaRotationAngle = 0f; - @Override + @SuppressLint("InflateParams") @Override public void onCreate() { forceSquareCanvas = true; super.onCreate(); @@ -35,22 +37,22 @@ public class Steampunk extends BaseWatchFace { @Override protected void onTapCommand(int tapType, int x, int y, long eventTime) { - if (tapType == TAP_TYPE_TAP&& + if (tapType == TAP_TYPE_TAP && x >= mChartTap.getLeft() && - x <= mChartTap.getRight()&& + x <= mChartTap.getRight() && y >= mChartTap.getTop() && - y <= mChartTap.getBottom()){ - if (eventTime - chartTapTime < 800){ + y <= mChartTap.getBottom()) { + if (eventTime - chartTapTime < 800) { changeChartTimeframe(); } chartTapTime = eventTime; - } else if (tapType == TAP_TYPE_TAP&& + } else if (tapType == TAP_TYPE_TAP && x >= mMainMenuTap.getLeft() && - x <= mMainMenuTap.getRight()&& + x <= mMainMenuTap.getRight() && y >= mMainMenuTap.getTop() && - y <= mMainMenuTap.getBottom()){ - if (eventTime - mainMenuTapTime < 800){ + y <= mMainMenuTap.getBottom()) { + if (eventTime - mainMenuTapTime < 800) { Intent intent = new Intent(this, MainMenuActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); @@ -67,7 +69,7 @@ public class Steampunk extends BaseWatchFace { protected void setColorDark() { if (mLinearLayout2 != null) { - if (ageLevel() <= 0 && rawData.datetime != 0) { + if (ageLevel() <= 0 && singleBg.getTimeStamp() != 0) { mLinearLayout2.setBackgroundResource(R.drawable.redline); mTimestamp.setTextColor(getResources().getColor(R.color.red_600)); } else { @@ -84,30 +86,32 @@ public class Steampunk extends BaseWatchFace { } } - if (!rawData.sSgv.equals("---")) { + if (!singleBg.getSgvString().equals("---")) { float rotationAngle = 0f; //by default, show ? on the dial (? is at 0 degrees on the dial) - if (!rawData.sUnits.equals("-")) { + if (!singleBg.getGlucoseUnits().equals("-")) { //ensure the glucose dial is the correct units - if (rawData.sUnits.equals("mmol")) { + if (singleBg.getGlucoseUnits().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 + if (singleBg.getGlucoseUnits().equals("mmol")) { + rotationAngle = SafeParse.stringToFloat(singleBg.getSgvString()) * 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. + rotationAngle = SafeParse.stringToFloat(singleBg.getSgvString()); //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 (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 @@ -124,51 +128,54 @@ public class Steampunk extends BaseWatchFace { //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 + if (!singleBg.getAvgDelta().equals("--")) { //if a legitimate delta value is + // received, + // then... + if (singleBg.getAvgDelta().charAt(0) == '-') + deltaIsNegative = -1f; //if the delta is negative, go counter-clockwise + Float AbssAvgDelta = SafeParse.stringToFloat(singleBg.getAvgDelta().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 + if (!singleBg.getGlucoseUnits().equals("-")) { + if (singleBg.getGlucoseUnits().equals("mmol")) { + if (sp.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 + 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 + autogranularity = "2"; // medium if below 0.5 mmol/l } } - if (sharedPrefs.getString("delta_granularity", "2").equals("1") || autogranularity.equals("1")) { //low + if (sp.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 + if (sp.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 + if (sp.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 + if (sp.getString("delta_granularity", "2").equals("4")) { //Auto granularity autogranularity = "1"; // low (init) - if (AbssAvgDelta < 5 ) { - autogranularity = "3" ; // high if below 5 mg/dl + if (AbssAvgDelta < 5) { + autogranularity = "3"; // high if below 5 mg/dl } else if (AbssAvgDelta < 10) { - autogranularity = "2" ; // medium if below 10 mg/dl + autogranularity = "2"; // medium if below 10 mg/dl } } - if (sharedPrefs.getString("delta_granularity", "2").equals("1") || autogranularity.equals("1")) { //low + if (sp.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 + if (sp.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 + if (sp.getString("delta_granularity", "2").equals("3") || autogranularity.equals("3")) { //high mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_5); deltaRotationAngle = (AbssAvgDelta * 6f); } @@ -179,10 +186,10 @@ public class Steampunk extends BaseWatchFace { } //rotate the minute hand. - mMinuteHand.setRotation(Float.valueOf(sMinute) * 6f); + mMinuteHand.setRotation(Float.parseFloat(sMinute) * 6f); //rotate the hour hand. - mHourHand.setRotation((Float.valueOf(sHour) * 30f) + (Float.valueOf(sMinute) * 0.5f)); + mHourHand.setRotation((Float.parseFloat(sHour) * 30f) + (Float.parseFloat(sMinute) * 0.5f)); setTextSizes(); @@ -197,7 +204,7 @@ public class Steampunk extends BaseWatchFace { 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) { + if (sp.getInt("chart_timeframe", 3) < 3) { pointSize = 2; } else { pointSize = 1; @@ -232,7 +239,7 @@ public class Steampunk extends BaseWatchFace { //top row. large font unless text too big (i.e. detailedIOB) mCOB2.setTextSize(fontLarge); mBasalRate.setTextSize(fontLarge); - if (rawData.sIOB2.length() < 7) { + if (status.getIobDetail().length() < 7) { mIOB2.setTextSize(fontLarge); } else { mIOB2.setTextSize(fontSmall); @@ -248,7 +255,8 @@ public class Steampunk extends BaseWatchFace { } //if both batteries are shown, make them smaller. - if (sharedPrefs.getBoolean("show_uploader_battery", true) && sharedPrefs.getBoolean("show_rig_battery", false)) { + if (sp.getBoolean("show_uploader_battery", true) && sp.getBoolean( + "show_rig_battery", false)) { mUploaderBattery.setTextSize(fontSmall); mRigBattery.setTextSize(fontSmall); } else { @@ -258,14 +266,14 @@ public class Steampunk extends BaseWatchFace { } private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - timeframe = (timeframe%5) + 1; + int timeframe = sp.getInt("chart_timeframe", 3); + timeframe = (timeframe % 5) + 1; if (timeframe < 3) { pointSize = 2; } else { pointSize = 1; } setupCharts(); - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); + sp.putString("chart_timeframe", "" + timeframe); } } diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 56709347c7..b4f91135a5 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -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,15 @@ 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 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 f6fefeefd6..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); - - // THEN - assertBasalsOk(newRaw); - } - - @Test - public void updateBasalsFromEmptyMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateBasalsFromMessage(intent); - - // 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 index e6469b0110..d563cdcddb 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java @@ -106,10 +106,10 @@ public class DisplayFormatTest extends TestBase { @Test public void shortTrendTest() { - RawDisplayData raw = new RawDisplayData(wearUtil); + RawDisplayData raw = new RawDisplayData(); assertEquals(displayFormat.shortTrend(raw), "-- Δ--"); - raw.datetime = wearUtilMocker.backInTime(0, 0, 2, 0); + raw.getSingleBg().setTimeStamp(wearUtilMocker.backInTime(0, 0, 2, 0)); assertEquals(displayFormat.shortTrend(raw), "2' Δ--"); when(sp.getBoolean("complication_unicode", true)).thenReturn(true); 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 index b879ff440e..dcfbf5235e 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java @@ -2,12 +2,7 @@ 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; @@ -42,62 +37,6 @@ public class PersistenceTest extends TestBase { 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 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..3c4fbe283a 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() { 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 index a6bdf446f9..b6aa2318e9 100644 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java @@ -3,70 +3,138 @@ package info.nightscout.androidaps.testing.mockers; import info.nightscout.androidaps.data.RawDisplayData; import info.nightscout.androidaps.interaction.utils.WearUtil; import info.nightscout.shared.SafeParse; +import info.nightscout.shared.weardata.EventData; @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; - + RawDisplayData raw = new RawDisplayData(); double delta = SafeParse.stringToDouble(deltaString); + String d; if (delta <= (-3.5 * 5)) { - raw.sDirection = "\u21ca"; + d = "\u21ca"; } else if (delta <= (-2 * 5)) { - raw.sDirection = "\u2193"; + d = "\u2193"; } else if (delta <= (-1 * 5)) { - raw.sDirection = "\u2198"; + d = "\u2198"; } else if (delta <= (1 * 5)) { - raw.sDirection = "\u2192"; + d = "\u2192"; } else if (delta <= (2 * 5)) { - raw.sDirection = "\u2197"; + d = "\u2197"; } else if (delta <= (3.5 * 5)) { - raw.sDirection = "\u2191"; + d = "\u2191"; } else { - raw.sDirection = "\u21c8"; + d = "\u21c8"; } - + raw.setSingleBg( + new EventData.SingleBg( + wearUtilMocker.backInTime(0, 0, m, 0), + sgv, + "", + d, + deltaString, + "", + 0, + 0.0, + 0.0, + 0.0, + 0 + ) + ); 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; + RawDisplayData raw = new RawDisplayData(); + raw.setSingleBg( + new EventData.SingleBg( + wearUtilMocker.backInTime(0, 0, m, 0), + "", + "", + "", + delta, + "", + 0, + 0.0, + 0.0, + 0.0, + 0 + ) + ); 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; + RawDisplayData raw = new RawDisplayData(); + raw.setStatus( + new EventData.Status( + "", + iob, + "", + true, + cob, + br, + "", + "", + 0L, + "", + true, + 0 + + ) + ); return raw; } public RawDisplayData rawIob(String iob, String iob2) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.sIOB1 = iob; - raw.sIOB2 = iob2; + RawDisplayData raw = new RawDisplayData(); + raw.setStatus( + new EventData.Status( + "", + iob, + iob2, + true, + "", + "", + "", + "", + 0L, + "", + true, + 0 + + ) + ); return raw; } public RawDisplayData rawCob(String cob) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.sCOB2 = cob; + RawDisplayData raw = new RawDisplayData(); + raw.setStatus( + new EventData.Status( + "", + "", + "", + true, + cob, + "", + "", + "", + 0L, + "", + true, + 0 + + ) + ); return raw; } 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); - } - -} From aea1fde34ebccf93aecfea8aba6aefb725a78b41 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Apr 2022 23:00:05 +0200 Subject: [PATCH 03/54] AAPSPreferences -> kt --- .../interaction/AAPSPreferences.java | 35 ------------------- .../androidaps/interaction/AAPSPreferences.kt | 29 +++++++++++++++ 2 files changed, 29 insertions(+), 35 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.kt 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/AAPSPreferences.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.kt new file mode 100644 index 0000000000..e02f3fb2ad --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.kt @@ -0,0 +1,29 @@ +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 AAPSPreferences : 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 From 5ca9390f07b219fd49e31214816277947318d6d3 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Apr 2022 23:14:41 +0200 Subject: [PATCH 04/54] AcceptActivity -> kt --- .../interaction/actions/AcceptActivity.java | 169 ------------------ .../interaction/actions/AcceptActivity.kt | 135 ++++++++++++++ 2 files changed, 135 insertions(+), 169 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt 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 a5feccda80..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java +++ /dev/null @@ -1,169 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import static info.nightscout.androidaps.comm.DataLayerListenerServiceWear.KEY_ACTION_DATA; - -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.events.EventWearToMobile; -import info.nightscout.shared.weardata.EventData; - -/** - * Created by adrian on 09/02/17. - */ - -public class AcceptActivity extends ViewSelectorActivity { - - String message = ""; - String actionKey = ""; - 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", ""); - actionKey = extras.getString(KEY_ACTION_DATA, ""); - - if (message.isEmpty() || actionKey.isEmpty()) { - 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(); - } - - @SuppressWarnings("deprecation") - 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) { - - final View view; - if (col == 0) { - 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((v, 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(); - } else { - view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmButton = view.findViewById(R.id.confirmbutton); - confirmButton.setOnClickListener((View v) -> { - EventData returnCommand = EventData.Companion.deserialize(actionKey); - rxBus.send(new EventWearToMobile(returnCommand)); - rxBus.send(new EventData.CancelNotification(System.currentTimeMillis())); - 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 re-init? - 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..4a612697ac --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt @@ -0,0 +1,135 @@ +@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.events.EventWearToMobile +import info.nightscout.shared.weardata.EventData.CancelNotification +import info.nightscout.shared.weardata.EventData.Companion.deserialize +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("message", "") + actionKey = extras.getString(DataLayerListenerServiceWear.KEY_ACTION_DATA, "") + if (message.isEmpty() || actionKey.isEmpty()) { + finish() + return + } + setAdapter(MyGridViewPagerAdapter()) + val v = getSystemService(VIBRATOR_SERVICE) as Vibrator + val vibratePattern = longArrayOf(0, 100, 50, 100, 50) + v.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_send_item, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + val returnCommand = deserialize(actionKey) + rxBus.send(EventWearToMobile(returnCommand)) + rxBus.send(CancelNotification(System.currentTimeMillis())) + 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) + if (dismissThread != null) dismissThread!!.invalidate() + val extras = intent.extras + val msgIntent = Intent(this, AcceptActivity::class.java) + msgIntent.putExtras(extras!!) + startActivity(msgIntent) + finish() + } +} \ No newline at end of file From ffdcf9900b937fe928d8fd2ad27aef0beeb630c2 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 00:05:10 +0200 Subject: [PATCH 05/54] BolusActivity -> kt --- .../interaction/actions/BolusActivity.java | 86 -------------- .../interaction/actions/BolusActivity.kt | 65 ++++++++++ .../actions/ViewSelectorActivity.java | 112 ------------------ .../actions/ViewSelectorActivity.kt | 92 ++++++++++++++ .../interaction/menus/MainMenuActivity.kt | 3 + 5 files changed, 160 insertions(+), 198 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt 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 372330ca7f..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java +++ /dev/null @@ -1,86 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -public class BolusActivity extends ViewSelectorActivity { - - PlusMinusEditText editInsulin; - double maxBolus; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - maxBolus = sp.getDouble(getString(R.string.key_treatmentssafety_maxbolus), 3.0); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - @SuppressWarnings("deprecation") - 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) { - - final View view; - if (col == 0) { - 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, maxBolus, 0.1d, new DecimalFormat("#0.0"), false); - setLabelToPlusMinusView(view, getString(R.string.action_insulin)); - container.addView(view); - view.requestFocus(); - } else { - view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmButton = view.findViewById(R.id.confirmbutton); - confirmButton.setOnClickListener((View v) -> { - rxBus.send(new EventWearToMobile(new EventData.ActionBolusPreCheck(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), 0))); - showToast(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..890da028fb --- /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_treatmentssafety_maxbolus), 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_send_item, 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/ViewSelectorActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java deleted file mode 100644 index a5aaa18768..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java +++ /dev/null @@ -1,112 +0,0 @@ -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 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 13/02/17. - */ - -public class ViewSelectorActivity extends DaggerActivity { - - @Inject SP sp; - @Inject RxBus rxBus; - - 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) { - int design = sp.getInt("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 showToast(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/menus/MainMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt index 4f37ea33dd..8663b50073 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt @@ -5,6 +5,7 @@ import android.os.Bundle import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventWearToMobile import info.nightscout.androidaps.interaction.AAPSPreferences +import info.nightscout.androidaps.interaction.actions.BolusActivity import info.nightscout.androidaps.interaction.actions.ECarbActivity import info.nightscout.androidaps.interaction.actions.TempTargetActivity import info.nightscout.androidaps.interaction.actions.TreatmentActivity @@ -31,6 +32,7 @@ class MainMenuActivity : MenuListActivity() { 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_bolus, getString(R.string.menu_bolus))) add(MenuItem(R.drawable.ic_temptarget, getString(R.string.menu_tempt))) add(MenuItem(R.drawable.ic_status, getString(R.string.status_cpp))) add(MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))) @@ -47,6 +49,7 @@ class MainMenuActivity : MenuListActivity() { getString(R.string.status_cpp) -> 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_bolus) -> startActivity(Intent(this, BolusActivity::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) }) From 1306388a459e32d5a764e9c71d2a141c09217758 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 09:55:21 +0200 Subject: [PATCH 06/54] ActionsTileService: Missing injection --- .../java/info/nightscout/androidaps/di/WearServicesModule.kt | 2 ++ 1 file changed, 2 insertions(+) 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 800aa4205a..4894e25027 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt @@ -4,6 +4,7 @@ import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.comm.DataLayerListenerServiceWear import info.nightscout.androidaps.complications.* +import info.nightscout.androidaps.tile.ActionsTileService import info.nightscout.androidaps.tile.QuickWizardTileService import info.nightscout.androidaps.tile.TempTargetTileService import info.nightscout.androidaps.tile.TileBase @@ -44,4 +45,5 @@ abstract class WearServicesModule { @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 From fc33d78418a06b722f485c6d612d7289c4b00567 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 10:13:01 +0200 Subject: [PATCH 07/54] CarbActivity -> kt --- .../androidaps/di/WearActivitiesModule.kt | 3 + .../interaction/TileConfigurationActivity.kt | 38 ++++---- .../interaction/actions/CarbActivity.java | 96 ------------------- .../interaction/actions/CarbActivity.kt | 72 ++++++++++++++ .../interaction/menus/MainMenuActivity.kt | 2 - .../androidaps/watchfaces/BaseWatchFace.java | 1 + 6 files changed, 98 insertions(+), 114 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt index 90ef38717e..222c1eb794 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.di import dagger.Module import dagger.android.ContributesAndroidInjector +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 @@ -12,6 +13,8 @@ import info.nightscout.androidaps.interaction.utils.MenuListActivity @Suppress("unused") abstract class WearActivitiesModule { + @ContributesAndroidInjector abstract fun contributesTileConfigurationActivity(): TileConfigurationActivity + @ContributesAndroidInjector abstract fun contributesBackgroundActionActivity(): BackgroundActionActivity @ContributesAndroidInjector abstract fun contributesViewSelectorActivity(): ViewSelectorActivity 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..8a7591e957 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt @@ -1,17 +1,19 @@ 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 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?) { @@ -19,8 +21,8 @@ class TileConfigurationActivity : WearPreferenceActivity() { 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 +31,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/actions/CarbActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java deleted file mode 100644 index fe6f9c6767..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java +++ /dev/null @@ -1,96 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -public class CarbActivity extends ViewSelectorActivity { - - PlusMinusEditText editCarbs; - int maxCarbs; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - @SuppressWarnings("deprecation") - 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) { - - final View view; - if (col == 0) { - 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(); - } else { - 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 - EventData.ActionECarbsPreCheck bolus = - new EventData.ActionECarbsPreCheck( - SafeParse.stringToInt(editCarbs.editText.getText().toString()), - 0, - 0 - ); - rxBus.send(new EventWearToMobile(bolus)); - showToast(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 re-init? - 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..ed4472b6bd --- /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_treatmentssafety_maxcarbs), 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_send_item, 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/menus/MainMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt index 8663b50073..d3c5b1b7f8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt @@ -32,7 +32,6 @@ class MainMenuActivity : MenuListActivity() { 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_bolus, getString(R.string.menu_bolus))) add(MenuItem(R.drawable.ic_temptarget, getString(R.string.menu_tempt))) add(MenuItem(R.drawable.ic_status, getString(R.string.status_cpp))) add(MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))) @@ -49,7 +48,6 @@ class MainMenuActivity : MenuListActivity() { getString(R.string.status_cpp) -> 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_bolus) -> startActivity(Intent(this, BolusActivity::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) }) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java index 8c44241e6b..7668b8ce40 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java @@ -172,6 +172,7 @@ public abstract class BaseWatchFace extends WatchFace { .toObservable(EventData.Status.class) .observeOn(aapsSchedulers.getMain()) .subscribe(event -> { + status = event; // this event is received as last batch of data if (isSimpleUi()) { if (needUpdate()) { From 3311a1a6f674b4f003e507ad36ce7d7ad76517b9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 10:27:53 +0200 Subject: [PATCH 08/54] Wear: Tile cleanup --- .../info/nightscout/androidaps/tile/QuickWizardTileService.kt | 3 +-- .../info/nightscout/androidaps/tile/TempTargetTileService.kt | 1 - .../src/main/java/info/nightscout/androidaps/tile/TileBase.kt | 4 ++-- 3 files changed, 3 insertions(+), 5 deletions(-) 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..d6afa427f9 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,7 @@ package info.nightscout.androidaps.tile -const val TAG = "QuickWizard" - class QuickWizardTileService : TileBase() { + override val resourceVersion = "QuickWizardTileService" override val source = QuickWizardSource } 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..1f315fb2b8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetTileService.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetTileService.kt @@ -4,5 +4,4 @@ class TempTargetTileService : TileBase() { override val resourceVersion = "TempTargetTileService" override val source = 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 7fd3cbf5c9..069883ee03 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt @@ -289,10 +289,10 @@ abstract class TileBase : TileService() { } private fun getWearControl(): WearControl { - if (!sp.contains("wearcontrol")) { + if (!sp.contains(R.string.key_wear_control)) { return WearControl.NO_DATA } - val wearControlPref = sp.getBoolean("wearcontrol", false) + val wearControlPref = sp.getBoolean(R.string.key_wear_control, false) if (wearControlPref) { return WearControl.ENABLED } From 9a90400f374f01840e97c7f61b131f6f34c603a6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 10:39:28 +0200 Subject: [PATCH 09/54] Wear: ConfigurationActivities cleanup --- wear/src/main/AndroidManifest.xml | 2 +- .../androidaps/comm/DataHandlerWear.kt | 4 +- .../androidaps/di/WearActivitiesModule.kt | 2 + .../interaction/ConfigurationActivity.java | 47 ------------------- .../interaction/ConfigurationActivity.kt | 44 +++++++++++++++++ .../interaction/TileConfigurationActivity.kt | 2 + ...s.kt => WatchfaceConfigurationActivity.kt} | 8 ++-- .../interaction/menus/MainMenuActivity.kt | 5 +- 8 files changed, 56 insertions(+), 58 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt rename wear/src/main/java/info/nightscout/androidaps/interaction/{AAPSPreferences.kt => WatchfaceConfigurationActivity.kt} (82%) diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index cd0fd89207..cafa9ae3ed 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -548,7 +548,7 @@ > 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 8a7591e957..f872266bc6 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.interaction import android.os.Bundle import android.view.ViewGroup import androidx.wear.tiles.TileService +import dagger.android.AndroidInjection import info.nightscout.androidaps.tile.ActionsTileService import info.nightscout.androidaps.tile.TempTargetTileService import info.nightscout.shared.logging.AAPSLogger @@ -17,6 +18,7 @@ class TileConfigurationActivity : WearPreferenceActivity() { private var configFileName: String? = null override fun onCreate(savedInstanceState: Bundle?) { + AndroidInjection.inject(this) super.onCreate(savedInstanceState) title = "Tile" configFileName = intent.action diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt similarity index 82% rename from wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.kt rename to wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt index e02f3fb2ad..2b06023155 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt @@ -7,7 +7,7 @@ import androidx.core.content.ContextCompat import info.nightscout.androidaps.R import preference.WearPreferenceActivity -class AAPSPreferences : WearPreferenceActivity() { +class WatchfaceConfigurationActivity : WearPreferenceActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -19,11 +19,9 @@ class AAPSPreferences : WearPreferenceActivity() { } private fun removeBackgroundRecursively(parent: View) { - if (parent is ViewGroup) { - for (i in 0 until parent.childCount) { + 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/menus/MainMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt index d3c5b1b7f8..e0091b1392 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt @@ -4,8 +4,7 @@ import android.content.Intent import android.os.Bundle import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventWearToMobile -import info.nightscout.androidaps.interaction.AAPSPreferences -import info.nightscout.androidaps.interaction.actions.BolusActivity +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 @@ -43,7 +42,7 @@ class MainMenuActivity : MenuListActivity() { override fun doAction(action: String) { when (action) { - getString(R.string.menu_settings) -> startActivity(Intent(this, AAPSPreferences::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + 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_cpp) -> 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) }) From 59394e5260e53a07de266a4634adcb6a984a1419 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 11:29:21 +0200 Subject: [PATCH 10/54] ProfileSwitchActivity -> kt --- wear/src/main/AndroidManifest.xml | 4 +- .../androidaps/comm/DataHandlerWear.kt | 4 +- .../androidaps/di/WearActivitiesModule.kt | 2 +- .../interaction/TileConfigurationActivity.kt | 4 +- .../interaction/actions/AcceptActivity.kt | 21 ++- .../interaction/actions/CPPActivity.java | 121 ------------------ .../actions/ProfileSwitchActivity.kt | 94 ++++++++++++++ .../interaction/menus/MainMenuActivity.kt | 20 +-- wear/src/main/res/values/strings.xml | 4 +- 9 files changed, 122 insertions(+), 152 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index cafa9ae3ed..d7041e76cb 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -569,8 +569,8 @@ android:exported="true" android:label="@string/action_insulin" /> + android:name=".interaction.actions.ProfileSwitchActivity" + android:label="@string/status_profile_switch" /> aapsLogger.debug(LTag.WEAR, "ActionProfileSwitchOpenActivity received from ${event.sourceNodeId}") - context.startActivity(Intent(context, CPPActivity::class.java).apply { + context.startActivity(Intent(context, ProfileSwitchActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) putExtras(Bundle().also { bundle -> bundle.putInt("percentage", event.percentage) diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt index 295dc638e7..18a63adb66 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt @@ -23,7 +23,7 @@ abstract class WearActivitiesModule { @ContributesAndroidInjector abstract fun contributesAcceptActivity(): AcceptActivity @ContributesAndroidInjector abstract fun contributesBolusActivity(): BolusActivity @ContributesAndroidInjector abstract fun contributesCarbActivity(): CarbActivity - @ContributesAndroidInjector abstract fun contributesCPPActivity(): CPPActivity + @ContributesAndroidInjector abstract fun contributesProfileSwitchActivity(): ProfileSwitchActivity @ContributesAndroidInjector abstract fun contributesECarbActivity(): ECarbActivity @ContributesAndroidInjector abstract fun contributesFillActivity(): FillActivity @ContributesAndroidInjector abstract fun contributesTempTargetActivity(): TempTargetActivity 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 f872266bc6..ccf19933fb 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt @@ -35,12 +35,12 @@ class TileConfigurationActivity : WearPreferenceActivity() { // Note that TileService updates are hard limited to once every 20 seconds. when { configFileName === "tile_configuration_activity" -> { - aapsLogger.info(LTag.WEAR, "onDestroy a: requestUpdate!!") + 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!!") + aapsLogger.info(LTag.WEAR, "onDestroy tt: requestUpdate") TileService.getUpdater(this).requestUpdate(TempTargetTileService::class.java) } 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 index 4a612697ac..47b4aca051 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt @@ -33,10 +33,10 @@ class AcceptActivity : ViewSelectorActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) dismissThread = DismissThread() - dismissThread!!.start() + dismissThread?.start() val extras = intent.extras - message = extras!!.getString("message", "") - actionKey = extras.getString(DataLayerListenerServiceWear.KEY_ACTION_DATA, "") + message = extras?.getString("message", "") ?: "" + actionKey = extras?.getString(DataLayerListenerServiceWear.KEY_ACTION_DATA, "") ?: "" if (message.isEmpty() || actionKey.isEmpty()) { finish() return @@ -117,19 +117,16 @@ class AcceptActivity : ViewSelectorActivity() { override fun run() { SystemClock.sleep((60 * 1000L)) - synchronized(this) { - if (valid) finish() - } + synchronized(this) { if (valid) finish() } } } @Synchronized override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) - if (dismissThread != null) dismissThread!!.invalidate() - val extras = intent.extras - val msgIntent = Intent(this, AcceptActivity::class.java) - msgIntent.putExtras(extras!!) - startActivity(msgIntent) - finish() + 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/CPPActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java deleted file mode 100644 index c0b6cedb33..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java +++ /dev/null @@ -1,121 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -/** - * 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(); - } - - @SuppressWarnings("deprecation") - 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 fragment is never created that hold data? - // (you have to swipe past them anyways - but still) - EventData.ActionProfileSwitchPreCheck ps = - new EventData.ActionProfileSwitchPreCheck(SafeParse.stringToInt(editTimeshift.editText.getText().toString()), SafeParse.stringToInt(editPercentage.editText.getText().toString())); - rxBus.send(new EventWearToMobile(ps)); - showToast(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 re-init? - 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/ProfileSwitchActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt new file mode 100644 index 0000000000..0ee7ec7ba3 --- /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_send_item, 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/menus/MainMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt index e0091b1392..9cc84c832c 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt @@ -32,7 +32,7 @@ class MainMenuActivity : MenuListActivity() { 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_cpp))) + 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)) @@ -42,15 +42,15 @@ class MainMenuActivity : MenuListActivity() { 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_cpp) -> 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) }) + 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/res/values/strings.xml b/wear/src/main/res/values/strings.xml index b4f91135a5..648f1745e2 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -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 From 572032095873a31385bea715e3a9e54a95a2de75 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 11:33:23 +0200 Subject: [PATCH 11/54] ECarbActivity -> kt --- .../interaction/actions/ECarbActivity.java | 126 ------------------ .../interaction/actions/ECarbActivity.kt | 101 ++++++++++++++ 2 files changed, 101 insertions(+), 126 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt 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 3b8f548c59..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java +++ /dev/null @@ -1,126 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -/** - * 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()); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - @SuppressWarnings("deprecation") - 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 fragment is never created that hold data? - // (you have to swipe past them anyways - but still) - - EventData.ActionECarbsPreCheck bolus = - new EventData.ActionECarbsPreCheck( - SafeParse.stringToInt(editCarbs.editText.getText().toString()), - SafeParse.stringToInt(editStartTime.editText.getText().toString()), - SafeParse.stringToInt(editDuration.editText.getText().toString()) - ); - rxBus.send(new EventWearToMobile(bolus)); - showToast(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 re-init? - 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..6fcc695fc2 --- /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_treatmentssafety_maxcarbs), 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_send_item, 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 From d94ab441da0b8e8cbee6e6a1a324be4a0b6f4bb9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 11:35:16 +0200 Subject: [PATCH 12/54] FillActivity -> kt --- .../interaction/actions/FillActivity.java | 94 ------------------- .../interaction/actions/FillActivity.kt | 71 ++++++++++++++ 2 files changed, 71 insertions(+), 94 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt 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 c7cbb892ce..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java +++ /dev/null @@ -1,94 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -/** - * 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(); - } - - @SuppressWarnings("deprecation") - 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) - - rxBus.send(new EventWearToMobile(new EventData.ActionFillPreCheck(SafeParse.stringToDouble(editInsulin.editText.getText().toString())))); - showToast(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..20e9346174 --- /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_send_item, 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 From 70d96d42ccb19bbbbe6006d5f2d8a78c05afb958 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 11:46:46 +0200 Subject: [PATCH 13/54] TempTargetActivity -> kt --- .../androidaps/comm/DataHandlerWear.kt | 6 +- .../interaction/actions/BolusActivity.kt | 2 +- .../interaction/actions/CarbActivity.kt | 2 +- .../interaction/actions/ECarbActivity.kt | 2 +- .../actions/TempTargetActivity.java | 152 ------------------ .../interaction/actions/TempTargetActivity.kt | 122 ++++++++++++++ .../actions/TreatmentActivity.java | 4 +- .../interaction/actions/WizardActivity.java | 4 +- wear/src/main/res/values/strings.xml | 7 +- wear/src/main/res/xml/preferences.xml | 2 +- 10 files changed, 137 insertions(+), 166 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt index a1e2b1a5ad..d457732323 100644 --- a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt @@ -179,9 +179,9 @@ class DataHandlerWear @Inject constructor( } } sp.putBoolean(R.string.key_units_mgdl, it.unitsMgdl) - sp.putInt(R.string.key_boluswizard_percentage, it.bolusPercentage) - sp.putInt(R.string.key_treatmentssafety_maxcarbs, it.maxCarbs) - sp.putDouble(R.string.key_treatmentssafety_maxbolus, it.maxBolus) + 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) 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 index 890da028fb..979ba52887 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt @@ -38,7 +38,7 @@ class BolusActivity : ViewSelectorActivity() { 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_treatmentssafety_maxbolus), 3.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) 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 index ed4472b6bd..44d226debd 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt @@ -41,7 +41,7 @@ class CarbActivity : ViewSelectorActivity() { if (editCarbs != null) { def = SafeParse.stringToDouble(editCarbs?.editText?.text.toString()) } - val maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48) + 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) 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 index 6fcc695fc2..c0207f6baa 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt @@ -43,7 +43,7 @@ class ECarbActivity : ViewSelectorActivity() { if (editCarbs != null) { def = stringToDouble(editCarbs?.editText?.text.toString()) } - val maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48) + 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) 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 22cb47811f..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java +++ /dev/null @@ -1,152 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -/** - * 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()); - - isMGDL = sp.getBoolean("units_mgdl", true); - isSingleTarget = sp.getBoolean("singletarget", true); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - @SuppressWarnings("deprecation") - 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 fragment is never created that hold data? - // (you have to swipe past them anyways - but still) - - EventData.ActionTempTargetPreCheck action = new EventData.ActionTempTargetPreCheck( - EventData.ActionTempTargetPreCheck.TempTargetCommand.MANUAL, - 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())) - ); - rxBus.send(new EventWearToMobile(action)); - showToast(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 re-init? - 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..d999a61eb1 --- /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_send_item, 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 index fa353128ba..d523eebbd4 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java @@ -30,8 +30,8 @@ public class TreatmentActivity extends ViewSelectorActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setAdapter(new MyGridViewPagerAdapter()); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - maxBolus = sp.getDouble(getString(R.string.key_treatmentssafety_maxbolus), 3.0); + maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48); + maxBolus = sp.getDouble(getString(R.string.key_treatments_safety_max_bolus), 3.0); } @Override 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 index 698c3fc59d..4917a34dcd 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java @@ -33,8 +33,8 @@ public class WizardActivity extends ViewSelectorActivity { super.onCreate(savedInstanceState); setAdapter(new MyGridViewPagerAdapter()); 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); + percentage = sp.getInt(getString(R.string.key_bolus_wizard_percentage), 100); + maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48); } @Override diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 648f1745e2..8d8ce23c8e 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -187,11 +187,12 @@ QuickWizard wearcontrol units_mgdl - boluswizard_percentage - treatmentssafety_maxcarbs - treatmentssafety_maxbolus + boluswizard_percentage + treatmentssafety_maxcarbs + treatmentssafety_maxbolus quick_wizard_data primefill showWizard + singletarget diff --git a/wear/src/main/res/xml/preferences.xml b/wear/src/main/res/xml/preferences.xml index efadbc39d9..3ec4a5bbec 100644 --- a/wear/src/main/res/xml/preferences.xml +++ b/wear/src/main/res/xml/preferences.xml @@ -134,7 +134,7 @@ Date: Sat, 23 Apr 2022 11:52:35 +0200 Subject: [PATCH 14/54] TreatmentActivity -> kt --- .../actions/TreatmentActivity.java | 110 ------------------ .../interaction/actions/TreatmentActivity.kt | 82 +++++++++++++ 2 files changed, 82 insertions(+), 110 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt 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 d523eebbd4..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java +++ /dev/null @@ -1,110 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -/** - * Created by adrian on 09/02/17. - */ - -public class TreatmentActivity extends ViewSelectorActivity { - - PlusMinusEditText editCarbs; - PlusMinusEditText editInsulin; - int maxCarbs; - double maxBolus; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48); - maxBolus = sp.getDouble(getString(R.string.key_treatments_safety_max_bolus), 3.0); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - - @SuppressWarnings("deprecation") - 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 fragment is never created that hold data? - // (you have to swipe past them anyways - but still) - EventData.ActionBolusPreCheck bolus = new EventData.ActionBolusPreCheck(SafeParse.stringToDouble(editInsulin.editText.getText().toString()), SafeParse.stringToInt(editCarbs.editText.getText().toString())); - rxBus.send(new EventWearToMobile(bolus)); - showToast(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 re-init? - 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..661d4cb421 --- /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_send_item, 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 From 7050cd507c0f3586b705f330e9ff83b953bc82c0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 12:00:35 +0200 Subject: [PATCH 15/54] WizardActivity -> kt --- .../interaction/actions/WizardActivity.java | 119 ------------------ .../interaction/actions/WizardActivity.kt | 90 +++++++++++++ wear/src/main/res/values/strings.xml | 1 + wear/src/main/res/xml/preferences.xml | 2 +- 4 files changed, 92 insertions(+), 120 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt 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 4917a34dcd..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java +++ /dev/null @@ -1,119 +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.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.EventData; - -/** - * 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()); - hasPercentage = sp.getBoolean("wizardpercentage", false); - percentage = sp.getInt(getString(R.string.key_bolus_wizard_percentage), 100); - maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - @SuppressWarnings("deprecation") - 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()); - } - - EventData.ActionWizardPreCheck action = new EventData.ActionWizardPreCheck( - SafeParse.stringToInt(editCarbs.editText.getText().toString()), - percentage - ); - rxBus.send(new EventWearToMobile(action)); - showToast(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 re-init? - 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..2443c0923a --- /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_send_item, 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/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 8d8ce23c8e..7561a48cf5 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -194,5 +194,6 @@ primefill showWizard singletarget + wizardpercentage diff --git a/wear/src/main/res/xml/preferences.xml b/wear/src/main/res/xml/preferences.xml index 3ec4a5bbec..517d6a982e 100644 --- a/wear/src/main/res/xml/preferences.xml +++ b/wear/src/main/res/xml/preferences.xml @@ -142,7 +142,7 @@ Date: Sat, 23 Apr 2022 12:35:09 +0200 Subject: [PATCH 16/54] Wear: Tile injection --- .../androidaps/di/WearServicesModule.kt | 6 +-- .../androidaps/tile/ActionSource.kt | 8 +++- .../androidaps/tile/ActionsTileService.kt | 14 +++++- .../androidaps/tile/QuickWizardSource.kt | 9 ++-- .../androidaps/tile/QuickWizardTileService.kt | 13 +++++- .../androidaps/tile/StaticTileSource.kt | 45 +++++++++---------- .../androidaps/tile/TempTargetSource.kt | 8 +++- .../androidaps/tile/TempTargetTileService.kt | 13 +++++- .../nightscout/androidaps/tile/TileBase.kt | 9 ++-- 9 files changed, 83 insertions(+), 42 deletions(-) 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 4894e25027..babfb10af4 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt @@ -4,10 +4,7 @@ import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.comm.DataLayerListenerServiceWear import info.nightscout.androidaps.complications.* -import info.nightscout.androidaps.tile.ActionsTileService -import info.nightscout.androidaps.tile.QuickWizardTileService -import info.nightscout.androidaps.tile.TempTargetTileService -import info.nightscout.androidaps.tile.TileBase +import info.nightscout.androidaps.tile.* import info.nightscout.androidaps.watchfaces.* @Module @@ -46,4 +43,5 @@ abstract class WearServicesModule { @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/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 b03123076f..00993b09bf 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardSource.kt @@ -9,10 +9,13 @@ 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, sp: SP, aapsLogger: AAPSLogger): List { + override fun getSelectedActions(): List { val quickList = mutableListOf() val quickMap = getQuickWizardData(sp) val sfm = secondsFromMidnight() @@ -38,7 +41,7 @@ object QuickWizardSource : TileSource { return quickList } - override fun getValidFor(sp: SP): Long? { + override fun getValidFor(): Long? { val quickMap = getQuickWizardData(sp) if (quickMap.entries.size == 0) return null 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 d6afa427f9..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,7 +1,18 @@ package info.nightscout.androidaps.tile +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 5f27d2e367..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,35 +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, - action: EventData? = null, - message: String? = null, -) : Action(buttonText, buttonTextSub, activityClass, iconRes, action, 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, sp: SP, aapsLogger: AAPSLogger): 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) } @@ -43,23 +41,20 @@ abstract class StaticTileSource : TileSource { return actionList } - override fun getValidFor(sp: SP): 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 48c39de5de..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,12 +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_" 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 1f315fb2b8..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,7 +1,18 @@ package info.nightscout.androidaps.tile +import dagger.android.AndroidInjection +import javax.inject.Inject + class TempTargetTileService : TileBase() { + @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 = TempTargetSource + 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 069883ee03..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,6 +1,5 @@ package info.nightscout.androidaps.tile -import android.content.Context import android.os.Build import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi @@ -49,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, sp: SP, aapsLogger: AAPSLogger): List - fun getValidFor(sp: SP): Long? + fun getSelectedActions(): List + fun getValidFor(): Long? } open class Action( @@ -107,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, sp, aapsLogger) + return source.getSelectedActions() } private fun validFor(): Long? { - return source.getValidFor(sp) + return source.getValidFor() } @RequiresApi(Build.VERSION_CODES.N) From 0dd72922d2e7dab55a32c311c5741c789bd67b60 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 14:09:37 +0200 Subject: [PATCH 17/54] gradle cleaup --- database/build.gradle | 2 +- wear/build.gradle | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/database/build.gradle b/database/build.gradle index 82516d6e33..a524196d9e 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -22,7 +22,7 @@ dependencies { 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/wear/build.gradle b/wear/build.gradle index 93d9e3281b..2bee9762de 100644 --- a/wear/build.gradle +++ b/wear/build.gradle @@ -96,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}" @@ -114,8 +114,6 @@ dependencies { 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 "androidx.core:core-ktx:$core_version" - implementation "androidx.wear.tiles:tiles:1.0.1" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" // for old fashioned support-app version From 68c7b130fbda3ee7b9da02c4662bb2d311b1804d Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 15:29:02 +0200 Subject: [PATCH 18/54] SteampunkWatchface -> kt, eliminate WatchViewStub --- .../general/actions/ActionsFragment.kt | 5 +- wear/src/main/AndroidManifest.xml | 2 +- .../androidaps/di/WearServicesModule.kt | 2 +- .../interaction/actions/AcceptActivity.kt | 2 +- .../interaction/actions/BolusActivity.kt | 2 +- .../interaction/actions/CarbActivity.kt | 2 +- .../interaction/actions/ECarbActivity.kt | 2 +- .../interaction/actions/FillActivity.kt | 2 +- .../actions/ProfileSwitchActivity.kt | 2 +- .../interaction/actions/TempTargetActivity.kt | 2 +- .../interaction/actions/TreatmentActivity.kt | 2 +- .../interaction/actions/WizardActivity.kt | 2 +- .../androidaps/watchfaces/BIGChart.java | 30 +- .../androidaps/watchfaces/BaseWatchFace.java | 95 +++--- .../watchfaces/CircleWatchface.java | 3 +- .../androidaps/watchfaces/Cockpit.java | 1 + .../androidaps/watchfaces/DigitalStyle.java | 1 + .../androidaps/watchfaces/Home.java | 1 + .../androidaps/watchfaces/Home2.java | 1 + .../androidaps/watchfaces/LargeHome.java | 1 + .../androidaps/watchfaces/NOChart.java | 31 +- .../androidaps/watchfaces/Steampunk.java | 279 ------------------ .../watchfaces/SteampunkWatchface.kt | 248 ++++++++++++++++ .../activity_bigchart.xml} | 0 .../activity_bigchart_small.xml} | 0 .../activity_cockpit.xml} | 0 .../activity_digitalstyle.xml} | 0 .../activity_home.xml} | 0 .../activity_home_2.xml} | 0 .../activity_home_large.xml} | 0 .../activity_nochart.xml} | 0 .../activity_nochart_small.xml} | 230 +++++++-------- .../activity_steampunk.xml} | 2 +- .../activity_bigchart.xml} | 0 .../activity_bigchart_small.xml} | 0 .../activity_cockpit.xml} | 0 .../activity_digitalstyle.xml} | 0 .../activity_home.xml} | 0 .../activity_home_2.xml} | 0 .../activity_home_large.xml} | 0 .../activity_nochart.xml} | 0 .../activity_nochart_small.xml} | 230 +++++++-------- .../activity_steampunk.xml} | 2 +- ...on_send_item.xml => action_confirm_ok.xml} | 0 .../src/main/res/layout/activity_bigchart.xml | 12 - .../res/layout/activity_bigchart_small.xml | 12 - ...{modern_layout.xml => activity_circle.xml} | 0 wear/src/main/res/layout/activity_cockpit.xml | 12 - .../main/res/layout/activity_digitalstyle.xml | 13 - wear/src/main/res/layout/activity_home.xml | 12 - wear/src/main/res/layout/activity_home_2.xml | 12 - .../main/res/layout/activity_home_large.xml | 12 - wear/src/main/res/layout/activity_nochart.xml | 12 - .../res/layout/activity_nochart_small.xml | 12 - .../main/res/layout/activity_steampunk.xml | 12 - 55 files changed, 568 insertions(+), 735 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt rename wear/src/main/res/{layout/rect_activity_bigchart.xml => layout-notround/activity_bigchart.xml} (100%) rename wear/src/main/res/{layout/rect_activity_bigchart_small.xml => layout-notround/activity_bigchart_small.xml} (100%) rename wear/src/main/res/{layout/rect_cockpit.xml => layout-notround/activity_cockpit.xml} (100%) rename wear/src/main/res/{layout/rect_activity_digitalstyle.xml => layout-notround/activity_digitalstyle.xml} (100%) rename wear/src/main/res/{layout/rect_activity_home.xml => layout-notround/activity_home.xml} (100%) rename wear/src/main/res/{layout/rect_activity_home_2.xml => layout-notround/activity_home_2.xml} (100%) rename wear/src/main/res/{layout/rect_activity_home_large.xml => layout-notround/activity_home_large.xml} (100%) rename wear/src/main/res/{layout/rect_activity_nochart.xml => layout-notround/activity_nochart.xml} (100%) rename wear/src/main/res/{layout/rect_activity_nochart_small.xml => layout-notround/activity_nochart_small.xml} (97%) rename wear/src/main/res/{layout/rect_steampunk.xml => layout-notround/activity_steampunk.xml} (99%) rename wear/src/main/res/{layout/round_activity_bigchart.xml => layout-round/activity_bigchart.xml} (100%) rename wear/src/main/res/{layout/round_activity_bigchart_small.xml => layout-round/activity_bigchart_small.xml} (100%) rename wear/src/main/res/{layout/round_cockpit.xml => layout-round/activity_cockpit.xml} (100%) rename wear/src/main/res/{layout/round_activity_digitalstyle.xml => layout-round/activity_digitalstyle.xml} (100%) rename wear/src/main/res/{layout/round_activity_home.xml => layout-round/activity_home.xml} (100%) rename wear/src/main/res/{layout/round_activity_home_2.xml => layout-round/activity_home_2.xml} (100%) rename wear/src/main/res/{layout/round_activity_home_large.xml => layout-round/activity_home_large.xml} (100%) rename wear/src/main/res/{layout/round_activity_nochart.xml => layout-round/activity_nochart.xml} (100%) rename wear/src/main/res/{layout/round_activity_nochart_small.xml => layout-round/activity_nochart_small.xml} (97%) rename wear/src/main/res/{layout/round_steampunk.xml => layout-round/activity_steampunk.xml} (99%) rename wear/src/main/res/layout/{action_send_item.xml => action_confirm_ok.xml} (100%) delete mode 100644 wear/src/main/res/layout/activity_bigchart.xml delete mode 100644 wear/src/main/res/layout/activity_bigchart_small.xml rename wear/src/main/res/layout/{modern_layout.xml => activity_circle.xml} (100%) delete mode 100644 wear/src/main/res/layout/activity_cockpit.xml delete mode 100644 wear/src/main/res/layout/activity_digitalstyle.xml delete mode 100644 wear/src/main/res/layout/activity_home.xml delete mode 100644 wear/src/main/res/layout/activity_home_2.xml delete mode 100644 wear/src/main/res/layout/activity_home_large.xml delete mode 100644 wear/src/main/res/layout/activity_nochart.xml delete mode 100644 wear/src/main/res/layout/activity_nochart_small.xml delete mode 100644 wear/src/main/res/layout/activity_steampunk.xml 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..a2e5cf0925 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 @@ -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/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index d7041e76cb..0964bca9fe 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -146,7 +146,7 @@ (R.id.confirmbutton) confirmButton.setOnClickListener { val returnCommand = deserialize(actionKey) 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 index 979ba52887..e7e8b56355 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt @@ -44,7 +44,7 @@ class BolusActivity : ViewSelectorActivity() { container.addView(view) view.requestFocus() } else { - view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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))) 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 index 44d226debd..4dd487bb79 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt @@ -47,7 +47,7 @@ class CarbActivity : ViewSelectorActivity() { container.addView(view) view.requestFocus() } else { - view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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 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 index c0207f6baa..21d7b41f31 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt @@ -70,7 +70,7 @@ class ECarbActivity : ViewSelectorActivity() { container.addView(view) view } else { - val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) val confirmButton = view.findViewById(R.id.confirmbutton) confirmButton.setOnClickListener { 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 index 20e9346174..a10163e466 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt @@ -46,7 +46,7 @@ class FillActivity : ViewSelectorActivity() { view.requestFocus() view } else { - val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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? 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 index 0ee7ec7ba3..73b9551b53 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt @@ -66,7 +66,7 @@ class ProfileSwitchActivity : ViewSelectorActivity() { container.addView(view) view } else { - val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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? 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 index d999a61eb1..cab25b52eb 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt @@ -88,7 +88,7 @@ class TempTargetActivity : ViewSelectorActivity() { container.addView(view) view } else { - val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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? 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 index 661d4cb421..ed504969b1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt @@ -56,7 +56,7 @@ class TreatmentActivity : ViewSelectorActivity() { container.addView(view) view } else { - val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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? 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 index 2443c0923a..53247573a7 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt @@ -63,7 +63,7 @@ class WizardActivity : ViewSelectorActivity() { container.addView(view) view } else { - val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_send_item, container, false) + 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( diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java index cd56d3fd0a..475a9d654b 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java @@ -180,23 +180,18 @@ public class BIGChart extends WatchFace { } public void performViewSetup() { - final WatchViewStub stub = layoutView.findViewById(R.id.watch_view_stub); - - stub.setOnLayoutInflatedListener(stub1 -> { - mTime = stub1.findViewById(R.id.watch_time); - mSgv = stub1.findViewById(R.id.sgv); - mTimestamp = stub1.findViewById(R.id.timestamp); - mDelta = stub1.findViewById(R.id.delta); - mAvgDelta = stub1.findViewById(R.id.avgdelta); - mRelativeLayout = stub1.findViewById(R.id.main_layout); - chart = stub1.findViewById(R.id.chart); - statusView = stub1.findViewById(R.id.aps_status); - layoutSet = true; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - }); + mTime = layoutView.findViewById(R.id.watch_time); + mSgv = layoutView.findViewById(R.id.sgv); + mTimestamp = layoutView.findViewById(R.id.timestamp); + mDelta = layoutView.findViewById(R.id.delta); + mAvgDelta = layoutView.findViewById(R.id.avgdelta); + mRelativeLayout = layoutView.findViewById(R.id.main_layout); + chart = layoutView.findViewById(R.id.chart); + statusView = layoutView.findViewById(R.id.aps_status); + layoutSet = true; + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:performViewSetup"))); wakeLock.acquire(50); } @@ -251,6 +246,7 @@ public class BIGChart extends WatchFace { } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java index 7668b8ce40..d34dcfb31c 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java @@ -71,15 +71,9 @@ public abstract class BaseWatchFace extends WatchFace { CompositeDisposable disposable = new CompositeDisposable(); - protected EventData.SingleBg singleBg = new EventData.SingleBg(0, "---", "-", "--", "--", "--" - , 0, 0.0, 0.0, 0.0, 0); + protected EventData.SingleBg singleBg = new EventData.SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0); protected EventData.Status status = new EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1); - protected EventData.TreatmentData treatmentData = new EventData.TreatmentData( - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>(), - new ArrayList<>() - ); + protected EventData.TreatmentData treatmentData = new EventData.TreatmentData(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); protected EventData.GraphData graphData = new EventData.GraphData(new ArrayList<>()); static IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); @@ -174,15 +168,11 @@ public abstract class BaseWatchFace extends WatchFace { .subscribe(event -> { status = event; // this event is received as last batch of data - if (isSimpleUi()) { - if (needUpdate()) { - invalidate(); - } - } else { + if (!isSimpleUi() || !needUpdate()) { setupCharts(); setDataFields(); - invalidate(); } + invalidate(); }) ); @@ -260,50 +250,47 @@ public abstract class BaseWatchFace extends WatchFace { } public void performViewSetup() { - final WatchViewStub layoutStub = layoutView.findViewById(R.id.watch_view_stub); - - 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); + mTime = layoutView.findViewById(R.id.watch_time); + mHour = layoutView.findViewById(R.id.hour); + mMinute = layoutView.findViewById(R.id.minute); + mTimePeriod = layoutView.findViewById(R.id.timePeriod); + 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(); - }); + wakeLock.acquire(50); } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java index d80b3e43d5..b9affede77 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java @@ -100,7 +100,7 @@ public class CircleWatchface extends WatchFace { //register Message Receiver LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - myLayout = inflater.inflate(R.layout.modern_layout, null); + myLayout = inflater.inflate(R.layout.activity_circle, null); prepareLayout(); prepareDrawTime(); @@ -507,6 +507,7 @@ public class CircleWatchface extends WatchFace { addArch(canvas, (offset + .8f) * offsetMultiplier + 11, getBackgroundColor(), 360); } + @SuppressWarnings("deprecation") @Override protected void onTapCommand(int tapType, int x, int y, long eventTime) { if (mSgv == null) return; diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java index 9ac98fe0ce..5590b5ce70 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java @@ -38,6 +38,7 @@ public class Cockpit extends BaseWatchFace { } } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java index b44f3c95dd..a780b14ff8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java @@ -47,6 +47,7 @@ public class DigitalStyle extends BaseWatchFace { } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java index fb15053f51..6c5a2eb0e2 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java @@ -59,6 +59,7 @@ public class Home extends BaseWatchFace { sp.putString("chart_timeframe", "" + timeframe); } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle(){ return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java index 21a600ce5f..6ffec5d910 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java @@ -63,6 +63,7 @@ public class Home2 extends BaseWatchFace { sp.putString("chart_timeframe", "" + timeframe); } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java index 29774131ef..7ba6053ad4 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java @@ -43,6 +43,7 @@ public class LargeHome extends BaseWatchFace { } } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle(){ return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java index 4091e9a8db..9524b63772 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java @@ -148,24 +148,18 @@ public class NOChart extends WatchFace { } public void performViewSetup() { - final WatchViewStub stub = layoutView.findViewById(R.id.watch_view_stub); - - stub.setOnLayoutInflatedListener(stub1 -> { - mTime = stub1.findViewById(R.id.watch_time); - mSgv = stub1.findViewById(R.id.sgv); - mTimestamp = stub1.findViewById(R.id.timestamp); - mDelta = stub1.findViewById(R.id.delta); - mAvgDelta = stub1.findViewById(R.id.avgdelta); - mRelativeLayout = stub1.findViewById(R.id.main_layout); - statusView = stub1.findViewById(R.id.aps_status); - layoutSet = true; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - }); - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("NOChart" + - ":performViewSetup"))); + mTime = layoutView.findViewById(R.id.watch_time); + mSgv = layoutView.findViewById(R.id.sgv); + mTimestamp = layoutView.findViewById(R.id.timestamp); + mDelta = layoutView.findViewById(R.id.delta); + mAvgDelta = layoutView.findViewById(R.id.avgdelta); + mRelativeLayout = layoutView.findViewById(R.id.main_layout); + statusView = layoutView.findViewById(R.id.aps_status); + layoutSet = true; + showAgeAndStatus(); + mRelativeLayout.measure(specW, specH); + mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); + rxBus.send(new EventWearToMobile(new EventData.ActionResendData("NOChart:performViewSetup"))); wakeLock.acquire(50); } @@ -204,6 +198,7 @@ public class NOChart extends WatchFace { } + @SuppressWarnings("deprecation") @Override protected WatchFaceStyle getWatchFaceStyle() { return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); 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 13791efd06..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java +++ /dev/null @@ -1,279 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -import android.content.Intent; -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 androidx.core.content.ContextCompat; - -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; - - @SuppressLint("InflateParams") @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 && singleBg.getTimeStamp() != 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 (!singleBg.getSgvString().equals("---")) { - - float rotationAngle = 0f; //by default, show ? on the dial (? is at 0 degrees on the dial) - - if (!singleBg.getGlucoseUnits().equals("-")) { - - //ensure the glucose dial is the correct units - if (singleBg.getGlucoseUnits().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 (singleBg.getGlucoseUnits().equals("mmol")) { - rotationAngle = SafeParse.stringToFloat(singleBg.getSgvString()) * 18f; //convert to - // mg/dL, which is equivalent to degrees - } else { - rotationAngle = SafeParse.stringToFloat(singleBg.getSgvString()); //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 (!singleBg.getAvgDelta().equals("--")) { //if a legitimate delta value is - // received, - // then... - if (singleBg.getAvgDelta().charAt(0) == '-') - deltaIsNegative = -1f; //if the delta is negative, go counter-clockwise - Float AbssAvgDelta = SafeParse.stringToFloat(singleBg.getAvgDelta().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 (!singleBg.getGlucoseUnits().equals("-")) { - if (singleBg.getGlucoseUnits().equals("mmol")) { - if (sp.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 (sp.getString("delta_granularity", "2").equals("1") || autogranularity.equals("1")) { //low - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_10); - deltaRotationAngle = (AbssAvgDelta * 30f); - } - if (sp.getString("delta_granularity", "2").equals("2") || autogranularity.equals("2")) { //medium - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_05); - deltaRotationAngle = (AbssAvgDelta * 60f); - } - if (sp.getString("delta_granularity", "2").equals("3") || autogranularity.equals("3")) { //high - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_03); - deltaRotationAngle = (AbssAvgDelta * 100f); - } - } else { - if (sp.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 (sp.getString("delta_granularity", "2").equals("1") || autogranularity.equals("1")) { //low - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_20); - deltaRotationAngle = (AbssAvgDelta * 1.5f); - } - if (sp.getString("delta_granularity", "2").equals("2") || autogranularity.equals("2")) { //medium - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_10); - deltaRotationAngle = (AbssAvgDelta * 3f); - } - if (sp.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.parseFloat(sMinute) * 6f); - - //rotate the hour hand. - mHourHand.setRotation((Float.parseFloat(sHour) * 30f) + (Float.parseFloat(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 (sp.getInt("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 (status.getIobDetail().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 (sp.getBoolean("show_uploader_battery", true) && sp.getBoolean( - "show_rig_battery", false)) { - mUploaderBattery.setTextSize(fontSmall); - mRigBattery.setTextSize(fontSmall); - } else { - mUploaderBattery.setTextSize(fontMedium); - mRigBattery.setTextSize(fontMedium); - } - } - - private void changeChartTimeframe() { - int timeframe = sp.getInt("chart_timeframe", 3); - timeframe = (timeframe % 5) + 1; - if (timeframe < 3) { - pointSize = 2; - } else { - pointSize = 1; - } - setupCharts(); - sp.putString("chart_timeframe", "" + timeframe); - } -} 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..924032b773 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -0,0 +1,248 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +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 androidx.core.content.ContextCompat +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +import info.nightscout.shared.SafeParse.stringToFloat + +/** + * Created by andrew-warrington on 01/12/2017. + * Refactored by MilosKozak on 23/04/2022 + */ +class SteampunkWatchface : BaseWatchFace() { + + private var chartTapTime: Long = 0 + private var mainMenuTapTime: Long = 0 + private var lastEndDegrees = 0f + private var deltaRotationAngle = 0f + + @SuppressLint("InflateParams") + override fun onCreate() { + forceSquareCanvas = true + super.onCreate() + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + layoutView = inflater.inflate(R.layout.activity_steampunk, null) + performViewSetup() + } + + override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { + if (tapType == TAP_TYPE_TAP && x >= mChartTap.left && x <= mChartTap.right && y >= mChartTap.top && y <= mChartTap.bottom) { + if (eventTime - chartTapTime < 800) { + changeChartTimeframe() + } + chartTapTime = eventTime + } else 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 + } + } + + override fun getWatchFaceStyle(): WatchFaceStyle { + return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() + } + + override fun setColorDark() { + if (mLinearLayout2 != null) { + 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)) + } + } + if (loopLevel == 0) { + mLoop?.setTextColor(ContextCompat.getColor(this, R.color.red_600)) + } else { + mLoop?.setTextColor(ContextCompat.getColor(this, 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 + if (singleBg.glucoseUnits == "mmol") { + mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mmol) + } else { + mGlucoseDial.setImageResource(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 + ) + rotate.fillAfter = true + rotate.interpolator = LinearInterpolator() + rotate.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 = "1" // low (init) + if (absAvgDelta < 0.3) { + autoGranularity = "3" // high if below 0.3 mmol/l + } else if (absAvgDelta < 0.5) { + autoGranularity = "2" // medium if below 0.5 mmol/l + } + } + 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 = "1" // low (init) + if (absAvgDelta < 5) { + autoGranularity = "3" // high if below 5 mg/dl + } else if (absAvgDelta < 10) { + autoGranularity = "2" // medium if below 10 mg/dl + } + } + 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 = sMinute.toFloat() * 6f + + //rotate the hour hand. + mHourHand.rotation = sHour.toFloat() * 30f + sMinute.toFloat() * 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("chart_timeframe", 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) + 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 + } + } + + private fun changeChartTimeframe() { + var timeframe = sp.getInt("chart_timeframe", 3) + timeframe = timeframe % 5 + 1 + pointSize = if (timeframe < 3) { + 2 + } else { + 1 + } + setupCharts() + sp.putString("chart_timeframe", "" + 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 100% rename from wear/src/main/res/layout/rect_activity_bigchart.xml rename to wear/src/main/res/layout-notround/activity_bigchart.xml diff --git a/wear/src/main/res/layout/rect_activity_bigchart_small.xml b/wear/src/main/res/layout-notround/activity_bigchart_small.xml similarity index 100% rename from wear/src/main/res/layout/rect_activity_bigchart_small.xml rename to wear/src/main/res/layout-notround/activity_bigchart_small.xml diff --git a/wear/src/main/res/layout/rect_cockpit.xml b/wear/src/main/res/layout-notround/activity_cockpit.xml similarity index 100% rename from wear/src/main/res/layout/rect_cockpit.xml rename to wear/src/main/res/layout-notround/activity_cockpit.xml diff --git a/wear/src/main/res/layout/rect_activity_digitalstyle.xml b/wear/src/main/res/layout-notround/activity_digitalstyle.xml similarity index 100% rename from wear/src/main/res/layout/rect_activity_digitalstyle.xml rename to wear/src/main/res/layout-notround/activity_digitalstyle.xml diff --git a/wear/src/main/res/layout/rect_activity_home.xml b/wear/src/main/res/layout-notround/activity_home.xml similarity index 100% rename from wear/src/main/res/layout/rect_activity_home.xml rename to wear/src/main/res/layout-notround/activity_home.xml 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 100% rename from wear/src/main/res/layout/rect_activity_home_2.xml rename to wear/src/main/res/layout-notround/activity_home_2.xml diff --git a/wear/src/main/res/layout/rect_activity_home_large.xml b/wear/src/main/res/layout-notround/activity_home_large.xml similarity index 100% rename from wear/src/main/res/layout/rect_activity_home_large.xml rename to wear/src/main/res/layout-notround/activity_home_large.xml diff --git a/wear/src/main/res/layout/rect_activity_nochart.xml b/wear/src/main/res/layout-notround/activity_nochart.xml similarity index 100% rename from wear/src/main/res/layout/rect_activity_nochart.xml rename to wear/src/main/res/layout-notround/activity_nochart.xml diff --git a/wear/src/main/res/layout/rect_activity_nochart_small.xml b/wear/src/main/res/layout-notround/activity_nochart_small.xml similarity index 97% rename from wear/src/main/res/layout/rect_activity_nochart_small.xml rename to wear/src/main/res/layout-notround/activity_nochart_small.xml index 2a4eae4f7e..7d57161c31 100644 --- a/wear/src/main/res/layout/rect_activity_nochart_small.xml +++ b/wear/src/main/res/layout-notround/activity_nochart_small.xml @@ -1,116 +1,116 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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 From 76124ec11ece68e7207861793ae65bb6a579a40b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 15:46:32 +0200 Subject: [PATCH 19/54] lint --- .../nightscout/androidaps/comm/DataHandlerWear.kt | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt index d457732323..da9b9ef702 100644 --- a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt @@ -209,7 +209,10 @@ class DataHandlerWear @Inject constructor( 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) + 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}") @@ -265,15 +268,15 @@ class DataHandlerWear @Inject constructor( // Register the channel with the system; you can't change the importance // or other notification behaviors after this - val notificationManager = context.getSystemService(NotificationManager::class.java) - notificationManager.createNotificationChannel(channel) + context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel) } + @Suppress("DEPRECATION") var builder = NotificationCompat.Builder(context, DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_OPEN_LOOP) - builder = builder.setSmallIcon(R.drawable.notif_icon) + .setSmallIcon(R.drawable.notif_icon) .setContentTitle(command.title) .setContentText(command.message) - .setPriority(Notification.PRIORITY_HIGH) .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 { From 22d7dda7579cc4c808f184186b0a53880146add8 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 16:20:50 +0200 Subject: [PATCH 20/54] Log -> AAPSLogger --- .../profile/local/LocalProfileFragment.kt | 4 ++-- .../androidaps/utils/wizard/QuickWizard.kt | 3 +-- .../pump/common/utils/DateTimeUtilUTest.java | 4 +--- .../ComplicationTapBroadcastReceiver.java | 8 ++++---- .../androidaps/interaction/utils/Inevitable.java | 16 ++++++++-------- .../androidaps/watchfaces/DigitalStyle.java | 12 ++++++------ 6 files changed, 22 insertions(+), 25 deletions(-) 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..c1c0959d68 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 @@ -38,6 +37,7 @@ 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/utils/wizard/QuickWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizard.kt index 450ce43d46..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 @@ -72,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/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/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java index 158ad0f3e1..96b0b36412 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java @@ -6,7 +6,6 @@ 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; @@ -23,6 +22,8 @@ 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; /* @@ -33,8 +34,7 @@ public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver { @Inject WearUtil wearUtil; @Inject DisplayFormat displayFormat; @Inject SP sp; - - private static final String TAG = ComplicationTapBroadcastReceiver.class.getSimpleName(); + @Inject AAPSLogger aapsLogger; private static final String EXTRA_PROVIDER_COMPONENT = "info.nightscout.androidaps.complications.action.PROVIDER_COMPONENT"; @@ -58,7 +58,7 @@ public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver { action = ComplicationAction.valueOf(ComplicationAction.class, complicationAction); } catch (IllegalArgumentException | NullPointerException ex) { // but how? - Log.e(TAG, "Cannot interpret complication action: " + complicationAction); + aapsLogger.error(LTag.WEAR, "Cannot interpret complication action: " + complicationAction); } action = remapActionWithUserPreferences(action); 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 index 5e97469c0c..b0d40d6b64 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.interaction.utils; import android.os.PowerManager; -import android.util.Log; import java.util.concurrent.ConcurrentHashMap; @@ -9,6 +8,8 @@ import javax.inject.Inject; import javax.inject.Singleton; import info.nightscout.androidaps.BuildConfig; +import info.nightscout.shared.logging.AAPSLogger; +import info.nightscout.shared.logging.LTag; /** * Created for xDrip by jamorham on 07/03/2018 @@ -23,10 +24,10 @@ import info.nightscout.androidaps.BuildConfig; public class Inevitable { @Inject WearUtil wearUtil; + @Inject AAPSLogger aapsLogger; @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; @@ -42,15 +43,14 @@ public class Inevitable { task.extendTime(idle_for); if (debug) - Log.d(TAG, "Extending time for: " + id + " to " + wearUtil.dateTimeText(task.when)); + aapsLogger.debug(LTag.WEAR, "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)); + aapsLogger.debug(LTag.WEAR, "Creating task: " + id + " due: " + wearUtil.dateTimeText(tasks.get(id).when)); } // create a thread to wait and execute in background @@ -79,7 +79,7 @@ public class Inevitable { stack++; } if (stack > 0) { - Log.d(TAG, "Task stacked to: " + id); + aapsLogger.debug(LTag.WEAR, "Task stacked to: " + id); } task(id, idle_for, runnable); } @@ -110,12 +110,12 @@ public class Inevitable { public boolean poll() { final long till = wearUtil.msTill(when); if (till < 1) { - if (debug) Log.d(TAG, "Executing task! " + this.id); + if (debug) aapsLogger.debug(LTag.WEAR, "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); + aapsLogger.debug(LTag.WEAR, "Task: " + this.id + " In queue too long: " + till); tasks.remove(this.id); return true; } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java index a780b14ff8..d9eb309742 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java @@ -4,7 +4,6 @@ import android.annotation.SuppressLint; 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; @@ -17,6 +16,7 @@ import java.util.Date; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; +import info.nightscout.shared.logging.LTag; public class DigitalStyle extends BaseWatchFace { private static final long TIME_TAP_THRESHOLD = 800; @@ -34,7 +34,7 @@ public class DigitalStyle extends BaseWatchFace { @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); + aapsLogger.debug(LTag.WEAR,"onTapCommand: DeviceWidth x DeviceHeight /// x , y, TapType >> ", getWidth() + " x " + getHeight() + " /// " + x + " , " + y + " , " + tapType); if (tapType == TAP_TYPE_TAP) { if (eventTime - sgvTapTime < TIME_TAP_THRESHOLD) { @@ -111,7 +111,7 @@ public class DigitalStyle extends BaseWatchFace { try { mShapesElements.setBackground(getResources().getDrawable(getResources().getIdentifier(styleDrawableName, "drawable", getApplicationContext().getPackageName()))); } catch (Exception e) { - Log.e("digitalstyle_frameStyle", "RESOURCE NOT FOUND >> " + styleDrawableName); + aapsLogger.error("digitalstyle_frameStyle", "RESOURCE NOT FOUND >> " + styleDrawableName); } // set background-tint-color @@ -119,13 +119,13 @@ public class DigitalStyle extends BaseWatchFace { mShapesElements.setBackgroundTintList(null); } else { String strColorName =(( displayFrameColor.equals("white") || displayFrameColor.equals("black") )?displayFrameColor:displayFrameColor+"_"+displayFrameColorSaturation); - Log.v("digitalstyle_strColorName",strColorName); + aapsLogger.debug(LTag.WEAR,"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); + aapsLogger.error("digitalstyle_colorName", "COLOR NOT FOUND >> " + strColorName); } } @@ -151,7 +151,7 @@ public class DigitalStyle extends BaseWatchFace { /* display week number */ Boolean isShowWeekNumber = sp.getBoolean("show_weeknumber", false); - Log.i("---------------------------------","weeknumber refresh "); + aapsLogger.info(LTag.WEAR,"---------------------------------","weeknumber refresh "); TextView mWeekNumber= layoutView.findViewById(R.id.weeknumber); if (isShowWeekNumber) { mWeekNumber.setVisibility(View.VISIBLE); From 8e7030815078d6ffc7619f7588f920ab175bb54a Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 23 Apr 2022 18:34:04 +0200 Subject: [PATCH 21/54] BgGraphBuilder -> kt --- .../activities/MyPreferenceFragment.kt | 2 +- .../fragments/TreatmentsBolusCarbsFragment.kt | 2 +- .../fragments/TreatmentsCareportalFragment.kt | 2 +- .../TreatmentsExtendedBolusesFragment.kt | 2 +- .../TreatmentsProfileSwitchFragment.kt | 2 +- .../fragments/TreatmentsTempTargetFragment.kt | 2 +- .../TreatmentsTemporaryBasalsFragment.kt | 2 +- .../fragments/TreatmentsUserEntryFragment.kt | 2 +- .../nightscout/androidaps/di/AppModule.kt | 2 +- .../androidaps/dialogs/CalibrationDialog.kt | 2 +- .../androidaps/dialogs/CarbsDialog.kt | 2 +- .../androidaps/dialogs/CareDialog.kt | 2 +- .../androidaps/dialogs/ExtendedBolusDialog.kt | 2 +- .../androidaps/dialogs/FillDialog.kt | 2 +- .../androidaps/dialogs/InsulinDialog.kt | 2 +- .../androidaps/dialogs/LoopDialog.kt | 2 +- .../androidaps/dialogs/ProfileSwitchDialog.kt | 2 +- .../androidaps/dialogs/TempBasalDialog.kt | 2 +- .../androidaps/dialogs/TempTargetDialog.kt | 2 +- .../androidaps/dialogs/TreatmentDialog.kt | 2 +- .../androidaps/dialogs/WizardDialog.kt | 2 +- .../androidaps/dialogs/WizardInfoDialog.kt | 2 +- .../plugins/aps/loop/LoopFragment.kt | 2 +- .../androidaps/plugins/aps/loop/LoopPlugin.kt | 2 +- .../aps/openAPSAMA/OpenAPSAMAFragment.kt | 2 +- .../aps/openAPSAMA/OpenAPSAMAPlugin.kt | 2 +- .../openAPSSMB/DetermineBasalAdapterSMBJS.kt | 2 +- .../aps/openAPSSMB/OpenAPSSMBFragment.kt | 2 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.kt | 2 +- .../DetermineBasalAdapterSMBDynamicISFJS.kt | 2 +- .../OpenAPSSMBDynamicISFPlugin.kt | 2 +- .../configBuilder/ConfigBuilderFragment.kt | 2 +- .../configBuilder/ConfigBuilderPlugin.kt | 2 +- .../ProfileFunctionImplementation.kt | 2 +- .../bgQualityCheck/BgQualityCheckPlugin.kt | 2 +- .../constraints/dstHelper/DstHelperPlugin.kt | 2 +- .../objectives/ObjectivesFragment.kt | 2 +- .../objectives/ObjectivesPlugin.kt | 2 +- .../activities/ObjectivesExamDialog.kt | 2 +- .../objectives/objectives/Objective.kt | 2 +- .../phoneChecker/PhoneCheckerPlugin.kt | 2 +- .../constraints/safety/SafetyPlugin.kt | 2 +- .../SignatureVerifierPlugin.kt | 2 +- .../storage/StorageConstraintPlugin.kt | 2 +- .../versionChecker/VersionCheckerPlugin.kt | 2 +- .../general/actions/ActionsFragment.kt | 2 +- .../plugins/general/actions/ActionsPlugin.kt | 2 +- .../dataBroadcaster/DataBroadcastPlugin.kt | 2 +- .../plugins/general/food/FoodFragment.kt | 2 +- .../plugins/general/food/FoodPlugin.kt | 2 +- .../maintenance/ImportExportPrefsImpl.kt | 2 +- .../maintenance/MaintenanceFragment.kt | 2 +- .../general/maintenance/MaintenancePlugin.kt | 2 +- .../general/nsclient/NSClientFragment.kt | 2 +- .../general/nsclient/NSClientPlugin.kt | 2 +- .../nsclient/NsClientReceiverDelegate.kt | 2 +- .../general/nsclient/data/NSDeviceStatus.kt | 2 +- .../general/nsclient/data/NSSettingsStatus.kt | 2 +- .../nsclient/events/EventNSClientStatus.kt | 2 +- .../nsclient/services/NSClientService.kt | 2 +- .../plugins/general/overview/OverviewData.kt | 2 +- .../general/overview/OverviewFragment.kt | 2 +- .../plugins/general/overview/OverviewMenus.kt | 2 +- .../general/overview/OverviewPlugin.kt | 2 +- .../general/overview/StatusLightHandler.kt | 2 +- .../general/overview/graphData/GraphData.kt | 2 +- .../graphExtensions/BolusDataPoint.kt | 2 +- .../graphExtensions/CarbsDataPoint.kt | 2 +- .../EffectiveProfileSwitchDataPoint.kt | 2 +- .../graphExtensions/ExtendedBolusDataPoint.kt | 2 +- .../graphExtensions/GlucoseValueDataPoint.kt | 2 +- .../InMemoryGlucoseValueDataPoint.kt | 2 +- .../graphExtensions/TherapyEventDataPoint.kt | 2 +- .../notifications/NotificationStore.kt | 2 +- .../notifications/NotificationWithAction.kt | 2 +- .../PersistentNotificationPlugin.kt | 2 +- .../general/smsCommunicator/AuthRequest.kt | 2 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 2 +- .../smsCommunicator/otp/OneTimePassword.kt | 2 +- .../general/themes/ThemeSwitcherPlugin.kt | 2 +- .../general/tidepool/TidepoolPlugin.kt | 2 +- .../general/tidepool/comm/TidepoolUploader.kt | 2 +- .../plugins/general/wear/WearPlugin.kt | 2 +- .../wear/wearintegration/DataHandlerMobile.kt | 2 +- .../DataLayerListenerServiceMobile.kt | 2 +- .../xdripStatusline/StatusLinePlugin.kt | 2 +- .../plugins/insulin/InsulinFragment.kt | 2 +- .../plugins/insulin/InsulinLyumjevPlugin.kt | 2 +- .../plugins/insulin/InsulinOrefBasePlugin.kt | 2 +- .../insulin/InsulinOrefFreePeakPlugin.kt | 2 +- .../insulin/InsulinOrefRapidActingPlugin.kt | 2 +- .../InsulinOrefUltraRapidActingPlugin.kt | 2 +- .../IobCobCalculatorPlugin.kt | 2 +- .../iob/iobCobCalculator/IobCobOref1Worker.kt | 2 +- .../iob/iobCobCalculator/IobCobOrefWorker.kt | 2 +- .../profile/local/LocalProfileFragment.kt | 2 +- .../profile/local/LocalProfilePlugin.kt | 2 +- .../androidaps/plugins/pump/mdi/MDIPlugin.kt | 2 +- .../pump/virtual/VirtualPumpFragment.kt | 2 +- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 2 +- .../sensitivity/AbstractSensitivityPlugin.kt | 2 +- .../sensitivity/SensitivityAAPSPlugin.kt | 2 +- .../sensitivity/SensitivityOref1Plugin.kt | 2 +- .../SensitivityWeightedAveragePlugin.kt | 2 +- .../androidaps/plugins/source/AidexPlugin.kt | 2 +- .../plugins/source/BGSourceFragment.kt | 2 +- .../androidaps/plugins/source/DexcomPlugin.kt | 2 +- .../plugins/source/EversensePlugin.kt | 2 +- .../androidaps/plugins/source/GlimpPlugin.kt | 2 +- .../plugins/source/GlunovoPlugin.kt | 2 +- .../androidaps/plugins/source/MM640gPlugin.kt | 2 +- .../plugins/source/NSClientSourcePlugin.kt | 2 +- .../plugins/source/PoctechPlugin.kt | 2 +- .../plugins/source/RandomBgPlugin.kt | 2 +- .../androidaps/plugins/source/TomatoPlugin.kt | 2 +- .../androidaps/plugins/source/XdripPlugin.kt | 2 +- .../queue/CommandQueueImplementation.kt | 2 +- .../androidaps/queue/QueueThread.kt | 2 +- .../androidaps/receivers/KeepAliveWorker.kt | 2 +- .../androidaps/setupwizard/SWDefinition.kt | 2 +- .../androidaps/setupwizard/SWScreen.kt | 2 +- .../androidaps/setupwizard/elements/SWItem.kt | 2 +- .../androidaps/utils/ActivityMonitor.kt | 2 +- .../androidaps/utils/AndroidPermission.kt | 2 +- .../nightscout/androidaps/utils/BolusTimer.kt | 2 +- .../nightscout/androidaps/utils/CarbTimer.kt | 2 +- .../androidaps/utils/LocalAlertUtils.kt | 2 +- .../androidaps/utils/TrendCalculator.kt | 2 +- .../androidaps/utils/XDripBroadcast.kt | 2 +- .../NotificationHolderImpl.kt | 2 +- .../nightscout/androidaps/utils/stats/TIR.kt | 2 +- .../androidaps/utils/stats/TddCalculator.kt | 2 +- .../androidaps/utils/stats/TirCalculator.kt | 2 +- .../androidaps/utils/wizard/BolusWizard.kt | 2 +- .../nightscout/androidaps/widget/Widget.kt | 2 +- .../workflow/CalculationWorkflow.kt | 2 +- .../workflow/PrepareBasalDataWorker.kt | 2 +- .../workflow/PrepareBgDataWorker.kt | 2 +- .../workflow/PrepareBucketedDataWorker.kt | 2 +- .../PrepareIobAutosensGraphDataWorker.kt | 2 +- .../workflow/PreparePredictionsWorker.kt | 2 +- .../PrepareTemporaryTargetDataWorker.kt | 2 +- .../workflow/PrepareTreatmentsDataWorker.kt | 2 +- .../androidaps/TestBaseWithProfile.kt | 2 +- .../plugins/aps/loop/LoopPluginTest.kt | 2 +- .../configBuilder/ConfigBuilderPluginTest.kt | 2 +- .../BgQualityCheckPluginTest.kt | 2 +- .../dstHelper/DstHelperPluginTest.kt | 2 +- .../objectives/ObjectivesPluginTest.kt | 2 +- .../SignatureVerifierPluginTest.kt | 2 +- .../storage/StorageConstraintPluginTest.kt | 2 +- .../maintenance/MaintenancePluginTest.kt | 2 +- .../nsclient/NsClientReceiverDelegateTest.kt | 2 +- .../smsCommunicator/AuthRequestTest.kt | 2 +- .../insulin/InsulinLyumjevPluginTest.kt | 2 +- .../insulin/InsulinOrefBasePluginTest.kt | 2 +- .../insulin/InsulinOrefFreePeakPluginTest.kt | 2 +- .../InsulinOrefRapidActingPluginTest.kt | 2 +- .../InsulinOrefUltraRapidActingPluginTest.kt | 2 +- .../pump/virtual/VirtualPumpPluginUTest.kt | 2 +- .../AbstractSensitivityPluginTest.kt | 2 +- .../plugins/source/GlimpPluginTest.kt | 2 +- .../plugins/source/MM640GPluginTest.kt | 2 +- .../plugins/source/NSClientPluginTest.kt | 2 +- .../plugins/source/XdripPluginTest.kt | 2 +- .../queue/CommandQueueImplementationTest.kt | 2 +- .../utils/wizard/BolusWizardTest.kt | 2 +- .../general/automation/AutomationFragment.kt | 2 +- .../general/automation/AutomationPlugin.kt | 2 +- .../general/automation/actions/Action.kt | 2 +- .../dialogs/ChooseOperationDialog.kt | 2 +- .../general/automation/elements/Comparator.kt | 2 +- .../automation/elements/ComparatorConnect.kt | 2 +- .../automation/elements/ComparatorExists.kt | 2 +- .../elements/InputCarePortalMenu.kt | 2 +- .../automation/elements/InputDateTime.kt | 2 +- .../general/automation/elements/InputDelta.kt | 2 +- .../automation/elements/InputDropdownMenu.kt | 2 +- .../automation/elements/InputLocationMode.kt | 2 +- .../automation/elements/InputProfileName.kt | 2 +- .../general/automation/elements/InputTime.kt | 2 +- .../automation/elements/InputTimeRange.kt | 2 +- .../automation/elements/LabelWithElement.kt | 2 +- .../automation/elements/StaticLabel.kt | 2 +- .../general/automation/triggers/Trigger.kt | 2 +- .../automation/triggers/TriggerConnector.kt | 2 +- .../general/automation/AutomationEventTest.kt | 2 +- .../general/automation/TestBaseWithProfile.kt | 2 +- .../general/automation/TestPumpPlugin.kt | 2 +- .../automation/actions/ActionAlarmTest.kt | 2 +- .../actions/ActionNotificationTest.kt | 2 +- .../automation/actions/ActionsTestBase.kt | 2 +- .../plugins/pump/combo/ComboFragment.kt | 2 +- .../plugins/pump/combo/ComboPlugin.java | 2 +- .../plugins/pump/combo/ComboPluginTest.kt | 2 +- .../DaggerAppCompatActivityWithResult.kt | 2 +- .../androidaps/data/ProfileSealed.kt | 2 +- .../androidaps/data/PumpEnactResult.kt | 2 +- .../nightscout/androidaps/di/CoreModule.kt | 2 +- .../androidaps/dialogs/BolusProgressDialog.kt | 2 +- .../androidaps/dialogs/NtpProgressDialog.kt | 2 +- .../androidaps/dialogs/ProfileViewerDialog.kt | 2 +- .../events/EventPreferenceChange.kt | 2 +- .../events/EventPumpStatusChanged.kt | 2 +- .../androidaps/events/EventStatus.kt | 2 +- .../androidaps/extensions/HtmlString.kt | 2 +- .../androidaps/extensions/JSONObjectExt.kt | 2 +- .../extensions/TemporaryTargetExtension.kt | 2 +- .../extensions/TherapyEventExtension.kt | 2 +- .../extensions/TotalDailyDoseExtension.kt | 2 +- .../androidaps/interfaces/PluginBase.kt | 2 +- .../androidaps/interfaces/Profile.kt | 2 +- .../androidaps/interfaces/PumpPluginBase.kt | 2 +- .../androidaps/plugins/aps/loop/APSResult.kt | 2 +- .../configBuilder/RunningConfiguration.kt | 2 +- .../versionChecker/VersionCheckerUtils.kt | 2 +- .../maintenance/PrefFileListProvider.kt | 2 +- .../activities/PrefImportListActivity.kt | 2 +- .../formats/EncryptedPrefsFormat.kt | 2 +- .../plugins/iob/iobCobCalculator/CobInfo.kt | 2 +- .../iob/iobCobCalculator/data/AutosensData.kt | 2 +- .../plugins/pump/PumpSyncImplementation.kt | 2 +- .../plugins/pump/common/ble/BlePreCheck.kt | 2 +- .../plugins/pump/common/defs/PumpType.kt | 2 +- .../androidaps/queue/commands/Command.kt | 2 +- .../androidaps/services/AlarmSoundService.kt | 2 +- .../androidaps/utils/ActionModeHelper.kt | 2 +- .../androidaps/utils/DecimalFormatter.kt | 2 +- .../nightscout/androidaps/utils/HardLimits.kt | 2 +- .../nightscout/androidaps/utils/TimerUtil.kt | 2 +- .../nightscout/androidaps/utils/Translator.kt | 2 +- .../nightscout/androidaps/utils/WarnColors.kt | 2 +- .../resources/ResourceHelperImplementation.kt | 1 + .../userEntry/UserEntryPresentationHelper.kt | 2 +- core/src/main/res/values/strings.xml | 28 - .../androidaps/TestBaseWithProfile.kt | 2 +- .../nightscout/androidaps/data/ProfileTest.kt | 2 +- .../VersionCheckerUtilsKtTest.kt | 2 +- .../formats/EncryptedPrefsFormatTest.kt | 2 +- .../androidaps/utils/DateUtilTest.kt | 2 +- .../androidaps/dana/DanaFragment.kt | 2 +- .../androidaps/TestBaseWithProfile.kt | 2 +- .../danaRKorean/DanaRKoreanPlugin.kt | 2 +- .../services/DanaRKoreanExecutionService.java | 2 +- .../androidaps/danaRv2/DanaRv2Plugin.java | 2 +- .../services/DanaRv2ExecutionService.java | 2 +- .../androidaps/danar/AbstractDanaRPlugin.java | 2 +- .../androidaps/danar/DanaRPlugin.java | 2 +- .../androidaps/danar/comm/MessageBase.kt | 2 +- .../AbstractDanaRExecutionService.java | 2 +- .../danar/services/DanaRExecutionService.java | 2 +- .../androidaps/TestBaseWithProfile.kt | 2 +- .../plugins/pump/danaR/comm/DanaRTestBase.kt | 2 +- .../androidaps/danars/DanaRSPlugin.kt | 2 +- .../comm/DanaRSPacketAPSHistoryEvents.kt | 2 +- .../comm/DanaRSPacketBasalGetBasalRate.kt | 2 +- .../comm/DanaRSPacketBolusGetBolusOption.kt | 2 +- .../comm/DanaRSPacketBolusSetStepBolusStop.kt | 2 +- .../comm/DanaRSPacketGeneralGetPumpCheck.kt | 2 +- .../danars/comm/DanaRSPacketNotifyAlarm.kt | 2 +- .../DanaRSPacketNotifyDeliveryComplete.kt | 2 +- .../DanaRSPacketNotifyDeliveryRateDisplay.kt | 2 +- .../danars/dialogs/PairingProgressDialog.java | 2 +- .../androidaps/danars/services/BLEComm.kt | 2 +- .../danars/services/DanaRSService.kt | 2 +- .../androidaps/TestBaseWithProfile.kt | 2 +- .../androidaps/diaconn/DiaconnG8Fragment.kt | 2 +- .../androidaps/diaconn/DiaconnG8Plugin.kt | 2 +- .../packet/BasalLimitInquireResponsePacket.kt | 2 +- .../BigAPSMainInfoInquireResponsePacket.kt | 2 +- .../packet/BigLogInquireResponsePacket.kt | 2 +- .../BigMainInfoInquireResponsePacket.kt | 2 +- .../IncarnationInquireResponsePacket.kt | 2 +- ...njectionExtendedBolusResultReportPacket.kt | 2 +- .../InjectionSnackResultReportPacket.kt | 2 +- .../diaconn/service/BLECommonService.kt | 2 +- .../diaconn/service/DiaconnG8Service.kt | 2 +- .../pump/insight/InsightAlertService.java | 2 +- .../pump/insight/LocalInsightFragment.java | 2 +- .../pump/insight/LocalInsightPlugin.java | 2 +- .../plugins/pump/insight/utils/AlertUtils.kt | 2 +- .../pump/medtronic/MedtronicFragment.kt | 2 +- .../pump/medtronic/MedtronicPumpPlugin.kt | 2 +- .../comm/ui/MedtronicUIPostprocessor.kt | 2 +- .../medtronic/data/MedtronicHistoryData.kt | 2 +- .../data/dto/RLHistoryItemMedtronic.kt | 2 +- .../dialog/MedtronicHistoryActivity.kt | 2 +- .../medtronic/driver/MedtronicPumpStatus.kt | 2 +- .../pump/medtronic/util/MedtronicUtil.kt | 2 +- .../pump/MedtronicPumpHistoryDecoderUTest.kt | 2 +- .../data/MedtronicHistoryDataUTest.kt | 2 +- .../common/fragment/WizardFragmentBase.kt | 2 +- .../omnipod/dash/OmnipodDashPumpPlugin.kt | 2 +- .../dash/ui/OmnipodDashOverviewFragment.kt | 2 +- .../action/DashInitializePodViewModel.kt | 2 +- .../action/DashInsertCannulaViewModel.kt | 2 +- .../plugins/pump/omnipod/dash/util/I8n.kt | 2 +- .../omnipod/eros/OmnipodErosPumpPlugin.java | 2 +- .../eros/data/RLHistoryItemOmnipod.java | 2 +- .../eros/manager/AapsOmnipodErosManager.java | 2 +- .../eros/ui/ErosPodHistoryActivity.java | 2 +- .../eros/ui/OmnipodErosOverviewFragment.kt | 2 +- .../omnipod/eros/util/AapsOmnipodUtil.java | 2 +- .../omnipod/eros/OmnipodErosPumpPluginTest.kt | 2 +- .../general/openhumans/OpenHumansUploader.kt | 2 +- .../plugins/pump/common/PumpPluginAbstract.kt | 2 +- .../pump/common/defs/PumpHistoryEntryGroup.kt | 2 +- .../dialog/RileyLinkBLEConfigActivity.kt | 2 +- .../EventRileyLinkDeviceStatusChange.kt | 2 +- .../pump/common/hw/rileylink/ble/RFSpy.java | 2 +- .../ble/defs/RileyLinkEncodingType.java | 2 +- .../hw/rileylink/data/RLHistoryItem.java | 2 +- .../dialog/RileyLinkStatusGeneralFragment.kt | 2 +- .../dialog/RileyLinkStatusHistoryFragment.kt | 2 +- .../hw/rileylink/service/RileyLinkService.kt | 2 +- shared/build.gradle | 1 + .../androidaps/interfaces}/ResourceHelper.kt | 2 +- .../nightscout/androidaps/utils/DateUtil.kt | 12 +- .../info/nightscout/androidaps/utils/T.kt | 0 shared/src/main/res/values/strings.xml | 30 ++ .../androidaps/watchfaces/BIGChart.java | 115 ++-- .../androidaps/watchfaces/BaseWatchFace.java | 18 +- .../androidaps/watchfaces/BgGraphBuilder.java | 498 ------------------ .../androidaps/watchfaces/BgGraphBuilder.kt | 367 +++++++++++++ .../androidaps/watchfaces/DigitalStyle.java | 36 +- .../androidaps/watchfaces/Home.java | 102 ++-- .../androidaps/watchfaces/Home2.java | 130 ++--- .../androidaps/watchfaces/LargeHome.java | 74 +-- .../androidaps/watchfaces/NOChart.java | 70 +-- wear/src/main/res/values/strings.xml | 1 + wear/src/main/res/xml/preferences.xml | 2 +- 331 files changed, 1001 insertions(+), 1112 deletions(-) rename {core/src/main/java/info/nightscout/androidaps/utils/resources => shared/src/main/java/info/nightscout/androidaps/interfaces}/ResourceHelper.kt (96%) rename {core => shared}/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt (97%) rename {core => shared}/src/main/java/info/nightscout/androidaps/utils/T.kt (100%) create mode 100644 shared/src/main/res/values/strings.xml delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index f4a679a9b0..19fdfea986 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -47,7 +47,7 @@ import info.nightscout.androidaps.plugins.source.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog.show import info.nightscout.androidaps.utils.protection.PasswordCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.ProtectionType.* -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.SafeParse import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject 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/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/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index 1a1ec6fae5..6f5e153387 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 @@ -16,7 +16,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.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable 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 0cb9545d61..94e90b2ad6 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 @@ -52,7 +52,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.logging.AAPSLogger import info.nightscout.shared.logging.LTag 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 8ec075f1a9..b0b3f44dd2 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 @@ -16,7 +16,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 io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign 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 8289e60f7c..8069079133 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 @@ -16,7 +16,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 a91cf4fe54..abff829785 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 a2e5cf0925..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 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 3cba103783..174537f38d 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 @@ -30,7 +30,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR 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 397f71248a..0c93f181ad 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 @@ -38,7 +38,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 44eb3d120a..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 @@ -68,7 +68,7 @@ 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 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 b055d92501..c47b633a8e 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.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus 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 javax.inject.Inject import javax.inject.Singleton 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/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index 3ac1f5adbb..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 @@ -17,7 +17,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB 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 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 index 16db4f7241..045e147e2b 100644 --- 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 @@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.receivers.ReceiverStatusStore 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.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizard 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 index b8305a981b..3bc626cd22 100644 --- 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 @@ -19,7 +19,7 @@ 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.utils.resources.ResourceHelper +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 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 a0d3652240..341ea29e8e 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 8968308243..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,7 +26,7 @@ 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 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 c1c0959d68..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 @@ -32,7 +32,7 @@ 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 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 809ae5472f..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 @@ -9,7 +9,7 @@ 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 -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.json.JSONException 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 03bc0655e4..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 @@ -23,7 +23,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy 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 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 d4cb82ce83..c9cb40eb7a 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 @@ -18,7 +18,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 import kotlin.math.log 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 4f9b16efcc..caf4bc9f49 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt @@ -36,7 +36,7 @@ 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 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 581e201deb..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 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/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 e8c554d30c..be0eb00790 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt @@ -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 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 420f062103..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 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..30edd95129 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() { 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/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 0cb2fde701..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; 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/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..7746345d70 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 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/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..c3141fc71a 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 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 ddf0aeb680..d5c31c6043 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 9e5ee7c4e2..2b341f120c 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/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 39ff22b27b..0038c50eab 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -201,34 +201,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..e32fa39a4e 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 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/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/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 33007e943f..33f410fd45 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/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 5ca09ea8e7..ef91fd3dc8 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 @@ -18,7 +18,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.sharedPreferences.SP import org.apache.commons.lang3.time.DateUtils import org.joda.time.DateTime 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 d278b76b48..cf4871b025 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 @@ -38,7 +38,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 db68af0a20..2dd50e1dc4 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 764adc301d..8e5b960778 100644 --- a/shared/build.gradle +++ b/shared/build.gradle @@ -18,6 +18,7 @@ android { dependencies { api "androidx.preference:preference-ktx:$preferencektx_version" + api 'net.danlew:android.joda:2.10.6' // for old fashioned support-app version (wear) api "com.google.dagger:dagger:$dagger_version" 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/utils/DateUtil.kt b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt similarity index 97% 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..e05ba8ecb6 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt +++ b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt @@ -3,8 +3,8 @@ package info.nightscout.androidaps.utils import android.content.Context 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 @@ -140,6 +140,14 @@ class DateUtil @Inject constructor(private val context: Context) { return DateTime(mills).toString(DateTimeFormat.forPattern(format)) } + 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 timeStringWithSeconds(mills: Long): String { var format = "hh:mm:ssa" if (android.text.format.DateFormat.is24HourFormat(context)) { 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/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/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java index 475a9d654b..e25270cf3e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java @@ -9,7 +9,6 @@ import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.os.PowerManager; -import android.support.wearable.view.WatchViewStub; import android.support.wearable.watchface.WatchFaceStyle; import android.text.format.DateFormat; import android.util.DisplayMetrics; @@ -37,6 +36,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventWearToMobile; import info.nightscout.androidaps.interaction.menus.MainMenuActivity; 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; @@ -55,6 +55,7 @@ public class BIGChart extends WatchFace { @Inject AapsSchedulers aapsSchedulers; @Inject AAPSLogger aapsLogger; @Inject SP sp; + @Inject DateUtil dateUtil; CompositeDisposable disposable = new CompositeDisposable(); @@ -350,20 +351,20 @@ public class BIGChart extends WatchFace { } 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); + statusView.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(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); + highColor = ContextCompat.getColor(this, R.color.dark_midColor); + lowColor = ContextCompat.getColor(this, R.color.dark_midColor); + midColor = ContextCompat.getColor(this, R.color.dark_midColor); + gridColour = 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(); } @@ -372,36 +373,36 @@ public class BIGChart extends WatchFace { protected void setColorDark() { if (singleBg != null) { - 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); + statusView.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == -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)); + 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(getApplicationContext(), R.color.dark_Timestamp)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); + mTimestamp.setTextColor(ContextCompat.getColor(this, 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); + highColor = ContextCompat.getColor(this, R.color.dark_highColor); + lowColor = ContextCompat.getColor(this, R.color.dark_lowColor); + midColor = ContextCompat.getColor(this, R.color.dark_midColor); + gridColour = 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(); } @@ -412,36 +413,36 @@ public class BIGChart extends WatchFace { 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)); + statusView.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == -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)); + 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(getApplicationContext(), R.color.light_mTimestamp1)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp1)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp)); + mTimestamp.setTextColor(ContextCompat.getColor(this, 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); + highColor = ContextCompat.getColor(this, R.color.light_highColor); + lowColor = ContextCompat.getColor(this, R.color.light_lowColor); + midColor = ContextCompat.getColor(this, R.color.light_midColor); + gridColour = 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(); } @@ -473,9 +474,11 @@ public class BIGChart extends WatchFace { if (bgDataList.size() > 0) { int timeframe = sp.getInt("chart_timeframe", 3); if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); + bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, bgDataList, + treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); } else { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); + bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, bgDataList, + treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); } chart.setLineChartData(bgGraphBuilder.lineData()); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java index d34dcfb31c..b28d48826e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java @@ -46,6 +46,7 @@ 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.DateUtil; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.logging.AAPSLogger; import info.nightscout.shared.logging.LTag; @@ -68,6 +69,7 @@ public abstract class BaseWatchFace extends WatchFace { @Inject RxBus rxBus; @Inject AapsSchedulers aapsSchedulers; @Inject SP sp; + @Inject DateUtil dateUtil; CompositeDisposable disposable = new CompositeDisposable(); @@ -121,9 +123,9 @@ public abstract class BaseWatchFace extends WatchFace { 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); + colorDarkHigh = ContextCompat.getColor(this, R.color.dark_highColor); + colorDarkMid = ContextCompat.getColor(this, R.color.dark_midColor); + colorDarkLow = ContextCompat.getColor(this, R.color.dark_lowColor); Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); display.getSize(displaySize); @@ -214,13 +216,13 @@ public abstract class BaseWatchFace extends WatchFace { private void setupSimpleUi() { mDateTime = new Date(); - int black = ContextCompat.getColor(getApplicationContext(), R.color.black); + int black = ContextCompat.getColor(this, 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); + int white = ContextCompat.getColor(this, R.color.white); Resources resources = this.getResources(); float textSizeSvg = resources.getDimension(R.dimen.simple_ui_svg_text_size); @@ -718,9 +720,11 @@ public abstract class BaseWatchFace extends WatchFace { if (chart != null && graphData.getEntries().size() > 0) { int timeframe = sp.getInt("chart_timeframe", 3); if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), graphData.getEntries(), treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); + bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, + graphData.getEntries(), treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); } else { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), graphData.getEntries(), treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); + bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, graphData.getEntries(), + treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); } chart.setLineChartData(bgGraphBuilder.lineData()); 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 2dd39c850f..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java +++ /dev/null @@ -1,498 +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.shared.weardata.EventData; -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; - -/** - * 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; - - 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<>(); - - //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() - (1000L * 60 * 60 * timespan); //timespan - // hours ago - this.bgDataList = aBgList; - this.predictionsList = predictionsList; - this.context = context; - this.highMark = aBgList.get(aBgList.size() - 1).getHigh(); - this.lowMark = aBgList.get(aBgList.size() - 1).getLow(); - 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() + (1000L * 60 * 6 * timespan); //Now plus 30 - // minutes padding (for 5 hours. Less if less.) - this.predictionEndTime = getPredictionEndTime(); - this.end_time = Math.max(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() - (1000L * 60 * 60 * timespan); //timespan - // hours ago - this.bgDataList = aBgList; - this.predictionsList = predictionsList; - this.context = context; - this.highMark = aBgList.get(aBgList.size() - 1).getHigh(); - this.lowMark = aBgList.get(aBgList.size() - 1).getLow(); - 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() + (1000L * 60 * 6 * timespan); //Now plus 30 - // minutes padding (for 5 hours. Less if less.) - this.predictionEndTime = getPredictionEndTime(); - this.end_time = Math.max(predictionEndTime, end_time); - } - - 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 (EventData.SingleBg bgd : bgDataList) { - if (bgd.getSgv() > maxChart) { - maxChart = bgd.getSgv(); - } - if (bgd.getSgv() < minChart) { - minChart = bgd.getSgv(); - } - } - - double maxBasal = 0.1; - for (EventData.TreatmentData.Basal bwd : basalWatchDataList) { - if (bwd.getAmount() > maxBasal) { - maxBasal = bwd.getAmount(); - } - } - - double maxTemp = maxBasal; - for (EventData.TreatmentData.TempBasal twd : tempWatchDataList) { - if (twd.getAmount() > maxTemp) { - maxTemp = twd.getAmount(); - } - } - - 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 (EventData.TreatmentData.TempBasal twd : tempWatchDataList) { - if (twd.getEndTime() > 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 (EventData.TreatmentData.Basal bwd : basalWatchDataList) { - if (bwd.getEndTime() > start_time) { - long begin = Math.max(start_time, bwd.getStartTime()); - pointValues.add(new PointValue(fuzz(begin), offset + (float) (factor * bwd.getAmount()))); - pointValues.add(new PointValue(fuzz(bwd.getEndTime()), - offset + (float) (factor * bwd.getAmount()))); - } - } - - 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 (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { - if (bwd.getDate() > start_time && bwd.getDate() <= end_time && !bwd.isSMB() && bwd.isValid() && bwd.getBolus() > 0) { - pointValues.add(new PointValue(fuzz(bwd.getDate()), 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 (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { - if (bwd.getDate() > start_time && bwd.getDate() <= end_time && bwd.isSMB() && bwd.isValid() && bwd.getBolus() > 0) { - pointValues.add(new PointValue(fuzz(bwd.getDate()), 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 (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { - if (bwd.getDate() > start_time && bwd.getDate() <= end_time && !(bwd.isValid() && (bwd.getBolus() > 0 || bwd.getCarbs() > 0))) { - pointValues.add(new PointValue(fuzz(bwd.getDate()), 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 (EventData.TreatmentData.Treatment bwd : bolusWatchDataList) { - if (bwd.getDate() > start_time && bwd.getDate() <= end_time && !bwd.isSMB() && bwd.isValid() && bwd.getCarbs() > 0) { - pointValues.add(new PointValue(fuzz(bwd.getDate()), 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 (EventData.SingleBg bwd : predictionsList) { - if (bwd.getTimeStamp() <= endTime) { - double value = Math.min(bwd.getSgv(), UPPER_CUTOFF_SGV); - if (!values.containsKey(bwd.getColor())) { - values.put(bwd.getColor(), new ArrayList<>()); - } - values.get(bwd.getColor()).add(new PointValue(fuzz(bwd.getTimeStamp()), (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(EventData.TreatmentData.TempBasal twd, float offset, double factor, boolean isHighlightLine, int strokeWidth) { - List lineValues = new ArrayList<>(); - long begin = Math.max(start_time, twd.getStartTime()); - lineValues.add(new PointValue(fuzz(begin), offset + (float) (factor * twd.getStartBasal()))); - lineValues.add(new PointValue(fuzz(begin), offset + (float) (factor * twd.getAmount()))); - lineValues.add(new PointValue(fuzz(twd.getEndTime()), offset + (float) (factor * twd.getAmount()))); - lineValues.add(new PointValue(fuzz(twd.getEndTime()), offset + (float) (factor * twd.getEndBasal()))); - 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 (EventData.SingleBg bgReading : bgDataList) { - if (bgReading.getTimeStamp() > start_time) { - if (bgReading.getSgv() >= 450) { - inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) 450)); - } else if (bgReading.getSgv() >= highMark) { - inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); - } else if (bgReading.getSgv() >= lowMark) { - inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); - } else if (bgReading.getSgv() >= 40) { - inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); - } else if (bgReading.getSgv() >= 11) { - inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) 40)); - } - } - } - } else { - for (EventData.SingleBg bgReading : bgDataList) { - if (bgReading.getTimeStamp() > start_time) { - if (bgReading.getSgv() >= 450) { - highValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) 450)); - } else if (bgReading.getSgv() >= highMark) { - highValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); - } else if (bgReading.getSgv() >= lowMark) { - inRangeValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); - } else if (bgReading.getSgv() >= 40) { - lowValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (float) bgReading.getSgv())); - } else if (bgReading.getSgv() >= 11) { - lowValues.add(new PointValue(fuzz(bgReading.getTimeStamp()), (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 (EventData.SingleBg prediction : - predictionsList) { - if (maxPredictionDate < prediction.getTimeStamp()) { - maxPredictionDate = prediction.getTimeStamp(); - } - } - 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/DigitalStyle.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java index d9eb309742..7ee43e93b1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java @@ -59,36 +59,36 @@ public class DigitalStyle extends BaseWatchFace { protected void setColorDark() { if (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); } else if (singleBg.getSgvLevel() == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); + 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(getApplicationContext(), R.color.dark_midColor)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); } if (status.getBatteryLevel() == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); + mUploaderBattery.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); + mUploaderBattery.setTextColor(ContextCompat.getColor(this, 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); + 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(); @@ -109,7 +109,7 @@ public class DigitalStyle extends BaseWatchFace { // Load image with shapes String styleDrawableName = "digitalstyle_bg_" + displayStyle + "_" + displayFormatType; try { - mShapesElements.setBackground(getResources().getDrawable(getResources().getIdentifier(styleDrawableName, "drawable", getApplicationContext().getPackageName()))); + mShapesElements.setBackground(getResources().getDrawable(getResources().getIdentifier(styleDrawableName, "drawable", this.getPackageName()))); } catch (Exception e) { aapsLogger.error("digitalstyle_frameStyle", "RESOURCE NOT FOUND >> " + styleDrawableName); } @@ -121,7 +121,7 @@ public class DigitalStyle extends BaseWatchFace { String strColorName =(( displayFrameColor.equals("white") || displayFrameColor.equals("black") )?displayFrameColor:displayFrameColor+"_"+displayFrameColorSaturation); aapsLogger.debug(LTag.WEAR,"digitalstyle_strColorName",strColorName); try { - ColorStateList colorStateList = ContextCompat.getColorStateList(getApplicationContext(), getResources().getIdentifier(strColorName, "color", getApplicationContext().getPackageName())); + ColorStateList colorStateList = ContextCompat.getColorStateList(this, getResources().getIdentifier(strColorName, "color", this.getPackageName())); mShapesElements.setBackgroundTintList(colorStateList); } catch (Exception e) { mShapesElements.setBackgroundTintList(null); diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java index 6c5a2eb0e2..a16dbd7af0 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java @@ -67,66 +67,66 @@ public class Home extends BaseWatchFace { protected void setColorDark() { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == -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)); + 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(getApplicationContext(), dividerMatchesBg ? + mTimestamp.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mTimestamp1_home)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); } if (status.getBatteryLevel() == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mUploaderBattery.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); + mUploaderBattery.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)); } - mStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mStatus.setTextColor(ContextCompat.getColor(this, 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); + 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(); } } 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)); + 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(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); + 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(); } @@ -137,21 +137,21 @@ public class Home extends BaseWatchFace { protected void setColorBright() { if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.light_background : R.color.light_stripe_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == -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)); + 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) { @@ -169,12 +169,12 @@ public class Home extends BaseWatchFace { 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); + 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(); } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java index 6ffec5d910..bc465070f6 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java @@ -71,47 +71,47 @@ public class Home2 extends BaseWatchFace { protected void setColorDark() { @ColorInt final int dividerTxtColor = dividerMatchesBg ? - ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor) : Color.BLACK; - @ColorInt final int dividerBatteryOkColor = ContextCompat.getColor(getApplicationContext(), + ContextCompat.getColor(this, R.color.dark_midColor) : Color.BLACK; + @ColorInt final int dividerBatteryOkColor = ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery); - @ColorInt final int dividerBgColor = ContextCompat.getColor(getApplicationContext(), + @ColorInt final int dividerBgColor = ContextCompat.getColor(this, 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)); + 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(); if (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); } else if (singleBg.getSgvLevel() == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); + 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(getApplicationContext(), R.color.dark_midColor)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); } if (status.getBatteryLevel() == 1) { mUploaderBattery.setTextColor(dividerBatteryOkColor); } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); + mUploaderBattery.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)); } mRigBattery.setTextColor(dividerTxtColor); mDelta.setTextColor(dividerTxtColor); @@ -128,12 +128,12 @@ public class Home2 extends BaseWatchFace { } 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); + 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(); } @@ -141,38 +141,38 @@ public class Home2 extends BaseWatchFace { protected void setColorLowRes() { @ColorInt final int dividerTxtColor = dividerMatchesBg ? - ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor) : Color.BLACK; - @ColorInt final int dividerBgColor = ContextCompat.getColor(getApplicationContext(), + ContextCompat.getColor(this, R.color.dark_midColor) : Color.BLACK; + @ColorInt final int dividerBgColor = ContextCompat.getColor(this, 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)); + 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(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)); + 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(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)); + 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(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); + 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(); } @@ -184,13 +184,13 @@ public class Home2 extends BaseWatchFace { 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(), + ContextCompat.getColor(this, R.color.dark_midColor); + @ColorInt final int dividerBgColor = ContextCompat.getColor(this, 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)); + 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); @@ -203,14 +203,14 @@ public class Home2 extends BaseWatchFace { setTextSizes(); if (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)); } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)); } else if (singleBg.getSgvLevel() == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); + mSgv.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)); + mDirection.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)); } if (ageLevel == 1) { @@ -239,12 +239,12 @@ public class Home2 extends BaseWatchFace { } 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); + 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(); } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java index 7ba6053ad4..a176f393f3 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java @@ -51,59 +51,59 @@ public class LargeHome extends BaseWatchFace { @Override protected void setColorDark(){ - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == -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)); + 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(getApplicationContext(), dividerMatchesBg ? + mTimestamp.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mTimestamp1_home)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); } if (status.getBatteryLevel() == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mUploaderBattery.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); + mUploaderBattery.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)); } - mStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mStatus_home)); + mStatus.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mStatus_home)); } @Override protected void setColorBright() { if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? + mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.light_background : R.color.light_stripe_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == 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)); + 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)); } else if (singleBg.getSgvLevel() == -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)); + 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) { @@ -145,14 +145,14 @@ public class LargeHome extends BaseWatchFace { @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)); + mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_background : 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, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mTimestamp1_home)); + mUploaderBattery.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); + mStatus.setTextColor(ContextCompat.getColor(this, 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 index 9524b63772..f8cc8ab9f2 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java @@ -292,37 +292,37 @@ public class NOChart extends WatchFace { } 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); + statusView.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)); } 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); + statusView.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, 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)); + 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)); } 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)); + 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)); } 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)); + 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(getApplicationContext(), R.color.dark_Timestamp)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); } } @@ -330,27 +330,27 @@ public class NOChart extends WatchFace { 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)); + mTime.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)); + statusView.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)); + mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, 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)); + 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)); } 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)); + 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)); } 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)); + 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(getApplicationContext(), R.color.light_mTimestamp1)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp1)); } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp)); + mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp)); } } else { setColorDark(); diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 7561a48cf5..9f4e614874 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -195,5 +195,6 @@ showWizard singletarget wizardpercentage + highlight_basals diff --git a/wear/src/main/res/xml/preferences.xml b/wear/src/main/res/xml/preferences.xml index 517d6a982e..a5f639c979 100644 --- a/wear/src/main/res/xml/preferences.xml +++ b/wear/src/main/res/xml/preferences.xml @@ -87,7 +87,7 @@ Date: Sat, 23 Apr 2022 18:35:43 +0200 Subject: [PATCH 22/54] update crowdin --- crowdin.yml | 2 ++ 1 file changed, 2 insertions(+) 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 From ec5a09bdb07f6ffc108008471a8377bcd53ac7f7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 10:08:25 +0200 Subject: [PATCH 23/54] DateUtil lints --- .../activities/HistoryBrowseActivity.kt | 2 +- .../automation/elements/InputDateTime.kt | 2 +- .../androidaps/data/ProfileSealed.kt | 4 +- .../dialogs/DialogFragmentWithDate.kt | 2 +- .../androidaps/dialogs/ProfileViewerDialog.kt | 10 ++-- .../nightscout/androidaps/data/ProfileTest.kt | 2 +- .../nightscout/androidaps/utils/DateUtil.kt | 59 ++++++++++--------- 7 files changed, 41 insertions(+), 40 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt index ab12179b23..1844e9ba9f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt @@ -150,7 +150,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { binding.date.setOnClickListener { MaterialDatePicker.Builder.datePicker() - .setSelection(dateUtil.timeStampToUtcDateMilis(overviewData.fromTime)) + .setSelection(dateUtil.timeStampToUtcDateMillis(overviewData.fromTime)) .setTheme(R.style.DatePicker) .build() .apply { 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 30edd95129..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 @@ -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/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt index 7746345d70..6c3e5b29db 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt @@ -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/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/ProfileViewerDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt index c3141fc71a..99fdc2f917 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -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/test/java/info/nightscout/androidaps/data/ProfileTest.kt b/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt index e32fa39a4e..fd28bdb158 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt @@ -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/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt index e05ba8ecb6..e3939443dc 100644 --- a/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt +++ b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt @@ -1,6 +1,8 @@ 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.interfaces.ResourceHelper @@ -10,6 +12,7 @@ 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 { @@ -174,20 +178,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 { @@ -198,12 +202,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) @@ -255,11 +259,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() @@ -277,7 +276,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)) } @@ -376,13 +375,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") @@ -394,7 +394,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)) @@ -403,8 +403,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)) @@ -425,7 +425,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 From 9a78a4cf9f0ee2643f3efc53a6cd9364d9b95469 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 17:20:29 +0200 Subject: [PATCH 24/54] Wear: Watchfaces -> kt --- .../info/nightscout/androidaps/MainApp.kt | 2 - build.gradle | 3 +- core/core_dependencies.gradle | 1 - shared/build.gradle | 2 +- .../androidaps/extensions/UIUtils.kt | 0 .../nightscout/androidaps/utils/DateUtil.kt | 22 + wear/src/main/AndroidManifest.xml | 32 +- .../androidaps/di/WearServicesModule.kt | 14 +- .../interaction/actions/AcceptActivity.kt | 4 +- .../interaction/utils/Inevitable.java | 22 +- .../interaction/utils/WearUtil.java | 5 - .../watchfaces/AapsLargeWatchface.kt | 148 ++++ .../androidaps/watchfaces/AapsV2Watchface.kt | 235 ++++++ .../androidaps/watchfaces/AapsWatchface.kt | 174 ++++ .../androidaps/watchfaces/BIGChart.java | 491 ------------ .../androidaps/watchfaces/BaseWatchFace.java | 744 ------------------ .../androidaps/watchfaces/BaseWatchFace.kt | 547 +++++++++++++ .../watchfaces/BigChartWatchface.kt | 428 ++++++++++ .../watchfaces/CircleWatchface.java | 534 ------------- .../androidaps/watchfaces/CircleWatchface.kt | 445 +++++++++++ .../androidaps/watchfaces/Cockpit.java | 122 --- .../androidaps/watchfaces/CockpitWatchface.kt | 105 +++ .../androidaps/watchfaces/DigitalStyle.java | 173 ---- .../watchfaces/DigitalStyleWatchface.kt | 162 ++++ .../androidaps/watchfaces/Home.java | 185 ----- .../androidaps/watchfaces/Home2.java | 270 ------- .../androidaps/watchfaces/LargeHome.java | 158 ---- .../androidaps/watchfaces/NOChart.java | 368 --------- .../androidaps/watchfaces/NoChartWatchface.kt | 324 ++++++++ .../watchfaces/SteampunkWatchface.kt | 105 +-- .../res/layout-notround/activity_bigchart.xml | 2 +- .../activity_bigchart_small.xml | 2 +- .../res/layout-notround/activity_cockpit.xml | 2 +- .../layout-notround/activity_digitalstyle.xml | 17 +- .../res/layout-notround/activity_home.xml | 2 +- .../res/layout-notround/activity_home_2.xml | 2 +- .../layout-notround/activity_home_large.xml | 2 +- .../res/layout-notround/activity_nochart.xml | 2 +- .../activity_nochart_small.xml | 2 +- .../res/layout-round/activity_bigchart.xml | 2 +- .../layout-round/activity_bigchart_small.xml | 2 +- .../res/layout-round/activity_cockpit.xml | 2 +- .../layout-round/activity_digitalstyle.xml | 17 +- .../main/res/layout-round/activity_home.xml | 2 +- .../main/res/layout-round/activity_home_2.xml | 2 +- .../res/layout-round/activity_home_large.xml | 2 +- .../res/layout-round/activity_nochart.xml | 2 +- .../layout-round/activity_nochart_small.xml | 2 +- wear/src/main/res/values/strings.xml | 29 +- wear/src/main/res/xml/preferences.xml | 14 +- .../xml/watch_face_configuration_circle.xml | 4 +- .../watch_face_configuration_digitalstyle.xml | 4 +- .../xml/watch_face_configuration_home2.xml | 2 +- 53 files changed, 2733 insertions(+), 3211 deletions(-) rename {core => shared}/src/main/java/info/nightscout/androidaps/extensions/UIUtils.kt (100%) create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java delete mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt index b40327bd1d..09cc6915bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt @@ -53,7 +53,6 @@ import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.exceptions.UndeliverableException import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.plugins.RxJavaPlugins -import net.danlew.android.joda.JodaTimeAndroid import java.io.IOException import java.net.SocketException import java.util.concurrent.TimeUnit @@ -102,7 +101,6 @@ class MainApp : DaggerApplication() { } disposable += compatDBHelper.dbChangeDisposable() registerActivityLifecycleCallbacks(activityMonitor) - JodaTimeAndroid.init(this) profileSwitchPlugin.setThemeMode() aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME) aapsLogger.debug("BuildVersion: " + BuildConfig.BUILDVERSION) diff --git a/build.gradle b/build.gradle index a6f867adc6..ddcd91c207 100644 --- a/build.gradle +++ b/build.gradle @@ -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' diff --git a/core/core_dependencies.gradle b/core/core_dependencies.gradle index d824f0c142..c88b6f4d48 100644 --- a/core/core_dependencies.gradle +++ b/core/core_dependencies.gradle @@ -75,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/shared/build.gradle b/shared/build.gradle index 8e5b960778..c4f3cfb88a 100644 --- a/shared/build.gradle +++ b/shared/build.gradle @@ -18,7 +18,7 @@ android { dependencies { api "androidx.preference:preference-ktx:$preferencektx_version" - api 'net.danlew:android.joda:2.10.6' + api "net.danlew:android.joda:$joga_version" // for old fashioned support-app version (wear) api "com.google.dagger:dagger:$dagger_version" 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/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt index e3939443dc..5578a94a92 100644 --- a/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt +++ b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt @@ -136,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)) { @@ -144,6 +145,11 @@ 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)) { @@ -152,6 +158,22 @@ class DateUtil @Inject constructor(private val context: Context) { 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)) { diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 0964bca9fe..ec2f3a4f8e 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -27,9 +27,9 @@ android:value="@integer/google_play_services_version" /> 0) { - aapsLogger.debug(LTag.WEAR, "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; 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 index 05654ea6ea..5f22657035 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java @@ -38,11 +38,6 @@ public class WearUtil { // 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(); } 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..71bf90aa78 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt @@ -0,0 +1,148 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +import android.graphics.Color +import android.support.wearable.watchface.WatchFaceStyle +import android.view.LayoutInflater +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interaction.menus.MainMenuActivity + +class AapsLargeWatchface : BaseWatchFace() { + + private var sgvTapTime: Long = 0 + + @SuppressLint("InflateParams") + override fun onCreate() { + super.onCreate() + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + layoutView = inflater.inflate(R.layout.activity_home_large, null) + performViewSetup() + } + + 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() + } + + 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..438009813c --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt @@ -0,0 +1,235 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +import android.graphics.Color +import android.support.wearable.watchface.WatchFaceStyle +import android.view.LayoutInflater +import androidx.annotation.ColorInt +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interaction.menus.MainMenuActivity + +class AapsV2Watchface : BaseWatchFace() { + + private var chartTapTime: Long = 0 + private var sgvTapTime: Long = 0 + + @SuppressLint("InflateParams") + override fun onCreate() { + super.onCreate() + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + layoutView = inflater.inflate(R.layout.activity_home_2, null) + performViewSetup() + } + + 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) { + val intent = Intent(this, MainMenuActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + sgvTapTime = eventTime + } + } + } + + private 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() + } + + 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..42d16e0763 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt @@ -0,0 +1,174 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +import android.graphics.Color +import android.support.wearable.watchface.WatchFaceStyle +import android.view.LayoutInflater +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interaction.menus.MainMenuActivity + +class AapsWatchface : BaseWatchFace() { + + private var chartTapTime: Long = 0 + private var sgvTapTime: Long = 0 + + @SuppressLint("InflateParams") + override fun onCreate() { + super.onCreate() + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + layoutView = inflater.inflate(R.layout.activity_home, null) + performViewSetup() + } + + 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) { + val intent = Intent(this, MainMenuActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + sgvTapTime = eventTime + } + } + } + + private 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() + } + + 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 e25270cf3e..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java +++ /dev/null @@ -1,491 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.Intent; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Point; -import android.graphics.Rect; -import android.os.PowerManager; -import android.support.wearable.watchface.WatchFaceStyle; -import android.text.format.DateFormat; -import android.util.DisplayMetrics; -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 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 java.util.ArrayList; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; -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 io.reactivex.rxjava3.disposables.CompositeDisposable; -import lecho.lib.hellocharts.view.LineChartView; - -/** - * Created by adrianLxM. - */ -@SuppressWarnings("deprecation") -public class BIGChart extends WatchFace { - - @Inject RxBus rxBus; - @Inject AapsSchedulers aapsSchedulers; - @Inject AAPSLogger aapsLogger; - @Inject SP sp; - @Inject DateUtil dateUtil; - - CompositeDisposable disposable = new CompositeDisposable(); - - private EventData.SingleBg singleBg; - private EventData.Status status; - private EventData.TreatmentData treatmentData; - private EventData.GraphData graphData; - - private static final int SCREEN_SIZE_SMALL = 280; - private TextView mTime, mSgv, mTimestamp, mDelta, mAvgDelta; - private RelativeLayout mRelativeLayout; - - 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 ArrayList bgDataList = new ArrayList<>(); - - public PowerManager.WakeLock wakeLock; - public View layoutView; - private final Point displaySize = new Point(); - private int specW, specH; - - private TextView statusView; - private long chartTapTime = 0L; - private long sgvTapTime = 0L; - - @SuppressLint("InflateParams") - @Override - public void onCreate() { - AndroidInjection.inject(this); - 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); - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - DisplayMetrics metrics = getResources().getDisplayMetrics(); - if (metrics.widthPixels < SCREEN_SIZE_SMALL || metrics.heightPixels < SCREEN_SIZE_SMALL) { - layoutView = inflater.inflate(R.layout.activity_bigchart_small, null); - } else { - layoutView = inflater.inflate(R.layout.activity_bigchart, null); - } - performViewSetup(); - disposable.add(rxBus - .toObservable(EventData.SingleBg.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - aapsLogger.debug(LTag.WEAR, "SingleBg received"); - singleBg = event; - - mSgv.setText(singleBg.getSgvString()); - 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())); - mDelta.setText(singleBg.getDelta()); - mAvgDelta.setText(singleBg.getAvgDelta()); - }) - ); - disposable.add(rxBus - .toObservable(EventData.TreatmentData.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> treatmentData = event) - ); - disposable.add(rxBus - .toObservable(EventData.GraphData.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> graphData = event) - ); - disposable.add(rxBus - .toObservable(EventData.Status.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - // this event is received as last batch of data - aapsLogger.debug(LTag.WEAR, "Status received"); - status = event; - showAgeAndStatus(); - addToWatchSet(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - }) - ); - disposable.add(rxBus - .toObservable(EventData.Preferences.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - setColor(); - if (layoutSet) { - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - invalidate(); - }) - ); - } - - @Override - protected void onLayout(WatchShape shape, Rect screenBounds, WindowInsets screenInsets) { - super.onLayout(shape, screenBounds, screenInsets); - layoutView.onApplyWindowInsets(screenInsets); - } - - public void performViewSetup() { - mTime = layoutView.findViewById(R.id.watch_time); - mSgv = layoutView.findViewById(R.id.sgv); - mTimestamp = layoutView.findViewById(R.id.timestamp); - mDelta = layoutView.findViewById(R.id.delta); - mAvgDelta = layoutView.findViewById(R.id.avgdelta); - mRelativeLayout = layoutView.findViewById(R.id.main_layout); - chart = layoutView.findViewById(R.id.chart); - statusView = layoutView.findViewById(R.id.aps_status); - layoutSet = true; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:performViewSetup"))); - 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 = sp.getInt("chart_timeframe", 3); - timeframe = (timeframe % 5) + 1; - sp.putInt("chart_timeframe", timeframe); - } - - protected void onWatchModeChanged(WatchMode watchMode) { - - if (lowResMode ^ isLowRes(watchMode)) { //if there was a change in lowResMode - lowResMode = isLowRes(watchMode); - setColor(); - } else if (!sp.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); - } - - - @SuppressWarnings("deprecation") - @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() - singleBg.getTimeStamp(); - } - - public String readingAge(boolean shortString) { - if (singleBg == null || singleBg.getTimeStamp() == 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() { - disposable.clear(); - super.onDestroy(); - } - - @Override - protected void onDraw(Canvas canvas) { - if (layoutSet) { - this.mRelativeLayout.draw(canvas); - } - } - - @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()); - } - } - - private void showAgeAndStatus() { - - if (mTimestamp != null) { - mTimestamp.setText(readingAge(true)); - } - - boolean showStatus = sp.getBoolean("showExternalStatus", true); - boolean showAvgDelta = sp.getBoolean("showAvgDelta", true); - - if (showAvgDelta) { - mAvgDelta.setVisibility(View.VISIBLE); - } else { - mAvgDelta.setVisibility(View.GONE); - } - - if (showStatus && status != null) { - String status = this.status.getExternalStatus(); - if (sp.getBoolean("show_cob", true)) { - status += " " + this.status.getCob(); - } - - statusView.setText(status); - statusView.setVisibility(View.VISIBLE); - } else { - statusView.setVisibility(View.GONE); - } - } - - public void setColor() { - if (lowResMode) { - setColorLowRes(); - } else if (sp.getBoolean("dark", true)) { - setColorDark(); - } else { - setColorBright(); - } - - } - - protected void setColorLowRes() { - mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); - statusView.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); - gridColour = 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(); - } - - } - - protected void setColorDark() { - if (singleBg != null) { - mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); - statusView.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); - if (singleBg.getSgvLevel() == 1) { - 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)); - } else if (singleBg.getSgvLevel() == 0) { - 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)); - } else if (singleBg.getSgvLevel() == -1) { - 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); - gridColour = 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(); - } - } - } - - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mTime.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)); - statusView.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); - if (singleBg.getSgvLevel() == 1) { - 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)); - } else if (singleBg.getSgvLevel() == 0) { - 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)); - } else if (singleBg.getSgvLevel() == -1) { - 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); - gridColour = 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(); - } - } - - public void missedReadingAlert() { - int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); - if (minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - // attempt endTime recover missing data - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:missedReadingAlert"))); - } - } - - public void addToWatchSet() { - if (graphData != null) { - bgDataList = graphData.getEntries(); - } else { - final int size = bgDataList.size(); - if (size > 0 && bgDataList.get(size - 1).getTimeStamp() == singleBg.getTimeStamp()) - return; // Ignore duplicates. - bgDataList.add(singleBg); - } - } - - public void setupCharts() { - if (bgDataList.size() > 0) { - int timeframe = sp.getInt("chart_timeframe", 3); - if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, bgDataList, - treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); - } else { - bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, bgDataList, - treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); - } - - chart.setLineChartData(bgGraphBuilder.lineData()); - chart.setViewportCalculationEnabled(true); - chart.setMaximumViewport(chart.getMaximumViewport()); - } else { - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BIGChart:setupCharts"))); - } - } -} 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 b28d48826e..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ /dev/null @@ -1,744 +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.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.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 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.ArrayList; -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.events.EventWearPreferenceChange; -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.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 io.reactivex.rxjava3.disposables.CompositeDisposable; -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 { - - @Inject WearUtil wearUtil; - @Inject Persistence persistence; - @Inject AAPSLogger aapsLogger; - @Inject RxBus rxBus; - @Inject AapsSchedulers aapsSchedulers; - @Inject SP sp; - @Inject DateUtil dateUtil; - - CompositeDisposable disposable = new CompositeDisposable(); - - protected EventData.SingleBg singleBg = new EventData.SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0); - protected EventData.Status status = new EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1); - protected EventData.TreatmentData treatmentData = new EventData.TreatmentData(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); - protected EventData.GraphData graphData = new EventData.GraphData(new ArrayList<>()); - - 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 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"; - 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(this, R.color.dark_highColor); - colorDarkMid = ContextCompat.getColor(this, R.color.dark_midColor); - colorDarkLow = ContextCompat.getColor(this, R.color.dark_lowColor); - - 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); - } - - disposable.add(rxBus - .toObservable(EventWearPreferenceChange.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - setupBatteryReceiver(); - if (event.getChangedKey() != null && event.getChangedKey().equals("delta_granularity")) - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BaseWatchFace:onSharedPreferenceChanged"))); - if (layoutSet) setDataFields(); - invalidate(); - }) - ); - disposable.add(rxBus - .toObservable(EventData.SingleBg.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> singleBg = event) - ); - disposable.add(rxBus - .toObservable(EventData.TreatmentData.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> treatmentData = event) - ); - disposable.add(rxBus - .toObservable(EventData.GraphData.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> graphData = event) - ); - disposable.add(rxBus - .toObservable(EventData.Status.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - status = event; - // this event is received as last batch of data - if (!isSimpleUi() || !needUpdate()) { - setupCharts(); - setDataFields(); - } - invalidate(); - }) - ); - - persistence.turnOff(); - - setupBatteryReceiver(); - initFormats(); - setupSimpleUi(); - } - - private void setupBatteryReceiver() { - String setting = sp.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(this, 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(this, 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() { - mTime = layoutView.findViewById(R.id.watch_time); - mHour = layoutView.findViewById(R.id.hour); - mMinute = layoutView.findViewById(R.id.minute); - mTimePeriod = layoutView.findViewById(R.id.timePeriod); - 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(); - - wakeLock.acquire(50); - } - - public int ageLevel() { - if (timeSince() <= (1000 * 60 * 12)) { - return 1; - } - return 0; - } - - public double timeSince() { - return System.currentTimeMillis() - singleBg.getTimeStamp(); - } - - public String readingAge(boolean shortString) { - if (singleBg.getTimeStamp() == 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() { - disposable.clear(); - 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 = singleBg.getTimeStamp() > 0 && ageLevel() <= 0; - mSvgPaint.setStrikeThruText(isOutdated); - - mSvgPaint.setColor(getBgColour(singleBg.getSgvLevel())); - mDirectionPaint.setColor(getBgColour(singleBg.getSgvLevel())); - - String sSvg = singleBg.getSgvString(); - float svgWidth = mSvgPaint.measureText(sSvg); - - String sDirection = " " + singleBg.getSgvString() + "\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 = sp.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 (sp.getBoolean("showBG", true)) { - mSgv.setText(singleBg.getSgvString()); - 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 (sp.getBoolean("show_direction", true)) { - mDirection.setText(singleBg.getSgvString() + "\uFE0E"); - mDirection.setVisibility(View.VISIBLE); - } else { - mDirection.setVisibility(View.GONE); - } - } - - if (mDelta != null) { - if (sp.getBoolean("showDelta", true)) { - mDelta.setText(singleBg.getDelta()); - mDelta.setVisibility(View.VISIBLE); - } else { - mDelta.setVisibility(View.GONE); - } - } - - if (mAvgDelta != null) { - if (sp.getBoolean("showAvgDelta", true)) { - mAvgDelta.setText(singleBg.getAvgDelta()); - mAvgDelta.setVisibility(View.VISIBLE); - } else { - mAvgDelta.setVisibility(View.GONE); - } - } - - if (mCOB1 != null && mCOB2 != null) { - mCOB2.setText(status.getCob()); - if (sp.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(status.getCob()); - if (sp.getBoolean("show_cob", true)) { - mCOB2.setVisibility(View.VISIBLE); - } else { - mCOB2.setVisibility(View.GONE); - } - } - - if (mIOB1 != null && mIOB2 != null) { - if (sp.getBoolean("show_iob", true)) { - mIOB1.setVisibility(View.VISIBLE); - mIOB2.setVisibility(View.VISIBLE); - if (status.getDetailedIob()) { - mIOB1.setText(status.getIobSum()); - mIOB2.setText(status.getIobDetail()); - } else { - mIOB1.setText(getString(R.string.activity_IOB)); - mIOB2.setText(status.getIobSum()); - } - } 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 (sp.getBoolean("show_iob", true)) { - mIOB2.setVisibility(View.VISIBLE); - if (status.getDetailedIob()) { - mIOB2.setText(status.getIobDetail()); - } else { - mIOB2.setText(status.getIobSum()); - } - } else { - mIOB2.setText(""); - } - } - - if (mTimestamp != null) { - if (sp.getBoolean("showAgo", true)) { - if (isAAPSv2 != null) { - mTimestamp.setText(readingAge(true)); - } else { - boolean shortString = sp.getBoolean("showExternalStatus", true); - mTimestamp.setText(readingAge(shortString)); - } - mTimestamp.setVisibility(View.VISIBLE); - } else { - mTimestamp.setVisibility(View.GONE); - } - } - - if (mUploaderBattery != null) { - if (sp.getBoolean("show_uploader_battery", true)) { - if (isAAPSv2 != null) { - mUploaderBattery.setText(status.getBattery() + "%"); - mUploaderBattery.setVisibility(View.VISIBLE); - } else { - if (sp.getBoolean("showExternalStatus", true)) { - mUploaderBattery.setText("U: " + status.getBattery() + "%"); - } else { - mUploaderBattery.setText("Uploader: " + status.getBattery() + "%"); - } - } - } else { - mUploaderBattery.setVisibility(View.GONE); - } - } - - if (mRigBattery != null) { - if (sp.getBoolean("show_rig_battery", false)) { - mRigBattery.setText(status.getRigBattery()); - mRigBattery.setVisibility(View.VISIBLE); - } else { - mRigBattery.setVisibility(View.GONE); - } - } - - if (mBasalRate != null) { - if (sp.getBoolean("show_temp_basal", true)) { - mBasalRate.setText(status.getCurrentBasal()); - mBasalRate.setVisibility(View.VISIBLE); - } else { - mBasalRate.setVisibility(View.GONE); - } - } - - if (mBgi != null) { - if (status.getShowBgi()) { - mBgi.setText(status.getBgi()); - mBgi.setVisibility(View.VISIBLE); - } else { - mBgi.setVisibility(View.GONE); - } - } - - if (mStatus != null) { - if (sp.getBoolean("showExternalStatus", true)) { - mStatus.setText(status.getExternalStatus()); - mStatus.setVisibility(View.VISIBLE); - } else { - mStatus.setVisibility(View.GONE); - } - } - - if (mLoop != null) { - if (sp.getBoolean("showExternalStatus", true)) { - mLoop.setVisibility(View.VISIBLE); - if (status.getOpenApsStatus() != -1) { - int mins = (int) ((System.currentTimeMillis() - status.getOpenApsStatus()) / 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 (sp.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 = sp.getBoolean("match_divider", false); - if (lowResMode) { - setColorLowRes(); - } else if (sp.getBoolean("dark", true)) { - setColorDark(); - } else { - setColorBright(); - } - } - - public void strikeThroughSgvIfNeeded() { - if (mSgv != null) { - if (sp.getBoolean("showBG", true)) { - if (ageLevel() <= 0 && singleBg.getTimeStamp() > 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 = sp.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(); - } - - 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 (singleBg.getTimeStamp() == 0 || minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - // Attempt endTime recover missing data - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("BaseWatchFace:missedReadingAlert"))); - } - } - - public void setupCharts() { - if (isSimpleUi()) { - return; - } - if (chart != null && graphData.getEntries().size() > 0) { - int timeframe = sp.getInt("chart_timeframe", 3); - if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, - graphData.getEntries(), treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); - } else { - bgGraphBuilder = new BgGraphBuilder(sp, dateUtil, graphData.getEntries(), - treatmentData.getPredictions(), treatmentData.getTemps(), treatmentData.getBasals(), treatmentData.getBoluses(), pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); - } - - chart.setLineChartData(bgGraphBuilder.lineData()); - chart.setViewportCalculationEnabled(true); - chart.setMaximumViewport(chart.getMaximumViewport()); - } - } - - private boolean needUpdate() { - if (mLastSvg.equals(singleBg.getSgvString()) && mLastDirection.equals(singleBg.getSgvString())) { - return false; - } - mLastSvg = singleBg.getSgvString(); - mLastDirection = singleBg.getSgvString(); - 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..61df905c48 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt @@ -0,0 +1,547 @@ +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.PowerManager +import android.os.Vibrator +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 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.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.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 + */ +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() + + protected var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) + protected var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) + protected var treatmentData = TreatmentData(ArrayList(), ArrayList(), ArrayList(), ArrayList()) + protected var graphData = EventData.GraphData(ArrayList()) + + 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 + var mMainMenuTap: LinearLayout? = 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 + var lowResMode = false + var layoutSet = false + var bIsRound = false + var dividerMatchesBg = false + var pointSize = 2 + var chart: LineChartView? = null + var wakeLock: PowerManager.WakeLock? = null + + // 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) + wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:BaseWatchFace") + 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(SingleBg::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: SingleBg -> singleBg = event } + disposable += rxBus + .toObservable(TreatmentData::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: TreatmentData -> treatmentData = event } + disposable += rxBus + .toObservable(EventData.GraphData::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: EventData.GraphData -> graphData = event } + disposable += rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: EventData.Status -> + status = event + // this event is received as last batch of data + if (!isSimpleUi || !needUpdate()) { + setupCharts() + setDataFields() + } + invalidate() + } + persistence.turnOff() + setupBatteryReceiver() + setupSimpleUi() + } + + 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 + } + + 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() + wakeLock?.acquire(50) + } + + fun ageLevel(): Int { + return if (timeSince() <= 1000 * 60 * 12) { + 1 + } else 0 + } + + fun timeSince(): Double { + return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() + } + + private 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))) { + val wl = wearUtil.getWakeLock("readingPrefs", 50) + missedReadingAlert() + checkVibrateHourly(oldTime, newTime) + if (!isSimpleUi) { + setDataFields() + } + wearUtil.releaseWakeLock(wl) + } + } + + 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") 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() + } + + private 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() + } + } + + private 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) + } +} \ 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..91872facc9 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt @@ -0,0 +1,428 @@ +@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.Rect +import android.os.PowerManager +import android.support.wearable.watchface.WatchFaceStyle +import android.text.format.DateFormat +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 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.events.EventWearToMobile +import info.nightscout.androidaps.extensions.toVisibility +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +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 lecho.lib.hellocharts.view.LineChartView +import javax.inject.Inject +import kotlin.math.floor + +class BigChartWatchface : WatchFace() { + + @Inject lateinit var rxBus: RxBus + @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var sp: SP + @Inject lateinit var dateUtil: DateUtil + + private var disposable = CompositeDisposable() + + private var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) + private var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) + private var treatmentData = TreatmentData(java.util.ArrayList(), java.util.ArrayList(), java.util.ArrayList(), java.util.ArrayList()) + private var graphData = EventData.GraphData(java.util.ArrayList()) + + private var mTime: TextView? = null + private var mSgv: TextView? = null + private var mTimestamp: TextView? = null + private var mDelta: TextView? = null + private var mAvgDelta: TextView? = null + private var mRelativeLayout: RelativeLayout? = null + private var ageLevel = 1 + private var highColor = Color.YELLOW + private var lowColor = Color.RED + private var midColor = Color.WHITE + private var gridColour = Color.WHITE + private var basalBackgroundColor = Color.BLUE + private var basalCenterColor = Color.BLUE + private var bolusColor = Color.MAGENTA + private var carbsColor = Color.GREEN + private var pointSize = 2 + private var lowResMode = false + private var layoutSet = false + var chart: LineChartView? = null + private var bgDataList = ArrayList() + private var wakeLock: PowerManager.WakeLock? = null + private var layoutView: View? = null + private val displaySize = Point() + private var specW = 0 + private var specH = 0 + private var statusView: TextView? = null + private var chartTapTime = 0L + private var sgvTapTime = 0L + + @SuppressLint("InflateParams") + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + val display = (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay + display.getSize(displaySize) + wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).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) + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + val metrics = resources.displayMetrics + layoutView = if (metrics.widthPixels < SCREEN_SIZE_SMALL || metrics.heightPixels < SCREEN_SIZE_SMALL) { + inflater.inflate(R.layout.activity_bigchart_small, null) + } else { + inflater.inflate(R.layout.activity_bigchart, null) + } + performViewSetup() + disposable.add(rxBus + .toObservable(SingleBg::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> + aapsLogger.debug(LTag.WEAR, "SingleBg received") + singleBg = event + mSgv?.text = singleBg.sgvString + mSgv?.let { mSgv -> + if (ageLevel() <= 0) mSgv.paintFlags = mSgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + else mSgv.paintFlags = mSgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + mTime?.text = dateUtil.timeString() + mDelta?.text = singleBg.delta + mAvgDelta?.text = singleBg.avgDelta + } + ) + disposable.add(rxBus + .toObservable(TreatmentData::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> treatmentData = event } + ) + disposable.add(rxBus + .toObservable(EventData.GraphData::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> graphData = event } + ) + disposable.add(rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received") + status = event + showAgeAndStatus() + addToWatchSet() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + invalidate() + setColor() + } + ) + disposable.add(rxBus + .toObservable(EventData.Preferences::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { + setColor() + if (layoutSet) { + showAgeAndStatus() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + } + invalidate() + } + ) + } + + override fun onLayout(shape: WatchShape, screenBounds: Rect, screenInsets: WindowInsets) { + super.onLayout(shape, screenBounds, screenInsets) + layoutView?.onApplyWindowInsets(screenInsets) + } + + private fun performViewSetup() { + mTime = layoutView?.findViewById(R.id.watch_time) + mSgv = layoutView?.findViewById(R.id.sgv) + mTimestamp = layoutView?.findViewById(R.id.timestamp) + mDelta = layoutView?.findViewById(R.id.delta) + mAvgDelta = layoutView?.findViewById(R.id.avgdelta) + mRelativeLayout = layoutView?.findViewById(R.id.main_layout) + chart = layoutView?.findViewById(R.id.chart) + statusView = layoutView?.findViewById(R.id.aps_status) + layoutSet = true + showAgeAndStatus() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + rxBus.send(EventWearToMobile(ActionResendData("BIGChart:performViewSetup"))) + wakeLock?.acquire(50) + } + + override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { + chart?.let { chart -> + mSgv?.let { mSgv -> + val extra = (mSgv.right - mSgv.left) / 2 + if (tapType == TAP_TYPE_TAP && x >= chart.left && x <= chart.right && y >= chart.top && y <= chart.bottom) { + if (eventTime - chartTapTime < 800) { + changeChartTimeframe() + } + chartTapTime = eventTime + } else 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 + } + } + } + } + + private 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 onWatchModeChanged(watchMode: WatchMode) { + if (lowResMode xor isLowRes(watchMode)) { //if there was a change in lowResMode + lowResMode = isLowRes(watchMode) + setColor() + } else if (!sp.getBoolean("dark", true)) { + //in bright mode: different colours if active: + setColor() + } + } + + private fun isLowRes(watchMode: WatchMode): Boolean { + return watchMode == WatchMode.LOW_BIT || watchMode == WatchMode.LOW_BIT_BURN_IN + } + + override fun getWatchFaceStyle(): WatchFaceStyle { + return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() + } + + private fun ageLevel(): Int { + return if (timeSince() <= 1000 * 60 * 12) { + 1 + } else { + 0 + } + } + + fun timeSince(): Double { + return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() + } + + private fun readingAge(): String { + if (singleBg.timeStamp == 0L) return "--'" + val minutesAgo = floor(timeSince() / (1000 * 60)).toInt() + return if (minutesAgo == 1) "$minutesAgo'" + else "$minutesAgo'" + } + + override fun onDestroy() { + disposable.clear() + super.onDestroy() + } + + override fun onDraw(canvas: Canvas) { + if (layoutSet) { + mRelativeLayout?.draw(canvas) + } + } + + override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { + if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { + wakeLock?.acquire(50) + mTime?.text = dateUtil.timeString() + showAgeAndStatus() + mSgv?.let { mSgv -> + if (ageLevel() <= 0) mSgv.paintFlags = mSgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + else mSgv.paintFlags = mSgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + missedReadingAlert() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + } + } + + private fun showAgeAndStatus() { + mTimestamp?.text = readingAge() + mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() + statusView?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() + statusView?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" + } + + private fun setColor() { + when { + lowResMode -> setColorLowRes() + sp.getBoolean("dark", true) -> setColorDark() + else -> setColorBright() + } + } + + private fun setColorLowRes() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + statusView?.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) + gridColour = 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() + } + } + + private fun setColorDark() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + statusView?.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) + gridColour = 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() + } + } + + private fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) + statusView?.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) + gridColour = 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 missedReadingAlert() { + val minutesSince = floor(timeSince() / (1000 * 60)).toInt() + if (minutesSince >= 16 && (minutesSince - 16) % 5 == 0) { + // attempt endTime recover missing data + rxBus.send(EventWearToMobile(ActionResendData("BIGChart:missedReadingAlert"))) + } + } + + private fun addToWatchSet() { + bgDataList = graphData.entries + } + + private fun setupCharts() { + if (bgDataList.size > 0) { + val timeframe = sp.getInt(R.string.key_chart_time_frame, 3) + val bgGraphBuilder = if (lowResMode) { + BgGraphBuilder( + sp, dateUtil, bgDataList, treatmentData.predictions, treatmentData.temps, treatmentData.basals, treatmentData.boluses, pointSize, + midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe + ) + } else { + BgGraphBuilder( + sp, dateUtil, bgDataList, treatmentData.predictions, treatmentData.temps, treatmentData.basals, treatmentData.boluses, pointSize, + highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe + ) + } + chart?.lineChartData = bgGraphBuilder.lineData() + chart?.isViewportCalculationEnabled = true + } else { + rxBus.send(EventWearToMobile(ActionResendData("BIGChart:setupCharts"))) + } + } + + companion object { + + private const val SCREEN_SIZE_SMALL = 280 + } +} \ 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 b9affede77..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java +++ /dev/null @@ -1,534 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -import android.content.Context; -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.Display; -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 java.util.ArrayList; -import java.util.Calendar; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; -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; - - -public class CircleWatchface extends WatchFace { - - @Inject RxBus rxBus; - @Inject AapsSchedulers aapsSchedulers; - @Inject AAPSLogger aapsLogger; - @Inject SP sp; - - CompositeDisposable disposable = new CompositeDisposable(); - - private EventData.SingleBg singleBg = new EventData.SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0); - private EventData.GraphData graphData; - private EventData.Status status = new EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1); - - 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 color; - private final Paint circlePaint = new Paint(); - private final Paint removePaint = new Paint(); - private RectF rect, rectDelete; - private boolean overlapping; - - public Point displaySize = new Point(); - - public ArrayList bgDataList = new ArrayList<>(); - - private int specW; - private int specH; - private View myLayout; - - private TextView mSgv; - private long sgvTapTime = 0; - - - @SuppressLint("InflateParams") @Override - public void onCreate() { - AndroidInjection.inject(this); - 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); - - //register Message Receiver - - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - myLayout = inflater.inflate(R.layout.activity_circle, null); - prepareLayout(); - prepareDrawTime(); - - disposable.add(rxBus - .toObservable(EventData.SingleBg.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> singleBg = event) - ); - disposable.add(rxBus - .toObservable(EventData.GraphData.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> graphData = event) - ); - disposable.add(rxBus - .toObservable(EventData.Status.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - // this event is received as last batch of data - aapsLogger.debug(LTag.WEAR, "Status received"); - status = event; - addToWatchSet(); - prepareLayout(); - prepareDrawTime(); - invalidate(); - }) - ); - disposable.add(rxBus - .toObservable(EventData.Preferences.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - prepareDrawTime(); - prepareLayout(); - invalidate(); - }) - ); - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("CircleWatchFace::onCreate"))); - - wakeLock.release(); - } - - - @Override - public void onDestroy() { - disposable.clear(); - super.onDestroy(); - } - - @Override - protected synchronized void onDraw(Canvas canvas) { - aapsLogger.debug(LTag.WEAR, "start onDraw"); - canvas.drawColor(getBackgroundColor()); - drawTime(canvas); - drawOtherStuff(canvas); - myLayout.draw(canvas); - - } - - private synchronized void prepareLayout() { - - aapsLogger.debug(LTag.WEAR, "start startPrepareLayout"); - - // prepare fields - - mSgv = myLayout.findViewById(R.id.sgvString); - if (sp.getBoolean("showBG", true)) { - mSgv.setVisibility(View.VISIBLE); - mSgv.setText(singleBg.getSgvString()); - mSgv.setTextColor(getTextColor()); - - } else { - //Also possible: View.INVISIBLE instead of View.GONE (no layout change) - mSgv.setVisibility(View.INVISIBLE); - } - - TextView textView = myLayout.findViewById(R.id.statusString); - if (sp.getBoolean("showExternalStatus", true)) { - textView.setVisibility(View.VISIBLE); - textView.setText(status.getExternalStatus()); - 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 (sp.getBoolean("showAgo", true)) { - textView.setVisibility(View.VISIBLE); - - if (sp.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 (sp.getBoolean("showDelta", true)) { - textView.setVisibility(View.VISIBLE); - textView.setText(singleBg.getDelta()); - textView.setTextColor(getTextColor()); - if (sp.getBoolean("showBigNumbers", false)) { - textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25); - } else { - textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); - } - if (sp.getBoolean("showAvgDelta", true)) { - textView.append(" " + singleBg.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 (singleBg.getTimeStamp() != 0) { - minutes = ((int) Math.floor((System.currentTimeMillis() - singleBg.getTimeStamp()) / 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() { - aapsLogger.debug(LTag.WEAR, "start prepareDrawTime"); - - int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) % 12; - int 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 ((int) singleBg.getSgvLevel()) { - case -1: - color = getLowColor(); - break; - case 0: - color = getInRangeColor(); - break; - case 1: - color = getHighColor(); - break; - } - - - 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); - aapsLogger.debug(LTag.WEAR, "end prepareDrawTime"); - - } - - 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 (sp.getBoolean("dark", true)) { - return Color.argb(255, 255, 120, 120); - } else { - return Color.argb(255, 255, 80, 80); - } - } - - public int getInRangeColor() { - if (sp.getBoolean("dark", true)) { - return Color.argb(255, 120, 255, 120); - } else { - return Color.argb(255, 0, 240, 0); - - } - } - - public int getHighColor() { - if (sp.getBoolean("dark", true)) { - return Color.argb(255, 255, 255, 120); - } else { - return Color.argb(255, 255, 200, 0); - } - - } - - public int getBackgroundColor() { - if (sp.getBoolean("dark", true)) { - return Color.BLACK; - } else { - return Color.WHITE; - - } - } - - public int getTextColor() { - if (sp.getBoolean("dark", true)) { - return Color.WHITE; - } else { - return Color.BLACK; - - } - } - - public void drawOtherStuff(Canvas canvas) { - aapsLogger.debug(LTag.WEAR, "start onDrawOtherStuff. bgDataList.size(): " + bgDataList.size()); - - if (sp.getBoolean("showRingHistory", false)) { - //Perfect low and High indicators - if (bgDataList.size() > 0) { - addIndicator(canvas, 100, Color.LTGRAY); - addIndicator(canvas, (float) bgDataList.iterator().next().getLow(), getLowColor()); - addIndicator(canvas, (float) bgDataList.iterator().next().getHigh(), getHighColor()); - - - if (sp.getBoolean("softRingHistory", true)) { - for (EventData.SingleBg data : bgDataList) { - addReadingSoft(canvas, data); - } - } else { - for (EventData.SingleBg data : bgDataList) { - addReading(canvas, data); - } - } - } - } - } - - public synchronized void addToWatchSet() { - - bgDataList.clear(); - if (!sp.getBoolean("showRingHistory", false)) return; - - double threshold = (System.currentTimeMillis() - (1000L * 60 * 30)); // 30 min - for (EventData.SingleBg entry : graphData.getEntries()) - if (entry.getTimeStamp() >= threshold) bgDataList.add(entry); - aapsLogger.debug(LTag.WEAR, "addToWatchSet size=" + bgDataList.size()); - } - - 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) { - - return (int) Math.max(color - (color * fraction), 0); - } - - - 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, EventData.SingleBg entry) { - - aapsLogger.debug(LTag.WEAR, "addReadingSoft"); - double size; - int color = Color.LTGRAY; - if (sp.getBoolean("dark", true)) { - color = Color.DKGRAY; - } - - float offsetMultiplier = (((displaySize.x / 2f) - PADDING) / 12f); - float offset = (float) Math.max(1, - Math.ceil((System.currentTimeMillis() - entry.getTimeStamp()) / (1000 * 60 * 5.0))); - size = bgToAngle((float) entry.getSgv()); - 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, EventData.SingleBg entry) { - aapsLogger.debug(LTag.WEAR, "addReading"); - - double size; - int color = Color.LTGRAY; - int indicatorColor = Color.DKGRAY; - if (sp.getBoolean("dark", true)) { - color = Color.DKGRAY; - indicatorColor = Color.LTGRAY; - } - int barColor = Color.GRAY; - if (entry.getSgv() >= entry.getHigh()) { - indicatorColor = getHighColor(); - barColor = darken(getHighColor(), .5); - } else if (entry.getSgv() <= entry.getLow()) { - indicatorColor = getLowColor(); - barColor = darken(getLowColor(), .5); - } - float offsetMultiplier = (((displaySize.x / 2f) - PADDING) / 12f); - float offset = (float) Math.max(1, - Math.ceil((System.currentTimeMillis() - entry.getTimeStamp()) / (1000 * 60 * 5.0))); - size = bgToAngle((float) entry.getSgv()); - 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); - } - - @SuppressWarnings("deprecation") - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - if (mSgv == null) return; - int extra = (mSgv.getRight() - mSgv.getLeft()) / 2; - - 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..6584b64d1f --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt @@ -0,0 +1,445 @@ +@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.events.EventWearToMobile +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +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 + + private var disposable = CompositeDisposable() + private var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) + private var graphData = EventData.GraphData(ArrayList()) + private var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) + + 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(SingleBg::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> singleBg = event } + disposable += rxBus + .toObservable(EventData.GraphData::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> graphData = event } + disposable += rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event -> + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received") + status = event + addToWatchSet() + prepareLayout() + prepareDrawTime() + invalidate() + } + disposable += rxBus + .toObservable(EventData.Preferences::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { + prepareDrawTime() + prepareLayout() + invalidate() + } + 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 5590b5ce70..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java +++ /dev/null @@ -1,122 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -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; - - @SuppressLint("InflateParams") @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; - } - } - - @SuppressWarnings("deprecation") - @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 (singleBg.getSgvLevel() == 1) { - mHighLight.setBackgroundResource(R.drawable.airplane_led_yellow_lit); - mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - } else if (singleBg.getSgvLevel() == 0) { - mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - } else if (singleBg.getSgvLevel() == -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 (status.getDetailedIob()) { - 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..db8b2e0c53 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt @@ -0,0 +1,105 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +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. + * Refactored by MilosKozak 24/04/2022 + */ +class CockpitWatchface : BaseWatchFace() { + + private var sgvTapTime: Long = 0 + + @SuppressLint("InflateParams") + override fun onCreate() { + super.onCreate() + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + layoutView = inflater.inflate(R.layout.activity_cockpit, null) + performViewSetup() + } + + override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { + if (tapType == TAP_TYPE_TAP) { + 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() + } + + 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 7ee43e93b1..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java +++ /dev/null @@ -1,173 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -import android.content.Intent; -import android.content.res.ColorStateList; -import android.support.wearable.watchface.WatchFaceStyle; -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; -import info.nightscout.shared.logging.LTag; - -public class DigitalStyle extends BaseWatchFace { - private static final long TIME_TAP_THRESHOLD = 800; - private long sgvTapTime = 0; - - @SuppressLint("InflateParams") @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; - aapsLogger.debug(LTag.WEAR,"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; - } - } - - - @SuppressWarnings("deprecation") - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this) - .setAcceptsTapEvents(true) - .setHideNotificationIndicator(false) - .setShowUnreadCountIndicator(true) - .build(); - } - - protected void setColorDark() { - if (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); - } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); - } else if (singleBg.getSgvLevel() == -1) { - 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.getBatteryLevel() == 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(); - } - } - - 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=sp.getString("digitalstyle_frameStyle", "full"); - String displayFrameColor=sp.getString("digitalstyle_frameColor", "red"); - String displayFrameColorSaturation=sp.getString("digitalstyle_frameColorSaturation", - "500"); - String displayFrameColorOpacity=sp.getString("digitalstyle_frameColorOpacity", "1"); - - // Load image with shapes - String styleDrawableName = "digitalstyle_bg_" + displayStyle + "_" + displayFormatType; - try { - mShapesElements.setBackground(getResources().getDrawable(getResources().getIdentifier(styleDrawableName, "drawable", this.getPackageName()))); - } catch (Exception e) { - aapsLogger.error("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); - aapsLogger.debug(LTag.WEAR,"digitalstyle_strColorName",strColorName); - try { - ColorStateList colorStateList = ContextCompat.getColorStateList(this, getResources().getIdentifier(strColorName, "color", this.getPackageName())); - mShapesElements.setBackgroundTintList(colorStateList); - } catch (Exception e) { - mShapesElements.setBackgroundTintList(null); - aapsLogger.error("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 = sp.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 = sp.getBoolean("show_weeknumber", false); - aapsLogger.info(LTag.WEAR,"---------------------------------","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..dd017cd267 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt @@ -0,0 +1,162 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +import android.support.wearable.watchface.WatchFaceStyle +import android.view.LayoutInflater +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.core.content.ContextCompat +import info.nightscout.androidaps.R +import info.nightscout.androidaps.extensions.toVisibility +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +import info.nightscout.shared.logging.LTag + +class DigitalStyleWatchface : BaseWatchFace() { + + private var sgvTapTime: Long = 0 + + @SuppressLint("InflateParams") + override fun onCreate() { + super.onCreate() + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + layoutView = inflater.inflate(R.layout.activity_digitalstyle, null) + performViewSetup() + } + + override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { + //tapType = TAP_TYPE_TAP; + aapsLogger.debug(LTag.WEAR, "onTapCommand: DeviceWidth x DeviceHeight /// x , y, TapType >> ", "$width x $height /// $x , $y , $tapType") + if (tapType == TAP_TYPE_TAP) { + if (eventTime - sgvTapTime < TIME_TAP_THRESHOLD) { + 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) + .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 */ + } + + companion object { + + private const val TIME_TAP_THRESHOLD: Long = 800 + } +} \ 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 a16dbd7af0..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java +++ /dev/null @@ -1,185 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -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; - - @SuppressLint("InflateParams") @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 = sp.getInt("chart_timeframe", 3); - timeframe = (timeframe%5) + 1; - sp.putString("chart_timeframe", "" + timeframe); - } - - @SuppressWarnings("deprecation") - @Override - protected WatchFaceStyle getWatchFaceStyle(){ - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - - protected void setColorDark() { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.dark_background : R.color.dark_statusView)); - mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); - if (singleBg.getSgvLevel() == 1) { - 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)); - } else if (singleBg.getSgvLevel() == 0) { - 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)); - } else if (singleBg.getSgvLevel() == -1) { - 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, dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_mTimestamp1_home)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); - } - - if (status.getBatteryLevel() == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_uploaderBattery)); - } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)); - } - - mStatus.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.dark_midColor : 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(); - } - } - - protected void 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(); - } - - } - - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.light_background : R.color.light_stripe_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); - if (singleBg.getSgvLevel() == 1) { - 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)); - } else if (singleBg.getSgvLevel() == 0) { - 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)); - } else if (singleBg.getSgvLevel() == -1) { - 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(dividerMatchesBg ? Color.BLACK : Color.WHITE); - } else { - mTimestamp.setTextColor(Color.RED); - } - - if (status.getBatteryLevel() == 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(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(); - } - } -} 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 bc465070f6..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java +++ /dev/null @@ -1,270 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -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; - - @SuppressLint("InflateParams") @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 = sp.getInt("chart_timeframe", 3); - timeframe = (timeframe % 5) + 1; - sp.putString("chart_timeframe", "" + timeframe); - } - - @SuppressWarnings("deprecation") - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - protected void setColorDark() { - @ColorInt final int dividerTxtColor = dividerMatchesBg ? - ContextCompat.getColor(this, R.color.dark_midColor) : Color.BLACK; - @ColorInt final int dividerBatteryOkColor = ContextCompat.getColor(this, - dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery); - @ColorInt final int dividerBgColor = ContextCompat.getColor(this, - dividerMatchesBg ? R.color.dark_background : 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(); - - if (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)); - } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)); - } else if (singleBg.getSgvLevel() == -1) { - 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.getBatteryLevel() == 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); - - 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(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(); - } - } - - protected void setColorLowRes() { - @ColorInt final int dividerTxtColor = dividerMatchesBg ? - ContextCompat.getColor(this, R.color.dark_midColor) : Color.BLACK; - @ColorInt final int dividerBgColor = ContextCompat.getColor(this, - dividerMatchesBg ? R.color.dark_background : 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(); - } - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - - @ColorInt final int dividerTxtColor = dividerMatchesBg ? Color.BLACK : - ContextCompat.getColor(this, R.color.dark_midColor); - @ColorInt final int dividerBgColor = ContextCompat.getColor(this, - dividerMatchesBg ? R.color.light_background : 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(); - - if (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)); - mDirection.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)); - } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)); - mDirection.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)); - } else if (singleBg.getSgvLevel() == -1) { - 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.getBatteryLevel() == 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(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(); - } - } - - protected void setTextSizes() { - - if (mIOB1 != null && mIOB2 != null) { - - if (status.getDetailedIob()) { - 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 a176f393f3..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java +++ /dev/null @@ -1,158 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -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; - - @SuppressLint("InflateParams") @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) { - if (mSgv == null) return; - int extra = (mSgv.getRight() - mSgv.getLeft())/2; - - 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; - } - } - - @SuppressWarnings("deprecation") - @Override - protected WatchFaceStyle getWatchFaceStyle(){ - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - @Override - protected void setColorDark(){ - mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.dark_background : R.color.dark_mLinearLayout)); - mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); - if (singleBg.getSgvLevel() == 1) { - 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)); - } else if (singleBg.getSgvLevel() == 0) { - 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)); - } else if (singleBg.getSgvLevel() == -1) { - 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, dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_mTimestamp1_home)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)); - } - - if (status.getBatteryLevel() == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_uploaderBattery)); - } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)); - } - - mStatus.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mStatus_home)); - } - - @Override - protected void setColorBright() { - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(this, dividerMatchesBg ? - R.color.light_background : R.color.light_stripe_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); - if (singleBg.getSgvLevel() == 1) { - 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)); - } else if (singleBg.getSgvLevel() == 0) { - 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)); - } else if (singleBg.getSgvLevel() == -1) { - 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(dividerMatchesBg ? Color.BLACK : Color.WHITE); - } else { - mTimestamp.setTextColor(Color.RED); - } - - if (status.getBatteryLevel() == 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 (singleBg.getSgvLevel() == 1) { - mSgv.setTextColor(Color.YELLOW); - mDirection.setTextColor(Color.YELLOW); - mDelta.setTextColor(Color.YELLOW); - } else if (singleBg.getSgvLevel() == 0) { - mSgv.setTextColor(Color.WHITE); - mDirection.setTextColor(Color.WHITE); - mDelta.setTextColor(Color.WHITE); - } else if (singleBg.getSgvLevel() == -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(this, dividerMatchesBg ? R.color.dark_background : 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, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mTimestamp1_home)); - mUploaderBattery.setTextColor(ContextCompat.getColor(this, dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); - mStatus.setTextColor(ContextCompat.getColor(this, 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 f8cc8ab9f2..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java +++ /dev/null @@ -1,368 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.Intent; -import android.graphics.Canvas; -import android.graphics.Paint; -import android.graphics.Point; -import android.graphics.Rect; -import android.os.PowerManager; -import android.support.wearable.view.WatchViewStub; -import android.support.wearable.watchface.WatchFaceStyle; -import android.text.format.DateFormat; -import android.util.DisplayMetrics; -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 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 javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventWearToMobile; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; -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; - -/** - * Created by adrianLxM. - */ -public class NOChart extends WatchFace { - - @Inject RxBus rxBus; - @Inject AapsSchedulers aapsSchedulers; - @Inject AAPSLogger aapsLogger; - @Inject SP sp; - - CompositeDisposable disposable = new CompositeDisposable(); - - private EventData.SingleBg singleBg; - private EventData.Status status; - - public static final int SCREENSIZE_SMALL = 280; - public TextView mTime, mSgv, mTimestamp, mDelta, mAvgDelta; - public RelativeLayout mRelativeLayout; - public long sgvLevel = 0; - public int ageLevel = 1; - public boolean lowResMode = false; - public boolean layoutSet = false; - public PowerManager.WakeLock wakeLock; - public View layoutView; - private final Point displaySize = new Point(); - private int specW, specH; - - private TextView statusView; - private long sgvTapTime = 0L; - - @SuppressLint("InflateParams") @Override - public void onCreate() { - AndroidInjection.inject(this); - 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); - 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_nochart_small, null); - } else { - layoutView = inflater.inflate(R.layout.activity_nochart, null); - } - disposable.add(rxBus - .toObservable(EventData.SingleBg.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - aapsLogger.debug(LTag.WEAR, "SingleBg received"); - singleBg = event; - - mSgv.setText(singleBg.getSgvString()); - 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(this); - mTime.setText(timeFormat.format(System.currentTimeMillis())); - mDelta.setText(singleBg.getDelta()); - mAvgDelta.setText(singleBg.getAvgDelta()); - }) - ); - disposable.add(rxBus - .toObservable(EventData.Status.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - // this event is received as last batch of data - aapsLogger.debug(LTag.WEAR, "Status received"); - status = event; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - }) - ); - disposable.add(rxBus - .toObservable(EventData.Preferences.class) - .observeOn(aapsSchedulers.getMain()) - .subscribe(event -> { - setColor(); - if (layoutSet) { - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - invalidate(); - }) - ); - performViewSetup(); - } - - @Override - protected void onLayout(WatchShape shape, Rect screenBounds, WindowInsets screenInsets) { - super.onLayout(shape, screenBounds, screenInsets); - layoutView.onApplyWindowInsets(screenInsets); - } - - public void performViewSetup() { - mTime = layoutView.findViewById(R.id.watch_time); - mSgv = layoutView.findViewById(R.id.sgv); - mTimestamp = layoutView.findViewById(R.id.timestamp); - mDelta = layoutView.findViewById(R.id.delta); - mAvgDelta = layoutView.findViewById(R.id.avgdelta); - mRelativeLayout = layoutView.findViewById(R.id.main_layout); - statusView = layoutView.findViewById(R.id.aps_status); - layoutSet = true; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), mRelativeLayout.getMeasuredHeight()); - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("NOChart:performViewSetup"))); - wakeLock.acquire(50); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - if (mSgv == null) return; - int extra = (mSgv.getRight() - mSgv.getLeft()) / 2; - - 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 (!sp.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); - } - - - @SuppressWarnings("deprecation") - @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() - singleBg.getTimeStamp(); - } - - public String readingAge(boolean shortString) { - if (singleBg == null || singleBg.getTimeStamp() == 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() { - disposable.clear(); - super.onDestroy(); - } - - @Override - protected void onDraw(Canvas canvas) { - if (layoutSet) { - this.mRelativeLayout.draw(canvas); - } - } - - @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()); - } - } - - private void showAgeAndStatus() { - - if (mTimestamp != null) { - mTimestamp.setText(readingAge(true)); - } - boolean showAvgDelta = sp.getBoolean("showAvgDelta", true); - - if (showAvgDelta) { - mAvgDelta.setVisibility(View.VISIBLE); - } else { - mAvgDelta.setVisibility(View.GONE); - } - if (status != null) { - statusView.setText(status.getExternalStatus()); - statusView.setVisibility(View.VISIBLE); - } - } - - public void setColor() { - if (lowResMode) { - setColorLowRes(); - } else if (sp.getBoolean("dark", true)) { - setColorDark(); - } else { - setColorBright(); - } - - } - - protected void setColorLowRes() { - mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); - statusView.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)); - } - - protected void setColorDark() { - mTime.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)); - statusView.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)); - if (sgvLevel == 1) { - 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)); - } else if (sgvLevel == 0) { - 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)); - } else if (sgvLevel == -1) { - 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)); - } - } - - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mTime.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)); - statusView.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)); - if (sgvLevel == 1) { - 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)); - } else if (sgvLevel == 0) { - 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)); - } else if (sgvLevel == -1) { - 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(); - } - } - - public void missedReadingAlert() { - int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); - if (minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - // attempt endTime recover missing data - rxBus.send(new EventWearToMobile(new EventData.ActionResendData("NOChart" + - ":missedReadingAlert"))); - } - } -} 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..b05fad60c5 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt @@ -0,0 +1,324 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +import android.graphics.Canvas +import android.graphics.Paint +import android.graphics.Point +import android.graphics.Rect +import android.os.PowerManager +import android.support.wearable.watchface.WatchFaceStyle +import android.text.format.DateFormat +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 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.events.EventWearToMobile +import info.nightscout.androidaps.extensions.toVisibility +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +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 io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import javax.inject.Inject +import kotlin.math.floor + +class NoChartWatchface : WatchFace() { + + @Inject lateinit var rxBus: RxBus + @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var sp: SP + @Inject lateinit var dateUtil: DateUtil + + private var disposable = CompositeDisposable() + + private var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) + private var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) + + private var mTime: TextView? = null + private var mSgv: TextView? = null + private var mTimestamp: TextView? = null + private var mDelta: TextView? = null + private var mAvgDelta: TextView? = null + private var mRelativeLayout: RelativeLayout? = null + private var sgvLevel: Long = 0 + private var ageLevel = 1 + private var lowResMode = false + private var layoutSet = false + private var wakeLock: PowerManager.WakeLock? = null + private var layoutView: View? = null + private val displaySize = Point() + private var specW = 0 + private var specH = 0 + private var statusView: TextView? = null + private var sgvTapTime = 0L + + @SuppressLint("InflateParams") + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + val display = (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay + display.getSize(displaySize) + wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).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) + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + val metrics = resources.displayMetrics + layoutView = if (metrics.widthPixels < SCREEN_SIZE_SMALL || metrics.heightPixels < SCREEN_SIZE_SMALL) { + inflater.inflate(R.layout.activity_nochart_small, null) + } else { + inflater.inflate(R.layout.activity_nochart, null) + } + disposable += rxBus + .toObservable(SingleBg::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: SingleBg -> + aapsLogger.debug(LTag.WEAR, "SingleBg received") + singleBg = event + mSgv?.let { sgv -> + sgv.text = singleBg.sgvString + if (ageLevel() <= 0) sgv.paintFlags = sgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + else sgv.paintFlags = sgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + mTime?.text = dateUtil.timeString() + mDelta?.text = singleBg.delta + mAvgDelta?.text = singleBg.avgDelta + } + disposable += rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: EventData.Status -> + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received") + status = event + showAgeAndStatus() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + invalidate() + setColor() + } + disposable += rxBus + .toObservable(EventData.Preferences::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { + setColor() + if (layoutSet) { + showAgeAndStatus() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + } + invalidate() + } + performViewSetup() + } + + override fun onLayout(shape: WatchShape, screenBounds: Rect, screenInsets: WindowInsets) { + super.onLayout(shape, screenBounds, screenInsets) + layoutView?.onApplyWindowInsets(screenInsets) + } + + private fun performViewSetup() { + mTime = layoutView?.findViewById(R.id.watch_time) + mSgv = layoutView?.findViewById(R.id.sgv) + mTimestamp = layoutView?.findViewById(R.id.timestamp) + mDelta = layoutView?.findViewById(R.id.delta) + mAvgDelta = layoutView?.findViewById(R.id.avgdelta) + mRelativeLayout = layoutView?.findViewById(R.id.main_layout) + statusView = layoutView?.findViewById(R.id.aps_status) + layoutSet = true + showAgeAndStatus() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + rxBus.send(EventWearToMobile(ActionResendData("NOChart:performViewSetup"))) + } + + 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) { + startActivity(Intent(this, MainMenuActivity::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + } + sgvTapTime = eventTime + } + } + } + + override fun onWatchModeChanged(watchMode: WatchMode) { + if (lowResMode xor isLowRes(watchMode)) { //if there was a change in lowResMode + lowResMode = isLowRes(watchMode) + setColor() + } else if (!sp.getBoolean("dark", true)) { + //in bright mode: different colours if active: + setColor() + } + } + + private fun isLowRes(watchMode: WatchMode): Boolean { + return watchMode == WatchMode.LOW_BIT || watchMode == WatchMode.LOW_BIT_BURN_IN + } + + override fun getWatchFaceStyle(): WatchFaceStyle { + return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() + } + + private fun ageLevel(): Int = if (timeSince() <= 1000 * 60 * 12) 1 else 0 + + fun timeSince(): Double = (System.currentTimeMillis() - singleBg.timeStamp).toDouble() + + private fun readingAge(): String { + if (singleBg.timeStamp == 0L) return "--'" + val minutesAgo = floor(timeSince() / (1000 * 60)).toInt() + return if (minutesAgo == 1) "$minutesAgo'" + else "$minutesAgo'" + } + + override fun onDestroy() { + disposable.clear() + super.onDestroy() + } + + override fun onDraw(canvas: Canvas) { + if (layoutSet) { + mRelativeLayout?.draw(canvas) + } + } + + override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { + if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { + mTime?.text = dateUtil.timeString() + showAgeAndStatus() + mSgv?.let { sgv -> + if (ageLevel() <= 0) { + sgv.paintFlags = sgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + } else { + sgv.paintFlags = sgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + } + missedReadingAlert() + mRelativeLayout?.measure(specW, specH) + mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) + } + } + + private fun showAgeAndStatus() { + mTimestamp?.text = readingAge() + mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_avg_delta, true).toVisibility() + statusView?.text = status.externalStatus + statusView?.visibility = View.VISIBLE + } + + private fun setColor() { + when { + lowResMode -> setColorLowRes() + sp.getBoolean("dark", true) -> setColorDark() + else -> setColorBright() + } + } + + private fun setColorLowRes() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + statusView?.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)) + } + + private fun setColorDark() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + statusView?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + when (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)) + } + } + + private fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) + statusView?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + when (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() + } + } + + private fun missedReadingAlert() { + val minutesSince = floor(timeSince() / (1000 * 60)).toInt() + if (minutesSince >= 16 && (minutesSince - 16) % 5 == 0) { + // attempt endTime recover missing data + rxBus.send(EventWearToMobile(ActionResendData("NOChart::missedReadingAlert"))) + } + } + + companion object { + + const val SCREEN_SIZE_SMALL = 280 + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt index 924032b773..776c4a8c6a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -13,6 +13,7 @@ import androidx.core.content.ContextCompat import info.nightscout.androidaps.R import info.nightscout.androidaps.interaction.menus.MainMenuActivity import info.nightscout.shared.SafeParse.stringToFloat +import org.joda.time.TimeOfDay /** * Created by andrew-warrington on 01/12/2017. @@ -35,16 +36,23 @@ class SteampunkWatchface : BaseWatchFace() { } override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { - if (tapType == TAP_TYPE_TAP && x >= mChartTap.left && x <= mChartTap.right && y >= mChartTap.top && y <= mChartTap.bottom) { - if (eventTime - chartTapTime < 800) { - changeChartTimeframe() + 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 } - chartTapTime = eventTime - } else 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) }) + } + 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 } - mainMenuTapTime = eventTime } } @@ -53,14 +61,12 @@ class SteampunkWatchface : BaseWatchFace() { } override fun setColorDark() { - if (mLinearLayout2 != null) { - 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)) - } + 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)) } if (loopLevel == 0) { mLoop?.setTextColor(ContextCompat.getColor(this, R.color.red_600)) @@ -73,9 +79,9 @@ class SteampunkWatchface : BaseWatchFace() { //ensure the glucose dial is the correct units if (singleBg.glucoseUnits == "mmol") { - mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mmol) + mGlucoseDial?.setImageResource(R.drawable.steampunk_dial_mmol) } else { - mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mgdl) + mGlucoseDial?.setImageResource(R.drawable.steampunk_dial_mgdl) } //convert the Sgv to degrees of rotation @@ -99,7 +105,7 @@ class SteampunkWatchface : BaseWatchFace() { rotate.fillAfter = true rotate.interpolator = LinearInterpolator() rotate.duration = 1 - mGlucoseDial.startAnimation(rotate) + mGlucoseDial?.startAnimation(rotate) lastEndDegrees = rotationAngle //store the final angle as a starting point for the next rotation. } @@ -123,15 +129,15 @@ class SteampunkWatchface : BaseWatchFace() { } } if (sp.getString("delta_granularity", "2") == "1" || autoGranularity == "1") { //low - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_10) + 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) + 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) + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mmol_03) deltaRotationAngle = absAvgDelta * 100f } } else { @@ -144,28 +150,28 @@ class SteampunkWatchface : BaseWatchFace() { } } if (sp.getString("delta_granularity", "2") == "1" || autoGranularity == "1") { //low - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_20) + 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) + 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) + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_5) deltaRotationAngle = absAvgDelta * 6f } } } if (deltaRotationAngle > 40) deltaRotationAngle = 40f - mDeltaGauge.rotation = deltaRotationAngle * deltaIsNegative + mDeltaGauge?.rotation = deltaRotationAngle * deltaIsNegative } //rotate the minute hand. - mMinuteHand.rotation = sMinute.toFloat() * 6f + mMinuteHand?.rotation = TimeOfDay().minuteOfHour * 6f //rotate the hour hand. - mHourHand.rotation = sHour.toFloat() * 30f + sMinute.toFloat() * 0.5f + mHourHand?.rotation = TimeOfDay().hourOfDay * 30f + TimeOfDay().minuteOfHour * 0.5f setTextSizes() mLoop?.setBackgroundResource(0) if (chart != null) { @@ -175,7 +181,7 @@ class SteampunkWatchface : BaseWatchFace() { 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("chart_timeframe", 3) < 3) { + pointSize = if (sp.getInt(R.string.key_chart_time_frame, 3) < 3) { 2 } else { 1 @@ -204,38 +210,39 @@ class SteampunkWatchface : BaseWatchFace() { } //top row. large font unless text too big (i.e. detailedIOB) - mCOB2.textSize = fontLarge - mBasalRate.textSize = fontLarge + mCOB2?.textSize = fontLarge + mBasalRate?.textSize = fontLarge if (status.iobDetail.length < 7) { - mIOB2.textSize = fontLarge + mIOB2?.textSize = fontLarge } else { - mIOB2.textSize = fontSmall + mIOB2?.textSize = fontSmall } //bottom row. font medium unless text too long (i.e. longer than 9' timestamp) - 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 + 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 + 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 + mUploaderBattery?.textSize = fontMedium + mRigBattery?.textSize = fontMedium } } private fun changeChartTimeframe() { - var timeframe = sp.getInt("chart_timeframe", 3) + var timeframe = sp.getInt(R.string.key_chart_time_frame, 3) timeframe = timeframe % 5 + 1 pointSize = if (timeframe < 3) { 2 @@ -243,6 +250,6 @@ class SteampunkWatchface : BaseWatchFace() { 1 } setupCharts() - sp.putString("chart_timeframe", "" + timeframe) + sp.putInt(R.string.key_chart_time_frame, timeframe) } } \ No newline at end of file diff --git a/wear/src/main/res/layout-notround/activity_bigchart.xml b/wear/src/main/res/layout-notround/activity_bigchart.xml index 10540e5247..8b8ed78e10 100644 --- a/wear/src/main/res/layout-notround/activity_bigchart.xml +++ b/wear/src/main/res/layout-notround/activity_bigchart.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-notround/activity_bigchart_small.xml b/wear/src/main/res/layout-notround/activity_bigchart_small.xml index 099760767a..8aed526c0d 100644 --- a/wear/src/main/res/layout-notround/activity_bigchart_small.xml +++ b/wear/src/main/res/layout-notround/activity_bigchart_small.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-notround/activity_cockpit.xml b/wear/src/main/res/layout-notround/activity_cockpit.xml index ca09d8be69..75290deb00 100644 --- a/wear/src/main/res/layout-notround/activity_cockpit.xml +++ b/wear/src/main/res/layout-notround/activity_cockpit.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-notround/activity_digitalstyle.xml b/wear/src/main/res/layout-notround/activity_digitalstyle.xml index b7304d1836..7f9fbb28c1 100644 --- a/wear/src/main/res/layout-notround/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"> @@ -425,21 +425,10 @@ android:textSize="26sp" android:textStyle="bold" /> - - +
+
diff --git a/wear/src/main/res/layout-notround/activity_home.xml b/wear/src/main/res/layout-notround/activity_home.xml index c619efbb37..dd700fcf5c 100644 --- a/wear/src/main/res/layout-notround/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-notround/activity_home_2.xml b/wear/src/main/res/layout-notround/activity_home_2.xml index 6f8e811f22..60ae6c3cf6 100644 --- a/wear/src/main/res/layout-notround/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-notround/activity_nochart.xml b/wear/src/main/res/layout-notround/activity_nochart.xml index 179b05d021..cb186665a2 100644 --- a/wear/src/main/res/layout-notround/activity_nochart.xml +++ b/wear/src/main/res/layout-notround/activity_nochart.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-notround/activity_nochart_small.xml b/wear/src/main/res/layout-notround/activity_nochart_small.xml index 7d57161c31..48bba6a6ea 100644 --- a/wear/src/main/res/layout-notround/activity_nochart_small.xml +++ b/wear/src/main/res/layout-notround/activity_nochart_small.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-round/activity_bigchart.xml b/wear/src/main/res/layout-round/activity_bigchart.xml index 10540e5247..8b8ed78e10 100644 --- a/wear/src/main/res/layout-round/activity_bigchart.xml +++ b/wear/src/main/res/layout-round/activity_bigchart.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-round/activity_bigchart_small.xml b/wear/src/main/res/layout-round/activity_bigchart_small.xml index 099760767a..8aed526c0d 100644 --- a/wear/src/main/res/layout-round/activity_bigchart_small.xml +++ b/wear/src/main/res/layout-round/activity_bigchart_small.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-round/activity_cockpit.xml b/wear/src/main/res/layout-round/activity_cockpit.xml index 44a91fe29c..8486b4d211 100644 --- a/wear/src/main/res/layout-round/activity_cockpit.xml +++ b/wear/src/main/res/layout-round/activity_cockpit.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-round/activity_digitalstyle.xml b/wear/src/main/res/layout-round/activity_digitalstyle.xml index 20aeeef3fc..988fa7f031 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"> @@ -425,21 +425,10 @@ android:textSize="26sp" android:textStyle="bold" /> - - + + diff --git a/wear/src/main/res/layout-round/activity_home.xml b/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 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-round/activity_nochart.xml b/wear/src/main/res/layout-round/activity_nochart.xml index 179b05d021..cb186665a2 100644 --- a/wear/src/main/res/layout-round/activity_nochart.xml +++ b/wear/src/main/res/layout-round/activity_nochart.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout-round/activity_nochart_small.xml b/wear/src/main/res/layout-round/activity_nochart_small.xml index 7d57161c31..48bba6a6ea 100644 --- a/wear/src/main/res/layout-round/activity_nochart_small.xml +++ b/wear/src/main/res/layout-round/activity_nochart_small.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 9f4e614874..2b019792f2 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) @@ -196,5 +196,16 @@ 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/xml/preferences.xml b/wear/src/main/res/xml/preferences.xml index a5f639c979..a719b98f78 100644 --- a/wear/src/main/res/xml/preferences.xml +++ b/wear/src/main/res/xml/preferences.xml @@ -12,7 +12,7 @@ @@ -97,7 +97,7 @@ android:defaultValue="3" android:entries="@array/chart_timeframe" android:entryValues="@array/chart_timeframe_values" - android:key="chart_timeframe" + android:key="@string/key_chart_time_frame" android:summary="Chart Timeframe" android:title="@string/pref_chart_timeframe" /> diff --git a/wear/src/main/res/xml/watch_face_configuration_circle.xml b/wear/src/main/res/xml/watch_face_configuration_circle.xml index 1943d72b0f..556068b915 100644 --- a/wear/src/main/res/xml/watch_face_configuration_circle.xml +++ b/wear/src/main/res/xml/watch_face_configuration_circle.xml @@ -12,7 +12,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 @@ From b210bea490b5c625b16b85ea6016b726f6efdbe1 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 17:31:30 +0200 Subject: [PATCH 25/54] VersionPreference -> kt --- .../interaction/utils/VersionPreference.java | 30 ------------------- .../interaction/utils/VersionPreference.kt | 26 ++++++++++++++++ 2 files changed, 26 insertions(+), 30 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt 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..9f5ce4968c --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt @@ -0,0 +1,26 @@ +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. + */ +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 From 09433d6a4f6a8066a3179db01579610be7e3e872 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 17:40:16 +0200 Subject: [PATCH 26/54] WatchfaceSettingsPreference -> kt --- .../interaction/utils/VersionPreference.kt | 1 + .../utils/WatchfaceSettingsPreference.java | 33 ------------------- .../utils/WatchfaceSettingsPreference.kt | 25 ++++++++++++++ wear/src/main/res/values/strings.xml | 2 +- 4 files changed, 27 insertions(+), 34 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.kt 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 index 9f5ce4968c..d63d7ca252 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt @@ -9,6 +9,7 @@ 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 { 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/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 2b019792f2..bc56b0bb46 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -70,7 +70,7 @@ Complication Tap Action Unicode in Complications Version: - more Watchface settings + More Watchface settings Look into Watchface configuration, please. TempT From 9b064404ac0a31e1fe67759866136ce0f9c2c081 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 17:46:07 +0200 Subject: [PATCH 27/54] lints --- .../androidaps/watchfaces/BigChartWatchface.kt | 12 ++++-------- .../androidaps/watchfaces/NoChartWatchface.kt | 10 ++++------ 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt index 91872facc9..a88f46c6fe 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt @@ -11,7 +11,6 @@ import android.graphics.Point import android.graphics.Rect import android.os.PowerManager import android.support.wearable.watchface.WatchFaceStyle -import android.text.format.DateFormat import android.view.LayoutInflater import android.view.View import android.view.WindowInsets @@ -239,12 +238,9 @@ class BigChartWatchface : WatchFace() { return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() } - private fun readingAge(): String { - if (singleBg.timeStamp == 0L) return "--'" - val minutesAgo = floor(timeSince() / (1000 * 60)).toInt() - return if (minutesAgo == 1) "$minutesAgo'" - else "$minutesAgo'" - } + private fun readingAge(): String = + if (singleBg.timeStamp == 0L) "--'" + else "${floor(timeSince() / (1000 * 60)).toInt()}'" override fun onDestroy() { disposable.clear() @@ -276,7 +272,7 @@ class BigChartWatchface : WatchFace() { mTimestamp?.text = readingAge() mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() statusView?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() - statusView?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" + statusView?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" } private fun setColor() { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt index b05fad60c5..52f8106741 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt @@ -185,12 +185,10 @@ class NoChartWatchface : WatchFace() { fun timeSince(): Double = (System.currentTimeMillis() - singleBg.timeStamp).toDouble() - private fun readingAge(): String { - if (singleBg.timeStamp == 0L) return "--'" - val minutesAgo = floor(timeSince() / (1000 * 60)).toInt() - return if (minutesAgo == 1) "$minutesAgo'" - else "$minutesAgo'" - } + private fun readingAge(): String = + if (singleBg.timeStamp == 0L) "--'" + else "${floor(timeSince() / (1000 * 60)).toInt()}'" + override fun onDestroy() { disposable.clear() From 9c17c075f4ea0571b6733a1bdf803656f61ed543 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 19:38:16 +0200 Subject: [PATCH 28/54] Wear: Watchfaces unify onCreate, onTapCommand --- .../watchfaces/AapsLargeWatchface.kt | 37 +-------- .../androidaps/watchfaces/AapsV2Watchface.kt | 51 +----------- .../androidaps/watchfaces/AapsWatchface.kt | 51 +----------- .../androidaps/watchfaces/BaseWatchFace.kt | 80 ++++++++++++++++--- .../androidaps/watchfaces/CockpitWatchface.kt | 46 ++--------- .../watchfaces/DigitalStyleWatchface.kt | 26 +----- .../androidaps/watchfaces/NoChartWatchface.kt | 1 - .../watchfaces/SteampunkWatchface.kt | 49 +----------- .../layout-notround/activity_digitalstyle.xml | 2 + .../layout-round/activity_digitalstyle.xml | 2 + 10 files changed, 92 insertions(+), 253 deletions(-) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt index 71bf90aa78..84104d0c85 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt @@ -1,46 +1,13 @@ -@file:Suppress("DEPRECATION") - package info.nightscout.androidaps.watchfaces -import android.annotation.SuppressLint -import android.content.Intent import android.graphics.Color -import android.support.wearable.watchface.WatchFaceStyle -import android.view.LayoutInflater import androidx.core.content.ContextCompat import com.ustwo.clockwise.common.WatchMode import info.nightscout.androidaps.R -import info.nightscout.androidaps.interaction.menus.MainMenuActivity class AapsLargeWatchface : BaseWatchFace() { - private var sgvTapTime: Long = 0 - - @SuppressLint("InflateParams") - override fun onCreate() { - super.onCreate() - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - layoutView = inflater.inflate(R.layout.activity_home_large, null) - performViewSetup() - } - - 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() - } + 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)) @@ -70,7 +37,7 @@ class AapsLargeWatchface : BaseWatchFace() { 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)) } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt index 438009813c..5432e3d650 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt @@ -1,63 +1,14 @@ -@file:Suppress("DEPRECATION") - package info.nightscout.androidaps.watchfaces -import android.annotation.SuppressLint -import android.content.Intent import android.graphics.Color -import android.support.wearable.watchface.WatchFaceStyle -import android.view.LayoutInflater import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import com.ustwo.clockwise.common.WatchMode import info.nightscout.androidaps.R -import info.nightscout.androidaps.interaction.menus.MainMenuActivity class AapsV2Watchface : BaseWatchFace() { - private var chartTapTime: Long = 0 - private var sgvTapTime: Long = 0 - - @SuppressLint("InflateParams") - override fun onCreate() { - super.onCreate() - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - layoutView = inflater.inflate(R.layout.activity_home_2, null) - performViewSetup() - } - - 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) { - val intent = Intent(this, MainMenuActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - startActivity(intent) - } - sgvTapTime = eventTime - } - } - } - - private 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() - } + 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 diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt index 42d16e0763..a2ada7a19d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt @@ -1,62 +1,13 @@ -@file:Suppress("DEPRECATION") - package info.nightscout.androidaps.watchfaces -import android.annotation.SuppressLint -import android.content.Intent import android.graphics.Color -import android.support.wearable.watchface.WatchFaceStyle -import android.view.LayoutInflater import androidx.core.content.ContextCompat import com.ustwo.clockwise.common.WatchMode import info.nightscout.androidaps.R -import info.nightscout.androidaps.interaction.menus.MainMenuActivity class AapsWatchface : BaseWatchFace() { - private var chartTapTime: Long = 0 - private var sgvTapTime: Long = 0 - - @SuppressLint("InflateParams") - override fun onCreate() { - super.onCreate() - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - layoutView = inflater.inflate(R.layout.activity_home, null) - performViewSetup() - } - - 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) { - val intent = Intent(this, MainMenuActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - startActivity(intent) - } - sgvTapTime = eventTime - } - } - } - - private 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() - } + 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)) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt index 61df905c48..aa37055b3c 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt @@ -7,8 +7,9 @@ import android.content.Intent import android.content.IntentFilter import android.graphics.* import android.os.BatteryManager -import android.os.PowerManager 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 @@ -16,6 +17,7 @@ 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 @@ -27,6 +29,7 @@ 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 @@ -49,6 +52,7 @@ 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() { @@ -67,6 +71,9 @@ abstract class BaseWatchFace : WatchFace() { protected var treatmentData = TreatmentData(ArrayList(), ArrayList(), ArrayList(), ArrayList()) protected var graphData = EventData.GraphData(ArrayList()) + // Layout + @LayoutRes abstract fun layoutResource(): Int + private val displaySize = Point() var mTime: TextView? = null var mHour: TextView? = null @@ -100,8 +107,10 @@ abstract class BaseWatchFace : WatchFace() { var mLinearLayout: LinearLayout? = null var mLinearLayout2: LinearLayout? = null var mDate: LinearLayout? = null - var mChartTap: LinearLayout? = null - var mMainMenuTap: 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 @@ -111,13 +120,16 @@ abstract class BaseWatchFace : WatchFace() { var basalBackgroundColor = Color.BLUE var basalCenterColor = Color.BLUE var bolusColor = Color.MAGENTA - var lowResMode = false - var layoutSet = false + private var lowResMode = false + private var layoutSet = false var bIsRound = false var dividerMatchesBg = false var pointSize = 2 - var chart: LineChartView? = null - var wakeLock: PowerManager.WakeLock? = null + + // 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 @@ -146,7 +158,6 @@ abstract class BaseWatchFace : WatchFace() { colorDarkLow = ContextCompat.getColor(this, R.color.dark_lowColor) @Suppress("DEPRECATION") (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay.getSize(displaySize) - wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:BaseWatchFace") specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY) specH = if (forceSquareCanvas) specW else View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY) disposable += rxBus @@ -185,6 +196,58 @@ abstract class BaseWatchFace : WatchFace() { 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() { @@ -272,7 +335,6 @@ abstract class BaseWatchFace : WatchFace() { setupCharts() setDataFields() missedReadingAlert() - wakeLock?.acquire(50) } fun ageLevel(): Int { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt index db8b2e0c53..ab3fab10e5 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt @@ -1,14 +1,7 @@ -@file:Suppress("DEPRECATION") - package info.nightscout.androidaps.watchfaces -import android.annotation.SuppressLint -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. @@ -16,30 +9,7 @@ import info.nightscout.androidaps.interaction.menus.MainMenuActivity */ class CockpitWatchface : BaseWatchFace() { - private var sgvTapTime: Long = 0 - - @SuppressLint("InflateParams") - override fun onCreate() { - super.onCreate() - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - layoutView = inflater.inflate(R.layout.activity_cockpit, null) - performViewSetup() - } - - override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { - if (tapType == TAP_TYPE_TAP) { - 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() - } + override fun layoutResource(): Int = R.layout.activity_cockpit override fun setColorDark() { mRelativeLayout?.setBackgroundResource(R.drawable.airplane_cockpit_outside_clouds) @@ -77,13 +47,13 @@ class CockpitWatchface : BaseWatchFace() { } 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 (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 diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt index dd017cd267..7308fa0873 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt @@ -3,42 +3,18 @@ package info.nightscout.androidaps.watchfaces import android.annotation.SuppressLint -import android.content.Intent import android.support.wearable.watchface.WatchFaceStyle -import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import info.nightscout.androidaps.R import info.nightscout.androidaps.extensions.toVisibility -import info.nightscout.androidaps.interaction.menus.MainMenuActivity import info.nightscout.shared.logging.LTag class DigitalStyleWatchface : BaseWatchFace() { - private var sgvTapTime: Long = 0 - - @SuppressLint("InflateParams") - override fun onCreate() { - super.onCreate() - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - layoutView = inflater.inflate(R.layout.activity_digitalstyle, null) - performViewSetup() - } - - override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { - //tapType = TAP_TYPE_TAP; - aapsLogger.debug(LTag.WEAR, "onTapCommand: DeviceWidth x DeviceHeight /// x , y, TapType >> ", "$width x $height /// $x , $y , $tapType") - if (tapType == TAP_TYPE_TAP) { - if (eventTime - sgvTapTime < TIME_TAP_THRESHOLD) { - val intent = Intent(this, MainMenuActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - startActivity(intent) - } - sgvTapTime = eventTime - } - } + override fun layoutResource(): Int = R.layout.activity_digitalstyle override fun getWatchFaceStyle(): WatchFaceStyle { return WatchFaceStyle.Builder(this) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt index 52f8106741..9347951660 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt @@ -10,7 +10,6 @@ import android.graphics.Point import android.graphics.Rect import android.os.PowerManager import android.support.wearable.watchface.WatchFaceStyle -import android.text.format.DateFormat import android.view.LayoutInflater import android.view.View import android.view.WindowInsets diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt index 776c4a8c6a..2ee0eb5142 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -1,17 +1,10 @@ -@file:Suppress("DEPRECATION") - package info.nightscout.androidaps.watchfaces -import android.annotation.SuppressLint -import android.content.Intent -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 androidx.core.content.ContextCompat import info.nightscout.androidaps.R -import info.nightscout.androidaps.interaction.menus.MainMenuActivity import info.nightscout.shared.SafeParse.stringToFloat import org.joda.time.TimeOfDay @@ -21,43 +14,14 @@ import org.joda.time.TimeOfDay */ class SteampunkWatchface : BaseWatchFace() { - private var chartTapTime: Long = 0 - private var mainMenuTapTime: Long = 0 private var lastEndDegrees = 0f private var deltaRotationAngle = 0f - @SuppressLint("InflateParams") + override fun layoutResource(): Int = R.layout.activity_steampunk + override fun onCreate() { forceSquareCanvas = true super.onCreate() - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - layoutView = inflater.inflate(R.layout.activity_steampunk, null) - performViewSetup() - } - - override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { - 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 - } - } - } - - override fun getWatchFaceStyle(): WatchFaceStyle { - return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() } override fun setColorDark() { @@ -241,15 +205,10 @@ class SteampunkWatchface : BaseWatchFace() { } } - private fun changeChartTimeframe() { + 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 - } - setupCharts() + 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-notround/activity_digitalstyle.xml b/wear/src/main/res/layout-notround/activity_digitalstyle.xml index 7f9fbb28c1..294d708df4 100644 --- a/wear/src/main/res/layout-notround/activity_digitalstyle.xml +++ b/wear/src/main/res/layout-notround/activity_digitalstyle.xml @@ -28,6 +28,7 @@ Date: Sun, 24 Apr 2022 19:58:22 +0200 Subject: [PATCH 29/54] Wear: Watchface cleanup --- .../androidaps/watchfaces/AapsV2Watchface.kt | 14 ++--- .../androidaps/watchfaces/AapsWatchface.kt | 28 +++------ .../watchfaces/DigitalStyleWatchface.kt | 5 -- .../watchfaces/SteampunkWatchface.kt | 58 +++++++------------ 4 files changed, 34 insertions(+), 71 deletions(-) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt index 5432e3d650..9bfd65675d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt @@ -139,16 +139,10 @@ class AapsV2Watchface : BaseWatchFace() { 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) - } + 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) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt index a2ada7a19d..9f7c2e8b63 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt @@ -32,16 +32,10 @@ class AapsWatchface : BaseWatchFace() { 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)) - } + 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) @@ -96,16 +90,10 @@ class AapsWatchface : BaseWatchFace() { 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) - } + 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) { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt index 7308fa0873..b88425c88a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt @@ -130,9 +130,4 @@ class DigitalStyleWatchface : BaseWatchFace() { override fun setColorBright() { setColorDark() /* getCurrentWatchMode() == WatchMode.AMBIENT or WatchMode.INTERACTIVE */ } - - companion object { - - private const val TIME_TAP_THRESHOLD: Long = 800 - } } \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt index 2ee0eb5142..868dd83742 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -32,43 +32,29 @@ class SteampunkWatchface : BaseWatchFace() { mLinearLayout2?.setBackgroundResource(0) mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.black_86p)) } - if (loopLevel == 0) { - mLoop?.setTextColor(ContextCompat.getColor(this, R.color.red_600)) - } else { - mLoop?.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 - if (singleBg.glucoseUnits == "mmol") { - mGlucoseDial?.setImageResource(R.drawable.steampunk_dial_mmol) - } else { - mGlucoseDial?.setImageResource(R.drawable.steampunk_dial_mgdl) - } + 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. - } + 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 - ) - rotate.fillAfter = true - rotate.interpolator = LinearInterpolator() - rotate.duration = 1 + 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. } @@ -85,12 +71,12 @@ class SteampunkWatchface : BaseWatchFace() { if (singleBg.glucoseUnits != "-") { if (singleBg.glucoseUnits == "mmol") { if (sp.getString("delta_granularity", "2") == "4") { //Auto granularity - autoGranularity = "1" // low (init) - if (absAvgDelta < 0.3) { - autoGranularity = "3" // high if below 0.3 mmol/l - } else if (absAvgDelta < 0.5) { - autoGranularity = "2" // medium if below 0.5 mmol/l - } + 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) @@ -106,12 +92,12 @@ class SteampunkWatchface : BaseWatchFace() { } } else { if (sp.getString("delta_granularity", "2") == "4") { //Auto granularity - autoGranularity = "1" // low (init) - if (absAvgDelta < 5) { - autoGranularity = "3" // high if below 5 mg/dl - } else if (absAvgDelta < 10) { - autoGranularity = "2" // medium if below 10 mg/dl - } + 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) From 2b00ea745afc07d943c288a582f2761b84c5ce71 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 24 Apr 2022 20:49:54 +0200 Subject: [PATCH 30/54] NoChartWatchface: based on BaseWatchFace --- .../watchfaces/AapsLargeWatchface.kt | 3 +- .../androidaps/watchfaces/AapsV2Watchface.kt | 3 +- .../androidaps/watchfaces/AapsWatchface.kt | 3 +- .../androidaps/watchfaces/BaseWatchFace.kt | 24 +- .../watchfaces/BigChartWatchface.kt | 14 +- .../androidaps/watchfaces/CockpitWatchface.kt | 3 +- .../watchfaces/DigitalStyleWatchface.kt | 3 +- .../androidaps/watchfaces/NoChartWatchface.kt | 260 +----------------- .../watchfaces/SteampunkWatchface.kt | 3 +- .../res/layout-notround/activity_bigchart.xml | 2 +- .../activity_bigchart_small.xml | 2 +- .../res/layout-notround/activity_nochart.xml | 10 +- .../activity_nochart_small.xml | 2 +- .../res/layout-round/activity_bigchart.xml | 2 +- .../layout-round/activity_bigchart_small.xml | 2 +- .../res/layout-round/activity_nochart.xml | 10 +- .../layout-round/activity_nochart_small.xml | 2 +- 17 files changed, 48 insertions(+), 300 deletions(-) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt index 84104d0c85..39e7252498 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt @@ -1,13 +1,14 @@ 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() { - override fun layoutResource(): Int = R.layout.activity_home_large + @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)) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt index 9bfd65675d..5665af5c09 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt @@ -2,13 +2,14 @@ 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() { - override fun layoutResource(): Int = R.layout.activity_home_2 + @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 diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt index 9f7c2e8b63..48e457a3d1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt @@ -1,13 +1,14 @@ 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() { - override fun layoutResource(): Int = R.layout.activity_home + @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)) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt index aa37055b3c..0a985d3fb9 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt @@ -337,11 +337,8 @@ abstract class BaseWatchFace : WatchFace() { missedReadingAlert() } - fun ageLevel(): Int { - return if (timeSince() <= 1000 * 60 * 12) { - 1 - } else 0 - } + fun ageLevel(): Int = + if (timeSince() <= 1000 * 60 * 12) 1 else 0 fun timeSince(): Double { return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() @@ -414,13 +411,9 @@ abstract class BaseWatchFace : WatchFace() { override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { - val wl = wearUtil.getWakeLock("readingPrefs", 50) missedReadingAlert() checkVibrateHourly(oldTime, newTime) - if (!isSimpleUi) { - setDataFields() - } - wearUtil.releaseWakeLock(wl) + if (!isSimpleUi) setDataFields() } } @@ -442,7 +435,8 @@ abstract class BaseWatchFace : WatchFace() { } } - @SuppressLint("SetTextI18n") fun setDataFields() { + @SuppressLint("SetTextI18n") + fun setDataFields() { setDateAndTime() mSgv?.text = singleBg.sgvString mSgv?.visibility = sp.getBoolean(R.string.key_show_bg, true).toVisibilityKeepSpace() @@ -531,11 +525,8 @@ abstract class BaseWatchFace : WatchFace() { override fun onWatchModeChanged(watchMode: WatchMode) { lowResMode = isLowRes(watchMode) - if (isSimpleUi) { - setSimpleUiAntiAlias() - } else { - setDataFields() - } + if (isSimpleUi) setSimpleUiAntiAlias() + else setDataFields() invalidate() } @@ -605,5 +596,6 @@ abstract class BaseWatchFace : WatchFace() { 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/BigChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt index a88f46c6fe..9884c7861f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt @@ -82,7 +82,7 @@ class BigChartWatchface : WatchFace() { private val displaySize = Point() private var specW = 0 private var specH = 0 - private var statusView: TextView? = null + private var mStatus: TextView? = null private var chartTapTime = 0L private var sgvTapTime = 0L @@ -172,7 +172,7 @@ class BigChartWatchface : WatchFace() { mAvgDelta = layoutView?.findViewById(R.id.avgdelta) mRelativeLayout = layoutView?.findViewById(R.id.main_layout) chart = layoutView?.findViewById(R.id.chart) - statusView = layoutView?.findViewById(R.id.aps_status) + mStatus = layoutView?.findViewById(R.id.externaltstatus) layoutSet = true showAgeAndStatus() mRelativeLayout?.measure(specW, specH) @@ -271,8 +271,8 @@ class BigChartWatchface : WatchFace() { private fun showAgeAndStatus() { mTimestamp?.text = readingAge() mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() - statusView?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() - statusView?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" + mStatus?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() + mStatus?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" } private fun setColor() { @@ -285,7 +285,7 @@ class BigChartWatchface : WatchFace() { private fun setColorLowRes() { mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) - statusView?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + 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)) @@ -305,7 +305,7 @@ class BigChartWatchface : WatchFace() { private fun setColorDark() { mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) - statusView?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) when (singleBg.sgvLevel) { 1L -> { @@ -346,7 +346,7 @@ class BigChartWatchface : WatchFace() { private fun setColorBright() { if (currentWatchMode == WatchMode.INTERACTIVE) { mTime?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) - statusView?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) when (singleBg.sgvLevel) { 1L -> { diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt index ab3fab10e5..cb15fbc7f9 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.watchfaces import android.view.View +import androidx.annotation.LayoutRes import info.nightscout.androidaps.R /** @@ -9,7 +10,7 @@ import info.nightscout.androidaps.R */ class CockpitWatchface : BaseWatchFace() { - override fun layoutResource(): Int = R.layout.activity_cockpit + @LayoutRes override fun layoutResource(): Int = R.layout.activity_cockpit override fun setColorDark() { mRelativeLayout?.setBackgroundResource(R.drawable.airplane_cockpit_outside_clouds) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt index b88425c88a..e8d7ba0cf8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt @@ -7,6 +7,7 @@ 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 @@ -14,7 +15,7 @@ import info.nightscout.shared.logging.LTag class DigitalStyleWatchface : BaseWatchFace() { - override fun layoutResource(): Int = R.layout.activity_digitalstyle + @LayoutRes override fun layoutResource(): Int = R.layout.activity_digitalstyle override fun getWatchFaceStyle(): WatchFaceStyle { return WatchFaceStyle.Builder(this) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt index 9347951660..bcbb388684 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt @@ -1,240 +1,19 @@ -@file:Suppress("DEPRECATION") - package info.nightscout.androidaps.watchfaces -import android.annotation.SuppressLint -import android.content.Intent -import android.graphics.Canvas -import android.graphics.Paint -import android.graphics.Point -import android.graphics.Rect -import android.os.PowerManager -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.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.events.EventWearToMobile -import info.nightscout.androidaps.extensions.toVisibility -import info.nightscout.androidaps.interaction.menus.MainMenuActivity -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 io.reactivex.rxjava3.disposables.CompositeDisposable -import io.reactivex.rxjava3.kotlin.plusAssign -import javax.inject.Inject -import kotlin.math.floor -class NoChartWatchface : WatchFace() { +class NoChartWatchface : BaseWatchFace() { - @Inject lateinit var rxBus: RxBus - @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var sp: SP - @Inject lateinit var dateUtil: DateUtil + @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 - private var disposable = CompositeDisposable() - - private var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) - private var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) - - private var mTime: TextView? = null - private var mSgv: TextView? = null - private var mTimestamp: TextView? = null - private var mDelta: TextView? = null - private var mAvgDelta: TextView? = null - private var mRelativeLayout: RelativeLayout? = null - private var sgvLevel: Long = 0 - private var ageLevel = 1 - private var lowResMode = false - private var layoutSet = false - private var wakeLock: PowerManager.WakeLock? = null - private var layoutView: View? = null - private val displaySize = Point() - private var specW = 0 - private var specH = 0 - private var statusView: TextView? = null - private var sgvTapTime = 0L - - @SuppressLint("InflateParams") - override fun onCreate() { - AndroidInjection.inject(this) - super.onCreate() - val display = (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay - display.getSize(displaySize) - wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).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) - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - val metrics = resources.displayMetrics - layoutView = if (metrics.widthPixels < SCREEN_SIZE_SMALL || metrics.heightPixels < SCREEN_SIZE_SMALL) { - inflater.inflate(R.layout.activity_nochart_small, null) - } else { - inflater.inflate(R.layout.activity_nochart, null) - } - disposable += rxBus - .toObservable(SingleBg::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event: SingleBg -> - aapsLogger.debug(LTag.WEAR, "SingleBg received") - singleBg = event - mSgv?.let { sgv -> - sgv.text = singleBg.sgvString - if (ageLevel() <= 0) sgv.paintFlags = sgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG - else sgv.paintFlags = sgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() - } - mTime?.text = dateUtil.timeString() - mDelta?.text = singleBg.delta - mAvgDelta?.text = singleBg.avgDelta - } - disposable += rxBus - .toObservable(EventData.Status::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event: EventData.Status -> - // this event is received as last batch of data - aapsLogger.debug(LTag.WEAR, "Status received") - status = event - showAgeAndStatus() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - invalidate() - setColor() - } - disposable += rxBus - .toObservable(EventData.Preferences::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { - setColor() - if (layoutSet) { - showAgeAndStatus() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - } - invalidate() - } - performViewSetup() - } - - override fun onLayout(shape: WatchShape, screenBounds: Rect, screenInsets: WindowInsets) { - super.onLayout(shape, screenBounds, screenInsets) - layoutView?.onApplyWindowInsets(screenInsets) - } - - private fun performViewSetup() { - mTime = layoutView?.findViewById(R.id.watch_time) - mSgv = layoutView?.findViewById(R.id.sgv) - mTimestamp = layoutView?.findViewById(R.id.timestamp) - mDelta = layoutView?.findViewById(R.id.delta) - mAvgDelta = layoutView?.findViewById(R.id.avgdelta) - mRelativeLayout = layoutView?.findViewById(R.id.main_layout) - statusView = layoutView?.findViewById(R.id.aps_status) - layoutSet = true - showAgeAndStatus() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - rxBus.send(EventWearToMobile(ActionResendData("NOChart:performViewSetup"))) - } - - 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) { - startActivity(Intent(this, MainMenuActivity::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) - } - sgvTapTime = eventTime - } - } - } - - override fun onWatchModeChanged(watchMode: WatchMode) { - if (lowResMode xor isLowRes(watchMode)) { //if there was a change in lowResMode - lowResMode = isLowRes(watchMode) - setColor() - } else if (!sp.getBoolean("dark", true)) { - //in bright mode: different colours if active: - setColor() - } - } - - private fun isLowRes(watchMode: WatchMode): Boolean { - return watchMode == WatchMode.LOW_BIT || watchMode == WatchMode.LOW_BIT_BURN_IN - } - - override fun getWatchFaceStyle(): WatchFaceStyle { - return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() - } - - private fun ageLevel(): Int = if (timeSince() <= 1000 * 60 * 12) 1 else 0 - - fun timeSince(): Double = (System.currentTimeMillis() - singleBg.timeStamp).toDouble() - - private fun readingAge(): String = - if (singleBg.timeStamp == 0L) "--'" - else "${floor(timeSince() / (1000 * 60)).toInt()}'" - - - override fun onDestroy() { - disposable.clear() - super.onDestroy() - } - - override fun onDraw(canvas: Canvas) { - if (layoutSet) { - mRelativeLayout?.draw(canvas) - } - } - - override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { - if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { - mTime?.text = dateUtil.timeString() - showAgeAndStatus() - mSgv?.let { sgv -> - if (ageLevel() <= 0) { - sgv.paintFlags = sgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG - } else { - sgv.paintFlags = sgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() - } - } - missedReadingAlert() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - } - } - - private fun showAgeAndStatus() { - mTimestamp?.text = readingAge() - mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_avg_delta, true).toVisibility() - statusView?.text = status.externalStatus - statusView?.visibility = View.VISIBLE - } - - private fun setColor() { - when { - lowResMode -> setColorLowRes() - sp.getBoolean("dark", true) -> setColorDark() - else -> setColorBright() - } - } - - private fun setColorLowRes() { + override fun setColorLowRes() { mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) - statusView?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + 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)) @@ -242,11 +21,11 @@ class NoChartWatchface : WatchFace() { mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) } - private fun setColorDark() { + override fun setColorDark() { mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) - statusView?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) - when (sgvLevel) { + when (singleBg.sgvLevel) { 1L -> { mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) @@ -272,12 +51,12 @@ class NoChartWatchface : WatchFace() { } } - private fun setColorBright() { + override fun setColorBright() { if (currentWatchMode == WatchMode.INTERACTIVE) { mTime?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) - statusView?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) - when (sgvLevel) { + when (singleBg.sgvLevel) { 1L -> { mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) @@ -305,17 +84,4 @@ class NoChartWatchface : WatchFace() { setColorDark() } } - - private fun missedReadingAlert() { - val minutesSince = floor(timeSince() / (1000 * 60)).toInt() - if (minutesSince >= 16 && (minutesSince - 16) % 5 == 0) { - // attempt endTime recover missing data - rxBus.send(EventWearToMobile(ActionResendData("NOChart::missedReadingAlert"))) - } - } - - companion object { - - const val SCREEN_SIZE_SMALL = 280 - } } \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt index 868dd83742..6f12bde236 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -3,6 +3,7 @@ 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 @@ -17,7 +18,7 @@ class SteampunkWatchface : BaseWatchFace() { private var lastEndDegrees = 0f private var deltaRotationAngle = 0f - override fun layoutResource(): Int = R.layout.activity_steampunk + @LayoutRes override fun layoutResource(): Int = R.layout.activity_steampunk override fun onCreate() { forceSquareCanvas = true diff --git a/wear/src/main/res/layout-notround/activity_bigchart.xml b/wear/src/main/res/layout-notround/activity_bigchart.xml index 8b8ed78e10..d610c6f38b 100644 --- a/wear/src/main/res/layout-notround/activity_bigchart.xml +++ b/wear/src/main/res/layout-notround/activity_bigchart.xml @@ -65,7 +65,7 @@ android:gravity="center_horizontal" /> - - - - Date: Mon, 25 Apr 2022 08:38:35 +0200 Subject: [PATCH 31/54] BigChartWatchface based on BaseWatchFace --- .../androidaps/watchfaces/BaseWatchFace.kt | 10 +- .../watchfaces/BigChartWatchface.kt | 329 +----------------- 2 files changed, 18 insertions(+), 321 deletions(-) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt index 0a985d3fb9..96f4e09fc0 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt @@ -295,7 +295,7 @@ abstract class BaseWatchFace : WatchFace() { bIsRound = screenInsets.isRound } - fun performViewSetup() { + private fun performViewSetup() { mTime = layoutView?.findViewById(R.id.watch_time) mHour = layoutView?.findViewById(R.id.hour) mMinute = layoutView?.findViewById(R.id.minute) @@ -344,7 +344,7 @@ abstract class BaseWatchFace : WatchFace() { return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() } - private fun readingAge(shortString: Boolean): String { + protected fun readingAge(shortString: Boolean): String { if (singleBg.timeStamp == 0L) { return if (shortString) "--" else "-- Minute ago" } @@ -436,7 +436,7 @@ abstract class BaseWatchFace : WatchFace() { } @SuppressLint("SetTextI18n") - fun setDataFields() { + open fun setDataFields() { setDateAndTime() mSgv?.text = singleBg.sgvString mSgv?.visibility = sp.getBoolean(R.string.key_show_bg, true).toVisibilityKeepSpace() @@ -497,7 +497,7 @@ abstract class BaseWatchFace : WatchFace() { invalidate() } - private fun setDateAndTime() { + protected fun setDateAndTime() { mTime?.text = dateUtil.timeString() mHour?.text = dateUtil.hourString() mMinute?.text = dateUtil.minuteString() @@ -516,7 +516,7 @@ abstract class BaseWatchFace : WatchFace() { } } - private fun strikeThroughSgvIfNeeded() { + 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() diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt index 9884c7861f..8fe6eaae33 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt @@ -2,288 +2,23 @@ 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.Rect -import android.os.PowerManager -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.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.events.EventWearToMobile -import info.nightscout.androidaps.extensions.toVisibility -import info.nightscout.androidaps.interaction.menus.MainMenuActivity -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 lecho.lib.hellocharts.view.LineChartView -import javax.inject.Inject -import kotlin.math.floor -class BigChartWatchface : WatchFace() { +class BigChartWatchface : BaseWatchFace() { - @Inject lateinit var rxBus: RxBus - @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var sp: SP - @Inject lateinit var dateUtil: DateUtil + @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 - private var disposable = CompositeDisposable() - - private var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) - private var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) - private var treatmentData = TreatmentData(java.util.ArrayList(), java.util.ArrayList(), java.util.ArrayList(), java.util.ArrayList()) - private var graphData = EventData.GraphData(java.util.ArrayList()) - - private var mTime: TextView? = null - private var mSgv: TextView? = null - private var mTimestamp: TextView? = null - private var mDelta: TextView? = null - private var mAvgDelta: TextView? = null - private var mRelativeLayout: RelativeLayout? = null - private var ageLevel = 1 - private var highColor = Color.YELLOW - private var lowColor = Color.RED - private var midColor = Color.WHITE - private var gridColour = Color.WHITE - private var basalBackgroundColor = Color.BLUE - private var basalCenterColor = Color.BLUE - private var bolusColor = Color.MAGENTA - private var carbsColor = Color.GREEN - private var pointSize = 2 - private var lowResMode = false - private var layoutSet = false - var chart: LineChartView? = null - private var bgDataList = ArrayList() - private var wakeLock: PowerManager.WakeLock? = null - private var layoutView: View? = null - private val displaySize = Point() - private var specW = 0 - private var specH = 0 - private var mStatus: TextView? = null - private var chartTapTime = 0L - private var sgvTapTime = 0L - - @SuppressLint("InflateParams") - override fun onCreate() { - AndroidInjection.inject(this) - super.onCreate() - val display = (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay - display.getSize(displaySize) - wakeLock = (getSystemService(POWER_SERVICE) as PowerManager).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) - val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater - val metrics = resources.displayMetrics - layoutView = if (metrics.widthPixels < SCREEN_SIZE_SMALL || metrics.heightPixels < SCREEN_SIZE_SMALL) { - inflater.inflate(R.layout.activity_bigchart_small, null) - } else { - inflater.inflate(R.layout.activity_bigchart, null) - } - performViewSetup() - disposable.add(rxBus - .toObservable(SingleBg::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event -> - aapsLogger.debug(LTag.WEAR, "SingleBg received") - singleBg = event - mSgv?.text = singleBg.sgvString - mSgv?.let { mSgv -> - if (ageLevel() <= 0) mSgv.paintFlags = mSgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG - else mSgv.paintFlags = mSgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() - } - mTime?.text = dateUtil.timeString() - mDelta?.text = singleBg.delta - mAvgDelta?.text = singleBg.avgDelta - } - ) - disposable.add(rxBus - .toObservable(TreatmentData::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event -> treatmentData = event } - ) - disposable.add(rxBus - .toObservable(EventData.GraphData::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event -> graphData = event } - ) - disposable.add(rxBus - .toObservable(EventData.Status::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event -> - // this event is received as last batch of data - aapsLogger.debug(LTag.WEAR, "Status received") - status = event - showAgeAndStatus() - addToWatchSet() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - invalidate() - setColor() - } - ) - disposable.add(rxBus - .toObservable(EventData.Preferences::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { - setColor() - if (layoutSet) { - showAgeAndStatus() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - } - invalidate() - } - ) - } - - override fun onLayout(shape: WatchShape, screenBounds: Rect, screenInsets: WindowInsets) { - super.onLayout(shape, screenBounds, screenInsets) - layoutView?.onApplyWindowInsets(screenInsets) - } - - private fun performViewSetup() { - mTime = layoutView?.findViewById(R.id.watch_time) - mSgv = layoutView?.findViewById(R.id.sgv) - mTimestamp = layoutView?.findViewById(R.id.timestamp) - mDelta = layoutView?.findViewById(R.id.delta) - mAvgDelta = layoutView?.findViewById(R.id.avgdelta) - mRelativeLayout = layoutView?.findViewById(R.id.main_layout) - chart = layoutView?.findViewById(R.id.chart) - mStatus = layoutView?.findViewById(R.id.externaltstatus) - layoutSet = true - showAgeAndStatus() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - rxBus.send(EventWearToMobile(ActionResendData("BIGChart:performViewSetup"))) - wakeLock?.acquire(50) - } - - override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { - chart?.let { chart -> - mSgv?.let { mSgv -> - val extra = (mSgv.right - mSgv.left) / 2 - if (tapType == TAP_TYPE_TAP && x >= chart.left && x <= chart.right && y >= chart.top && y <= chart.bottom) { - if (eventTime - chartTapTime < 800) { - changeChartTimeframe() - } - chartTapTime = eventTime - } else 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 - } - } - } - } - - private 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 onWatchModeChanged(watchMode: WatchMode) { - if (lowResMode xor isLowRes(watchMode)) { //if there was a change in lowResMode - lowResMode = isLowRes(watchMode) - setColor() - } else if (!sp.getBoolean("dark", true)) { - //in bright mode: different colours if active: - setColor() - } - } - - private fun isLowRes(watchMode: WatchMode): Boolean { - return watchMode == WatchMode.LOW_BIT || watchMode == WatchMode.LOW_BIT_BURN_IN - } - - override fun getWatchFaceStyle(): WatchFaceStyle { - return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() - } - - private fun ageLevel(): Int { - return if (timeSince() <= 1000 * 60 * 12) { - 1 - } else { - 0 - } - } - - fun timeSince(): Double { - return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() - } - - private fun readingAge(): String = - if (singleBg.timeStamp == 0L) "--'" - else "${floor(timeSince() / (1000 * 60)).toInt()}'" - - override fun onDestroy() { - disposable.clear() - super.onDestroy() - } - - override fun onDraw(canvas: Canvas) { - if (layoutSet) { - mRelativeLayout?.draw(canvas) - } - } - - override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { - if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { - wakeLock?.acquire(50) - mTime?.text = dateUtil.timeString() - showAgeAndStatus() - mSgv?.let { mSgv -> - if (ageLevel() <= 0) mSgv.paintFlags = mSgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG - else mSgv.paintFlags = mSgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() - } - missedReadingAlert() - mRelativeLayout?.measure(specW, specH) - mRelativeLayout?.layout(0, 0, mRelativeLayout?.measuredWidth ?: 0, mRelativeLayout?.measuredHeight ?: 0) - } - } - - private fun showAgeAndStatus() { - mTimestamp?.text = readingAge() - mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() - mStatus?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() + override fun setDataFields() { + super.setDataFields() mStatus?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" } - private fun setColor() { - when { - lowResMode -> setColorLowRes() - sp.getBoolean("dark", true) -> setColorDark() - else -> setColorBright() - } - } - - private fun setColorLowRes() { + 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)) @@ -295,7 +30,7 @@ class BigChartWatchface : WatchFace() { highColor = ContextCompat.getColor(this, R.color.dark_midColor) lowColor = ContextCompat.getColor(this, R.color.dark_midColor) midColor = ContextCompat.getColor(this, R.color.dark_midColor) - gridColour = ContextCompat.getColor(this, R.color.dark_gridColor) + 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 @@ -303,7 +38,7 @@ class BigChartWatchface : WatchFace() { } } - private fun setColorDark() { + 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)) @@ -335,7 +70,7 @@ class BigChartWatchface : WatchFace() { highColor = ContextCompat.getColor(this, R.color.dark_highColor) lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) midColor = ContextCompat.getColor(this, R.color.dark_midColor) - gridColour = ContextCompat.getColor(this, R.color.dark_gridColor) + 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 @@ -343,7 +78,7 @@ class BigChartWatchface : WatchFace() { } } - private fun setColorBright() { + 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)) @@ -373,7 +108,7 @@ class BigChartWatchface : WatchFace() { highColor = ContextCompat.getColor(this, R.color.light_highColor) lowColor = ContextCompat.getColor(this, R.color.light_lowColor) midColor = ContextCompat.getColor(this, R.color.light_midColor) - gridColour = ContextCompat.getColor(this, R.color.light_gridColor) + 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 @@ -383,42 +118,4 @@ class BigChartWatchface : WatchFace() { setColorDark() } } - - private fun missedReadingAlert() { - val minutesSince = floor(timeSince() / (1000 * 60)).toInt() - if (minutesSince >= 16 && (minutesSince - 16) % 5 == 0) { - // attempt endTime recover missing data - rxBus.send(EventWearToMobile(ActionResendData("BIGChart:missedReadingAlert"))) - } - } - - private fun addToWatchSet() { - bgDataList = graphData.entries - } - - private fun setupCharts() { - if (bgDataList.size > 0) { - val timeframe = sp.getInt(R.string.key_chart_time_frame, 3) - val bgGraphBuilder = if (lowResMode) { - BgGraphBuilder( - sp, dateUtil, bgDataList, treatmentData.predictions, treatmentData.temps, treatmentData.basals, treatmentData.boluses, pointSize, - midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe - ) - } else { - BgGraphBuilder( - sp, dateUtil, bgDataList, treatmentData.predictions, treatmentData.temps, treatmentData.basals, treatmentData.boluses, pointSize, - highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe - ) - } - chart?.lineChartData = bgGraphBuilder.lineData() - chart?.isViewportCalculationEnabled = true - } else { - rxBus.send(EventWearToMobile(ActionResendData("BIGChart:setupCharts"))) - } - } - - companion object { - - private const val SCREEN_SIZE_SMALL = 280 - } } \ No newline at end of file From efa293c141d6abd46e94934a4c1cd800d3078f0a Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 26 Apr 2022 11:00:20 +0200 Subject: [PATCH 32/54] Wear: do not export activities --- wear/src/main/AndroidManifest.xml | 7 ------- 1 file changed, 7 deletions(-) diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index ec2f3a4f8e..59c5068de6 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -552,7 +552,6 @@ android:label="@string/menu_settings" /> Date: Tue, 26 Apr 2022 11:13:17 +0200 Subject: [PATCH 33/54] lint --- .../androidaps/plugins/constraints/safety/SafetyPlugin.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 abff829785..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 @@ -37,7 +37,7 @@ class SafetyPlugin @Inject constructor( private val constraintChecker: ConstraintChecker, private val openAPSAMAPlugin: OpenAPSAMAPlugin, private val openAPSSMBPlugin: OpenAPSSMBPlugin, - private val OpenAPSSMBDynamicISFPlugin: OpenAPSSMBDynamicISFPlugin, + private val openAPSSMBDynamicISFPlugin: OpenAPSSMBDynamicISFPlugin, private val sensitivityOref1Plugin: SensitivityOref1Plugin, private val activePlugin: ActivePlugin, private val hardLimits: HardLimits, @@ -190,12 +190,12 @@ class SafetyPlugin @Inject constructor( override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { val apsMode = sp.getString(R.string.key_aps_mode, "open") - val maxIobPref: Double = if (openAPSSMBPlugin.isEnabled() || OpenAPSSMBDynamicISFPlugin.isEnabled()) sp.getDouble(R.string.key_openapssmb_max_iob, 3.0) else sp.getDouble(R.string + val maxIobPref: Double = if (openAPSSMBPlugin.isEnabled() || openAPSSMBDynamicISFPlugin.isEnabled()) sp.getDouble(R.string.key_openapssmb_max_iob, 3.0) else sp.getDouble(R.string .key_openapsma_max_iob, 1.5) maxIob.setIfSmaller(aapsLogger, maxIobPref, rh.gs(R.string.limitingiob, maxIobPref, rh.gs(R.string.maxvalueinpreferences)), this) if (openAPSAMAPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobAMA(), rh.gs(R.string.limitingiob, hardLimits.maxIobAMA(), rh.gs(R.string.hardlimit)), this) if (openAPSSMBPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), rh.gs(R.string.limitingiob, hardLimits.maxIobSMB(), rh.gs(R.string.hardlimit)), this) - if (OpenAPSSMBDynamicISFPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), rh.gs(R.string.limitingiob, hardLimits.maxIobSMB(), rh.gs(R.string.hardlimit)), this) + if (openAPSSMBDynamicISFPlugin.isEnabled()) maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), rh.gs(R.string.limitingiob, hardLimits.maxIobSMB(), rh.gs(R.string.hardlimit)), this) if (apsMode == "lgs") maxIob.setIfSmaller(aapsLogger, HardLimits.MAX_IOB_LGS, rh.gs(R.string.limitingiob, HardLimits.MAX_IOB_LGS, rh.gs(R.string.lowglucosesuspend)), this) return maxIob } From 8ce4a7d716e1a1c42310a31c82724ee763f3e5d3 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 21:54:37 +0200 Subject: [PATCH 34/54] cleanup --- .../androidaps/comm/DataHandlerWear.kt | 29 +-- .../comm/DataLayerListenerServiceWear.kt | 25 ++- .../comm/IntentCancelNotification.kt | 11 + .../androidaps/comm/IntentWearToMobile.kt | 19 ++ .../BaseComplicationProviderService.java | 46 ++--- .../complications/BrCobIobComplication.java | 1 + .../CobDetailedComplication.java | 1 + .../complications/CobIconComplication.java | 1 + .../complications/CobIobComplication.java | 1 + .../ComplicationTapBroadcastReceiver.java | 3 +- .../IobDetailedComplication.java | 1 + .../complications/IobIconComplication.java | 1 + .../complications/LongStatusComplication.java | 1 + .../LongStatusFlippedComplication.java | 1 + .../complications/SgvComplication.java | 1 + .../UploaderBatteryComplication.java | 1 + .../complications/WallpaperComplication.java | 1 + .../androidaps/data/RawDisplayData.kt | 57 ++--- .../interaction/actions/AcceptActivity.kt | 14 +- .../interaction/utils/Persistence.java | 185 ----------------- .../interaction/utils/Persistence.kt | 195 ++++++++++++++++++ .../interaction/utils/PlusMinusEditText.java | 16 +- .../androidaps/watchfaces/BaseWatchFace.kt | 30 ++- .../androidaps/watchfaces/CircleWatchface.kt | 25 ++- .../watchfaces/SteampunkWatchface.kt | 2 + 25 files changed, 332 insertions(+), 336 deletions(-) create mode 100644 wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt create mode 100644 wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt index da9b9ef702..af9967f71a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt @@ -68,8 +68,8 @@ class DataHandlerWear @Inject constructor( addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) putExtras( Bundle().also { bundle -> - bundle.putString("title", it.title) - bundle.putString("message", it.message) + bundle.putString(DataLayerListenerServiceWear.KEY_TITLE, it.title) + bundle.putString(DataLayerListenerServiceWear.KEY_MESSAGE, it.message) bundle.putString(DataLayerListenerServiceWear.KEY_ACTION_DATA, it.returnCommand?.serialize()) } ) @@ -123,11 +123,7 @@ class DataHandlerWear @Inject constructor( .subscribe { aapsLogger.debug(LTag.WEAR, "Status received from ${it.sourceNodeId}") persistence.store(it) - LocalBroadcastManager.getInstance(context).sendBroadcast( - Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { - putExtra(DataLayerListenerServiceWear.KEY_STATUS_DATA, it.serialize()) - } - ) + LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA)) } disposable += rxBus .toObservable(EventData.SingleBg::class.java) @@ -135,11 +131,6 @@ class DataHandlerWear @Inject constructor( .subscribe { aapsLogger.debug(LTag.WEAR, "SingleBg received from ${it.sourceNodeId}") persistence.store(it) - LocalBroadcastManager.getInstance(context).sendBroadcast( - Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { - putExtra(DataLayerListenerServiceWear.KEY_SINGLE_BG_DATA, it.serialize()) - } - ) } disposable += rxBus .toObservable(EventData.GraphData::class.java) @@ -147,11 +138,6 @@ class DataHandlerWear @Inject constructor( .subscribe { aapsLogger.debug(LTag.WEAR, "GraphData received from ${it.sourceNodeId}") persistence.store(it) - LocalBroadcastManager.getInstance(context).sendBroadcast( - Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { - putExtra(DataLayerListenerServiceWear.KEY_GRAPH_DATA, it.serialize()) - } - ) } disposable += rxBus .toObservable(EventData.TreatmentData::class.java) @@ -159,11 +145,6 @@ class DataHandlerWear @Inject constructor( .subscribe { aapsLogger.debug(LTag.WEAR, "TreatmentData received from ${it.sourceNodeId}") persistence.store(it) - LocalBroadcastManager.getInstance(context).sendBroadcast( - Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA).apply { - putExtra(DataLayerListenerServiceWear.KEY_TREATMENTS_DATA, it.serialize()) - } - ) } disposable += rxBus .toObservable(EventData.Preferences::class.java) @@ -282,8 +263,8 @@ class DataHandlerWear @Inject constructor( val intent = Intent(context, AcceptActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) putExtras(Bundle().also { bundle -> - bundle.putString("title", command.title) - bundle.putString("message", command.message) + bundle.putString(DataLayerListenerServiceWear.KEY_TITLE, command.title) + bundle.putString(DataLayerListenerServiceWear.KEY_MESSAGE, command.message) bundle.putString(DataLayerListenerServiceWear.KEY_ACTION_DATA, command.returnCommand?.serialize()) }) } diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt b/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt index 3950cd0c10..e027d0fcbd 100644 --- a/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.comm +import android.app.NotificationManager import android.content.Intent import android.os.Handler import android.os.HandlerThread @@ -100,6 +101,9 @@ class DataLayerListenerServiceWear : WearableListenerService() { 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") } } } @@ -107,13 +111,15 @@ class DataLayerListenerServiceWear : WearableListenerService() { override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { when (intent?.action) { - INTENT_CANCEL_BOLUS -> { + 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 } @@ -125,7 +131,7 @@ class DataLayerListenerServiceWear : WearableListenerService() { capabilityClient.getCapability(PHONE_CAPABILITY, CapabilityClient.FILTER_REACHABLE) ) aapsLogger.debug(LTag.WEAR, "Nodes: ${capabilityInfo.nodes.joinToString(", ") { it.displayName + "(" + it.id + ")" }}") - transcriptionNodeId = pickBestNodeId(capabilityInfo.nodes) + pickBestNodeId(capabilityInfo.nodes)?.let { transcriptionNodeId = it } aapsLogger.debug(LTag.WEAR, "Selected node: $transcriptionNodeId") } @@ -156,16 +162,16 @@ class DataLayerListenerServiceWear : WearableListenerService() { } private fun sendMessage(path: String, data: String?) { - aapsLogger.debug(LTag.WEAR, "sendMessage: $path $data") 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") + aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure $it") } } - } + } ?: aapsLogger.debug(LTag.WEAR, "sendMessage: Ignoring message. No node selected.") } @Suppress("unused") @@ -187,17 +193,16 @@ class DataLayerListenerServiceWear : WearableListenerService() { const val PHONE_CAPABILITY = "androidaps_mobile" // Accepted intents - val INTENT_CANCEL_BOLUS = DataLayerListenerServiceWear::class.java.name + ".CancelBolus" 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_SINGLE_BG_DATA = "single_bg_data" - const val KEY_TREATMENTS_DATA = "treatments_data" - const val KEY_GRAPH_DATA = "graph_data" - const val KEY_STATUS_DATA = "status_data" + const val KEY_TITLE = "title" const val BOLUS_PROGRESS_NOTIF_ID = 1 const val CONFIRM_NOTIF_ID = 2 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 index 9593474390..0db70ad7e1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java @@ -40,6 +40,7 @@ import info.nightscout.shared.weardata.EventData; *

* Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public abstract class BaseComplicationProviderService extends ComplicationProviderService { @Inject Inevitable inevitable; @@ -56,9 +57,6 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid 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"; @@ -201,7 +199,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid persistence.putString("complication_" + complicationId, getProviderCanonicalName()); persistence.putBoolean("complication_" + complicationId + "_since", usesSinceField()); - persistence.addToSet(KEY_COMPLICATIONS, "complication_" + complicationId); + persistence.addToSet(Persistence.KEY_COMPLICATIONS, "complication_" + complicationId); IntentFilter messageFilter = new IntentFilter(DataLayerListenerServiceWear.Companion.getINTENT_NEW_DATA()); @@ -237,15 +235,15 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid getApplicationContext(), thisProvider, complicationId, getComplicationAction()); final RawDisplayData raw = new RawDisplayData(); - raw.updateForComplicationsFromPersistence(persistence); + 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(KEY_LAST_SHOWN_SINCE_VALUE, + persistence.putString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, displayFormat.shortTimeSince(raw.getSingleBg().getTimeStamp())); // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round - persistence.putBoolean(KEY_STALE_REPORTED, false); + persistence.putBoolean(Persistence.KEY_STALE_REPORTED, false); ComplicationData complicationData; @@ -280,7 +278,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid public void onComplicationDeactivated(int complicationId) { aapsLogger.warn(LTag.WEAR, "onComplicationDeactivated(): " + complicationId); - persistence.removeFromSet(KEY_COMPLICATIONS, "complication_" + complicationId); + persistence.removeFromSet(Persistence.KEY_COMPLICATIONS, "complication_" + complicationId); if (localBroadcastManager != null && messageReceiver != null) { localBroadcastManager.unregisterReceiver(messageReceiver); @@ -297,7 +295,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid */ public void checkIfUpdateNeeded() { - aapsLogger.warn(LTag.WEAR, "Pending check if update needed - " + persistence.getString(KEY_COMPLICATIONS, "")); + 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)) { @@ -316,19 +314,19 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid */ private void requestUpdateIfSinceChanged() { final RawDisplayData raw = new RawDisplayData(); - raw.updateForComplicationsFromPersistence(persistence); + raw.updateFromPersistence(persistence); - final String lastSince = persistence.getString(KEY_LAST_SHOWN_SINCE_VALUE, "-"); + final String lastSince = persistence.getString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, "-"); final String calcSince = displayFormat.shortTimeSince(raw.getSingleBg().getTimeStamp()); final boolean isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) || (wearUtil.msSince(raw.getSingleBg().getTimeStamp()) > Constants.STALE_MS); - final boolean staleWasRefreshed = persistence.getBoolean(KEY_STALE_REPORTED, false); + final boolean staleWasRefreshed = persistence.getBoolean(Persistence.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); + 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: " + (isStale ? "- stale detected" : "") @@ -367,7 +365,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid */ private Set getActiveProviderClasses() { Set providers = new HashSet<>(); - Set complications = persistence.getSetOf(KEY_COMPLICATIONS); + Set complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS); for (String complication : complications) { final String providerClass = persistence.getString(complication, ""); if (providerClass.length() > 0) { @@ -384,7 +382,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid */ private Set getSinceDependingProviderClasses() { Set providers = new HashSet<>(); - Set complications = persistence.getSetOf(KEY_COMPLICATIONS); + Set complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS); for (String complication : complications) { final String providerClass = persistence.getString(complication, ""); final boolean dependOnSince = persistence.getBoolean(complication + "_since", false); @@ -401,14 +399,16 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid 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()); - } + updateAll(); } } - + private void updateAll() { + Set complications = persistence.getSetOf(Persistence.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/BrCobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java index bdbc079793..48c4171d91 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java @@ -15,6 +15,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class BrCobIobComplication extends BaseComplicationProviderService { @Inject DisplayFormat displayFormat; diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java index 3f77ca3fb5..17693f8547 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java @@ -11,6 +11,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class CobDetailedComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java index c679635e4c..a0dcde11b7 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java @@ -12,6 +12,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class CobIconComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java index 411b1e943b..b50ebba72f 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java @@ -11,6 +11,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class CobIobComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java index 96b0b36412..cd6f956720 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java @@ -29,6 +29,7 @@ import info.nightscout.shared.sharedPreferences.SP; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver { @Inject WearUtil wearUtil; @@ -64,7 +65,7 @@ public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver { action = remapActionWithUserPreferences(action); // Request an update for the complication that has just been tapped. - ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider); + ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider); requester.requestUpdate(complicationId); Intent intentOpen = null; diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java index 55b6f7168c..23db29f49a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java @@ -11,6 +11,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class IobDetailedComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java index 632ac70c05..d9f66de4ac 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java @@ -13,6 +13,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class IobIconComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java index ad03acfab4..3131b09161 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java @@ -14,6 +14,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class LongStatusComplication extends BaseComplicationProviderService { @Inject DisplayFormat displayFormat; diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java index c66c994d69..e8f4f0a9c2 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java @@ -14,6 +14,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class LongStatusFlippedComplication extends BaseComplicationProviderService { @Inject DisplayFormat displayFormat; diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java index 62d08ad8ba..8934a8df2d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java @@ -14,6 +14,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class SgvComplication extends BaseComplicationProviderService { @Inject DisplayFormat displayFormat; diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java index 6211641bb8..9e5e0b52c8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java @@ -14,6 +14,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public class UploaderBatteryComplication extends BaseComplicationProviderService { public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java index dfceeb4a03..e18b81e98a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java @@ -19,6 +19,7 @@ import info.nightscout.shared.logging.LTag; /* * Created by dlvoy on 2019-11-12 */ +@SuppressWarnings("deprecation") public abstract class WallpaperComplication extends BaseComplicationProviderService { public abstract String getWallpaperAssetsFileName(); diff --git a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt index ece27dee0d..471fc91b42 100644 --- a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt +++ b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt @@ -1,7 +1,5 @@ package info.nightscout.androidaps.data -import android.content.Intent -import info.nightscout.androidaps.comm.DataLayerListenerServiceWear import info.nightscout.androidaps.interaction.utils.Persistence import info.nightscout.shared.weardata.EventData @@ -11,17 +9,23 @@ import info.nightscout.shared.weardata.EventData * passing it to complications via persistence layer. * * Created by dlvoy on 2019-11-12 + * Refactored by MilosKozak 24/04/2022 + * */ class RawDisplayData { - // bg data bundle var singleBg = EventData.SingleBg( timeStamp = 0, + sgvString = "---", + glucoseUnits = "-", + slopeArrow = "--", + delta = "--", + avgDelta = "--", + sgvLevel = 0, sgv = 0.0, high = 0.0, low = 0.0, - color = 0 - ) + color = 0) // status bundle var status = EventData.Status( @@ -39,16 +43,15 @@ class RawDisplayData { batteryLevel = 1 ) - // basals bundle var graphData = EventData.GraphData( - entries = ArrayList() + entries = ArrayList() ) var treatmentData = EventData.TreatmentData( - temps = ArrayList(), - basals = ArrayList(), - boluses = ArrayList(), - predictions = ArrayList() + temps = ArrayList(), + basals = ArrayList(), + boluses = ArrayList(), + predictions = ArrayList() ) fun toDebugString(): String = @@ -60,36 +63,4 @@ class RawDisplayData { persistence.readStatus()?.let { status = it } persistence.readTreatments()?.let { treatmentData = it } } - - /* - * Since complications do not need Basals, we skip them for performance - */ - fun updateForComplicationsFromPersistence(persistence: Persistence) { - persistence.readSingleBg()?.let { singleBg = it } - persistence.readGraphData()?.let { graphData = it } - persistence.readStatus()?.let { status = it } - } - - fun updateFromMessage(intent: Intent) { - intent.getStringExtra(DataLayerListenerServiceWear.KEY_SINGLE_BG_DATA)?.let{ - singleBg = EventData.deserialize(it) as EventData.SingleBg - } - intent.getStringExtra(DataLayerListenerServiceWear.KEY_STATUS_DATA)?.let{ - status = EventData.deserialize(it) as EventData.Status - } - intent.getStringExtra(DataLayerListenerServiceWear.KEY_TREATMENTS_DATA)?.let{ - treatmentData = EventData.deserialize(it) as EventData.TreatmentData - } - intent.getStringExtra(DataLayerListenerServiceWear.KEY_GRAPH_DATA)?.let{ - graphData = EventData.deserialize(it) as EventData.GraphData - } - } - - companion object { - - const val BG_DATA_PERSISTENCE_KEY = "raw_data" - const val GRAPH_DATA_PERSISTENCE_KEY = "raw_data" - const val BASALS_PERSISTENCE_KEY = "raw_basals" - const val STATUS_PERSISTENCE_KEY = "raw_status" - } } \ No newline at end of file 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 index 20f380df43..2134f60f6d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt @@ -19,9 +19,8 @@ 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.events.EventWearToMobile -import info.nightscout.shared.weardata.EventData.CancelNotification -import info.nightscout.shared.weardata.EventData.Companion.deserialize +import info.nightscout.androidaps.comm.IntentCancelNotification +import info.nightscout.androidaps.comm.IntentWearToMobile import kotlin.math.roundToInt class AcceptActivity : ViewSelectorActivity() { @@ -35,9 +34,9 @@ class AcceptActivity : ViewSelectorActivity() { dismissThread = DismissThread() dismissThread?.start() val extras = intent.extras - message = extras?.getString("message", "") ?: "" + message = extras?.getString(DataLayerListenerServiceWear.KEY_MESSAGE, "") ?: "" actionKey = extras?.getString(DataLayerListenerServiceWear.KEY_ACTION_DATA, "") ?: "" - if (message.isEmpty() || actionKey.isEmpty()) { + if (message.isEmpty()) { finish() return } @@ -84,9 +83,8 @@ class AcceptActivity : ViewSelectorActivity() { view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) val confirmButton = view.findViewById(R.id.confirmbutton) confirmButton.setOnClickListener { - val returnCommand = deserialize(actionKey) - rxBus.send(EventWearToMobile(returnCommand)) - rxBus.send(CancelNotification(System.currentTimeMillis())) + if (actionKey.isNotEmpty()) startService(IntentWearToMobile(this@AcceptActivity, actionKey)) + startService(IntentCancelNotification(this@AcceptActivity)) finishAffinity() } container.addView(view) 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 a0856395d9..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java +++ /dev/null @@ -1,185 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.content.Context; -import android.content.SharedPreferences; -import android.util.Base64; - -import androidx.annotation.Nullable; - -import java.util.HashSet; -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.complications.BaseComplicationProviderService; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; -import info.nightscout.shared.weardata.EventData; - -/** - * Created by dlvoy on 2019-11-12 - */ -@Singleton -public class Persistence { - - 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.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); - } - - 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 store(EventData.SingleBg singleBg) { - putString(RawDisplayData.BG_DATA_PERSISTENCE_KEY, singleBg.serialize()); - markDataUpdated(); - } - - @Nullable - public EventData.SingleBg readSingleBg() { - try { - String s = getString(RawDisplayData.BG_DATA_PERSISTENCE_KEY, null); - if (s != null) { - return (EventData.SingleBg) EventData.Companion.deserialize(s); - } - } catch (Exception ignored) {} - return null; - } - - @Nullable - public EventData.Status readStatus() { - try { - String s = getString(RawDisplayData.STATUS_PERSISTENCE_KEY, null); - if (s != null) { - return (EventData.Status) EventData.Companion.deserialize(s); - } - } catch (Exception ignored) {} - return null; - } - - @Nullable - public EventData.TreatmentData readTreatments() { - try { - String s = getString(RawDisplayData.BASALS_PERSISTENCE_KEY, null); - if (s != null) { - return (EventData.TreatmentData) EventData.Companion.deserialize(s); - } - } catch (Exception ignored) {} - return null; - } - - @Nullable - public EventData.GraphData readGraphData() { - try { - String s = getString(RawDisplayData.BG_DATA_PERSISTENCE_KEY, null); - if (s != null) { - return (EventData.GraphData) EventData.Companion.deserialize(s); - } - } catch (Exception ignored) {} - return null; - } - - public void store(EventData.GraphData graphData) { - putString(RawDisplayData.GRAPH_DATA_PERSISTENCE_KEY, graphData.serialize()); - } - - public void store(EventData.TreatmentData treatmentData) { - putString(RawDisplayData.BASALS_PERSISTENCE_KEY, treatmentData.serialize()); - } - - public void store(EventData.Status status) { - putString(RawDisplayData.STATUS_PERSISTENCE_KEY, status.serialize()); - } - - 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..a41a0b5453 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt @@ -0,0 +1,195 @@ +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" + + } + + // For mocking only + fun base64decode(str: String, flags: Int): ByteArray { + return Base64.decode(str, flags) + } + + // For mocking only + fun base64encodeToString(input: ByteArray, flags: Int): String { + return Base64.encodeToString(input, flags) + } + + 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("\\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/watchfaces/BaseWatchFace.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt index 96f4e09fc0..12ea214fac 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt @@ -1,3 +1,5 @@ +@file:Suppress("DEPRECATION") + package info.nightscout.androidaps.watchfaces import android.annotation.SuppressLint @@ -25,6 +27,7 @@ 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 @@ -66,10 +69,12 @@ abstract class BaseWatchFace : WatchFace() { private var disposable = CompositeDisposable() - protected var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) - protected var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) - protected var treatmentData = TreatmentData(ArrayList(), ArrayList(), ArrayList(), ArrayList()) - protected var graphData = EventData.GraphData(ArrayList()) + 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 @@ -169,30 +174,19 @@ abstract class BaseWatchFace : WatchFace() { if (layoutSet) setDataFields() invalidate() } - disposable += rxBus - .toObservable(SingleBg::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event: SingleBg -> singleBg = event } - disposable += rxBus - .toObservable(TreatmentData::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event: TreatmentData -> treatmentData = event } - disposable += rxBus - .toObservable(EventData.GraphData::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event: EventData.GraphData -> graphData = event } disposable += rxBus .toObservable(EventData.Status::class.java) .observeOn(aapsSchedulers.main) - .subscribe { event: EventData.Status -> - status = event + .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() diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt index 6584b64d1f..20e9f511ce 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt @@ -20,8 +20,10 @@ 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 @@ -45,11 +47,15 @@ class CircleWatchface : WatchFace() { @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 var singleBg = SingleBg(0, "---", "-", "--", "--", "--", 0, 0.0, 0.0, 0.0, 0) - private var graphData = EventData.GraphData(ArrayList()) - private var status = EventData.Status("no status", "IOB", "-.--", false, "--g", "-.--U/h", "--", "--", -1, "--", false, 1) + + private val rawData = RawDisplayData() + + private val singleBg get() = rawData.singleBg + private val status get() = rawData.status + private val graphData get() = rawData.graphData companion object { @@ -96,21 +102,13 @@ class CircleWatchface : WatchFace() { myLayout = inflater.inflate(R.layout.activity_circle, null) prepareLayout() prepareDrawTime() - disposable += rxBus - .toObservable(SingleBg::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event -> singleBg = event } - disposable += rxBus - .toObservable(EventData.GraphData::class.java) - .observeOn(aapsSchedulers.main) - .subscribe { event -> graphData = event } disposable += rxBus .toObservable(EventData.Status::class.java) .observeOn(aapsSchedulers.main) - .subscribe { event -> + .subscribe { // this event is received as last batch of data aapsLogger.debug(LTag.WEAR, "Status received") - status = event + rawData.updateFromPersistence(persistence) addToWatchSet() prepareLayout() prepareDrawTime() @@ -124,6 +122,7 @@ class CircleWatchface : WatchFace() { prepareLayout() invalidate() } + rawData.updateFromPersistence(persistence) rxBus.send(EventWearToMobile(ActionResendData("CircleWatchFace::onCreate"))) wakeLock.release() } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt index 6f12bde236..3bc0c08ae1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -1,3 +1,5 @@ +@file:Suppress("DEPRECATION") + package info.nightscout.androidaps.watchfaces import android.view.animation.Animation From f350fa1ed51d41b97db4062cb037fd34fe347472 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:01:21 +0200 Subject: [PATCH 35/54] SgvComplication -> kt --- .../BaseComplicationProviderService.java | 6 +- .../complications/SgvComplication.java | 58 ------------------- .../complications/SgvComplication.kt | 41 +++++++++++++ 3 files changed, 45 insertions(+), 60 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java index 0db70ad7e1..c7648bed92 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java @@ -13,6 +13,8 @@ import android.support.wearable.complications.ComplicationProviderService; import android.support.wearable.complications.ComplicationText; import android.support.wearable.complications.ProviderUpdateRequester; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import java.util.HashSet; @@ -67,9 +69,9 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid // ABSTRACT COMPLICATION INTERFACE //============================================================================================== - public abstract ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent); + public abstract @Nullable ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent); - public abstract String getProviderCanonicalName(); + public abstract @NonNull String getProviderCanonicalName(); public ComplicationAction getComplicationAction() { return ComplicationAction.MENU; 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 8934a8df2d..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java +++ /dev/null @@ -1,58 +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 - */ -@SuppressWarnings("deprecation") -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.getSingleBg().getSgvString() + raw.getSingleBg().getSlopeArrow() + - "\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 From 4e0a83ba852e9f3556622c1bb726b57bf3c030fb Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:18:10 +0200 Subject: [PATCH 36/54] CobDetailedComplication -> kt --- .../CobDetailedComplication.java | 48 ------------------- .../complications/CobDetailedComplication.kt | 35 ++++++++++++++ 2 files changed, 35 insertions(+), 48 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt 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 17693f8547..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java +++ /dev/null @@ -1,48 +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 - */ -@SuppressWarnings("deprecation") -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 From 7de2c5a53af7c1d98174bf14e537eff36fab4d5f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:21:13 +0200 Subject: [PATCH 37/54] BrCobIobComplication -> kt --- .../complications/BrCobIobComplication.java | 54 ------------------- .../complications/BrCobIobComplication.kt | 42 +++++++++++++++ 2 files changed, 42 insertions(+), 54 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt 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 48c4171d91..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 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 - */ -@SuppressWarnings("deprecation") -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.getStatus().getCob(), SmallestDoubleString.Units.USE).minimise(displayFormat.MIN_FIELD_LEN_COB); - final String iob = new SmallestDoubleString(raw.getStatus().getIobSum(), 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.getStatus().getCurrentBasal())) - .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 From 759c81f10ec079bf4962b2edaca9ec9c4e27ed9f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:24:06 +0200 Subject: [PATCH 38/54] CobIconComplication -> kt --- .../complications/CobIconComplication.java | 48 ------------------- .../complications/CobIconComplication.kt | 35 ++++++++++++++ 2 files changed, 35 insertions(+), 48 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt 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 a0dcde11b7..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java +++ /dev/null @@ -1,48 +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 - */ -@SuppressWarnings("deprecation") -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.getStatus().getCob())) - .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 From 9ee281876d6fed59100724890f9ec637e8e8d312 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:26:37 +0200 Subject: [PATCH 39/54] CobIobComplication -> kt --- .../complications/CobIobComplication.java | 41 ------------------- .../complications/CobIobComplication.kt | 34 +++++++++++++++ 2 files changed, 34 insertions(+), 41 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt 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 b50ebba72f..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java +++ /dev/null @@ -1,41 +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 - */ -@SuppressWarnings("deprecation") -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.getStatus().getCob(); - final String iob = new SmallestDoubleString(raw.getStatus().getIobSum(), 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 From 2190da3113a621187bc41e36b78e5ce80331a6db Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:28:48 +0200 Subject: [PATCH 40/54] IobDetailedComplication -> kt --- .../IobDetailedComplication.java | 48 ------------------- .../complications/IobDetailedComplication.kt | 35 ++++++++++++++ 2 files changed, 35 insertions(+), 48 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt 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 23db29f49a..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java +++ /dev/null @@ -1,48 +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 - */ -@SuppressWarnings("deprecation") -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 From 205775e9c7e028ae6d93c3d5f014208659bfdb87 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:30:25 +0200 Subject: [PATCH 41/54] IobIconComplication -> kt --- .../complications/IobIconComplication.java | 51 ------------------- .../complications/IobIconComplication.kt | 37 ++++++++++++++ 2 files changed, 37 insertions(+), 51 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt 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 d9f66de4ac..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java +++ /dev/null @@ -1,51 +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 - */ -@SuppressWarnings("deprecation") -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.getStatus().getIobSum(), 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 From a427c290f4db8a893e235337b582abacdf47737e Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:34:25 +0200 Subject: [PATCH 42/54] LongStatusComplication -> kt --- .../complications/LongStatusComplication.java | 61 ------------------- .../complications/LongStatusComplication.kt | 43 +++++++++++++ 2 files changed, 43 insertions(+), 61 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt 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 3131b09161..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java +++ /dev/null @@ -1,61 +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 - */ -@SuppressWarnings("deprecation") -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 From e2436fedcfa3542e93dc971f0a7322647cd6132f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:36:22 +0200 Subject: [PATCH 43/54] LongStatusFlippedComplication -> kt --- .../LongStatusFlippedComplication.java | 61 ------------------- .../LongStatusFlippedComplication.kt | 43 +++++++++++++ 2 files changed, 43 insertions(+), 61 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt 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 e8f4f0a9c2..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java +++ /dev/null @@ -1,61 +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 - */ -@SuppressWarnings("deprecation") -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 From 60ea0421c88268b274c298e4953f050e0fdff3e5 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:38:42 +0200 Subject: [PATCH 44/54] UploaderBatteryComplication -> kt --- .../UploaderBatteryComplication.java | 158 ------------------ .../UploaderBatteryComplication.kt | 108 ++++++++++++ 2 files changed, 108 insertions(+), 158 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java deleted file mode 100644 index 9e5e0b52c8..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.java +++ /dev/null @@ -1,158 +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 - */ -@SuppressWarnings("deprecation") -public class UploaderBatteryComplication 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.getStatus().getBattery().matches("^[0-9]+$")) { - try { - level = Integer.parseInt(raw.getStatus().getBattery()); - 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.getStatus().getBattery()); - } - } - - 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 UploaderBatteryComplication.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 From 89f86df4823102cd7608cb6b7aae22b4412a5ac0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:42:18 +0200 Subject: [PATCH 45/54] WallpaperComplication -> kt --- .../complications/WallpaperComplication.java | 57 ------------------- .../complications/WallpaperComplication.kt | 47 +++++++++++++++ .../WallpaperDarkComplication.java | 22 ------- .../WallpaperDarkComplication.kt | 11 ++++ .../WallpaperGrayComplication.java | 22 ------- .../WallpaperGrayComplication.kt | 11 ++++ .../WallpaperLightComplication.java | 22 ------- .../WallpaperLightComplication.kt | 11 ++++ 8 files changed, 80 insertions(+), 123 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt 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 e18b81e98a..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java +++ /dev/null @@ -1,57 +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 - */ -@SuppressWarnings("deprecation") -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 From f8bfbf29cfd8e4d7bd6c8b45c6872354fbaf4878 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:51:05 +0200 Subject: [PATCH 46/54] ComplicationTapBroadcastReceiver -> kt --- .../BaseComplicationProviderService.java | 8 +- .../ComplicationTapBroadcastReceiver.java | 180 ------------------ .../ComplicationTapBroadcastReceiver.kt | 150 +++++++++++++++ 3 files changed, 155 insertions(+), 183 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java index c7648bed92..3230a4d5d2 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java @@ -233,7 +233,7 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid // We pass the complication id, so we can only update the specific complication tapped. final PendingIntent complicationPendingIntent = - ComplicationTapBroadcastReceiver.getTapActionIntent( + ComplicationTapBroadcastReceiver.Companion.getTapActionIntent( getApplicationContext(), thisProvider, complicationId, getComplicationAction()); final RawDisplayData raw = new RawDisplayData(); @@ -251,12 +251,14 @@ public abstract class BaseComplicationProviderService extends ComplicationProvid if (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) { // no new data arrived - probably configuration or connection error - final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent( + final PendingIntent infoToast = + ComplicationTapBroadcastReceiver.Companion.getTapWarningSinceIntent( getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated()); complicationData = buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated()); } else if (wearUtil.msSince(raw.getSingleBg().getTimeStamp()) > Constants.STALE_MS) { // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error) - final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent( + final PendingIntent infoToast = + ComplicationTapBroadcastReceiver.Companion.getTapWarningSinceIntent( getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.getSingleBg().getTimeStamp()); complicationData = buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.getSingleBg().getTimeStamp()); } else { 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 cd6f956720..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java +++ /dev/null @@ -1,180 +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.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.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; -import info.nightscout.shared.sharedPreferences.SP; - -/* - * Created by dlvoy on 2019-11-12 - */ -@SuppressWarnings("deprecation") -public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver { - - @Inject WearUtil wearUtil; - @Inject DisplayFormat displayFormat; - @Inject SP sp; - @Inject AAPSLogger aapsLogger; - - 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? - aapsLogger.error(LTag.WEAR, "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..0944960b3b --- /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.ECARB -> 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.ECARB + "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 From 8e59519a8aa6225eea12eafc4d9cf1ef4042e13a Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 22:52:04 +0200 Subject: [PATCH 47/54] ComplicationAction -> kt --- .../androidaps/complications/ComplicationAction.java | 12 ------------ .../androidaps/complications/ComplicationAction.kt | 5 +++++ .../ComplicationTapBroadcastReceiver.kt | 4 ++-- 3 files changed, 7 insertions(+), 14 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt 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.kt b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt index 0944960b3b..f8452ec35d 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt +++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt @@ -60,7 +60,7 @@ class ComplicationTapBroadcastReceiver : DaggerBroadcastReceiver() { return ComplicationAction.WIZARD -> intentOpen = Intent(context, WizardActivity::class.java) ComplicationAction.BOLUS -> intentOpen = Intent(context, TreatmentActivity::class.java) - ComplicationAction.ECARB -> intentOpen = Intent(context, ECarbActivity::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 -> { @@ -92,7 +92,7 @@ class ComplicationTapBroadcastReceiver : DaggerBroadcastReceiver() { "menu" -> ComplicationAction.MENU "wizard" -> ComplicationAction.WIZARD "bolus" -> ComplicationAction.BOLUS - "ecarb" -> ComplicationAction.ECARB + "ecarb" -> ComplicationAction.E_CARB "status" -> ComplicationAction.STATUS "none" -> ComplicationAction.NONE "default" -> originalAction From 5512f935ac86196145cae010cf684f4e27e6a0e4 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 2 May 2022 23:06:11 +0200 Subject: [PATCH 48/54] BaseComplicationProviderService -> kt --- .../BaseComplicationProviderService.java | 418 ------------------ .../BaseComplicationProviderService.kt | 380 ++++++++++++++++ 2 files changed, 380 insertions(+), 418 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt 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 3230a4d5d2..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ /dev/null @@ -1,418 +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.annotation.NonNull; -import androidx.annotation.Nullable; -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.comm.DataLayerListenerServiceWear; -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; - -/** - * Base class for all complications - *

- * Created by dlvoy on 2019-11-12 - */ -@SuppressWarnings("deprecation") -public abstract class BaseComplicationProviderService extends ComplicationProviderService { - - @Inject Inevitable inevitable; - @Inject WearUtil wearUtil; - @Inject DisplayFormat displayFormat; - @Inject Persistence persistence; - @Inject AAPSLogger aapsLogger; - @Inject RxBus rxBus; - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - private static final String TASK_ID_REFRESH_COMPLICATION = "refresh-complication"; - - - private LocalBroadcastManager localBroadcastManager; - private MessageReceiver messageReceiver; - - //============================================================================================== - // ABSTRACT COMPLICATION INTERFACE - //============================================================================================== - - public abstract @Nullable ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent); - - public abstract @NonNull 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(Persistence.KEY_COMPLICATIONS, "complication_" + complicationId); - - IntentFilter messageFilter = new IntentFilter(DataLayerListenerServiceWear.Companion.getINTENT_NEW_DATA()); - - messageReceiver = new MessageReceiver(); - localBroadcastManager = LocalBroadcastManager.getInstance(this); - localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - - rxBus.send(new EventWearToMobile(new EventData.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 - 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.Companion.getTapActionIntent( - getApplicationContext(), thisProvider, complicationId, getComplicationAction()); - - final RawDisplayData raw = new 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.getSingleBg().getTimeStamp())); - - // 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); - - ComplicationData complicationData; - - if (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) { - // no new data arrived - probably configuration or connection error - final PendingIntent infoToast = - ComplicationTapBroadcastReceiver.Companion.getTapWarningSinceIntent( - getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated()); - complicationData = buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated()); - } else if (wearUtil.msSince(raw.getSingleBg().getTimeStamp()) > Constants.STALE_MS) { - // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error) - final PendingIntent infoToast = - ComplicationTapBroadcastReceiver.Companion.getTapWarningSinceIntent( - getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.getSingleBg().getTimeStamp()); - complicationData = buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.getSingleBg().getTimeStamp()); - } 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(Persistence.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(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 void requestUpdateIfSinceChanged() { - final RawDisplayData raw = new RawDisplayData(); - raw.updateFromPersistence(persistence); - - final String lastSince = persistence.getString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, "-"); - final String calcSince = displayFormat.shortTimeSince(raw.getSingleBg().getTimeStamp()); - final boolean isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) - || (wearUtil.msSince(raw.getSingleBg().getTimeStamp()) > Constants.STALE_MS); - - final boolean staleWasRefreshed = persistence.getBoolean(Persistence.KEY_STALE_REPORTED, false); - final boolean sinceWasChanged = !lastSince.equals(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: " - + (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(Persistence.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(Persistence.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) { - updateAll(); - } - } - - private void updateAll() { - Set complications = persistence.getSetOf(Persistence.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 From 787bd4a074049f06e186d72f646f9a8098e57e06 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 3 May 2022 20:33:34 +0200 Subject: [PATCH 49/54] fix tests --- .../interaction/utils/Persistence.kt | 12 +-- .../interaction/utils/WearUtil.java | 2 - .../info/nightscout/androidaps/TestBase.kt | 22 +---- .../interaction/utils/PersistenceTest.java | 92 ------------------- 4 files changed, 6 insertions(+), 122 deletions(-) delete mode 100644 wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java 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 index a41a0b5453..bfad5b3571 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt @@ -37,16 +37,6 @@ class Persistence @Inject constructor( } - // For mocking only - fun base64decode(str: String, flags: Int): ByteArray { - return Base64.decode(str, flags) - } - - // For mocking only - fun base64encodeToString(input: ByteArray, flags: Int): String { - return Base64.encodeToString(input, flags) - } - fun getString(key: String, defaultValue: String): String { return sp.getString(key, defaultValue) } @@ -177,7 +167,7 @@ class Persistence @Inject constructor( 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("\\Q$separator\\E").toTypedArray() + val items = joined.split(Regex("\\Q$separator\\E")).toTypedArray() val set: MutableSet = HashSet() for (item in items) { val itemToAdd = item.trim { it <= ' ' } 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 index 5f22657035..38bb5b011e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java @@ -6,7 +6,6 @@ import android.os.PowerManager; import com.google.android.gms.wearable.DataMap; -import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -32,7 +31,6 @@ public class WearUtil { private final boolean debug_wakelocks = false; private final Map rateLimits = new HashMap<>(); - private final String TAG = WearUtil.class.getName(); //============================================================================================== // Time related util methods 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/interaction/utils/PersistenceTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java deleted file mode 100644 index dcfbf5235e..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java +++ /dev/null @@ -1,92 +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.assertTrue; - -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 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")); - } - -} From 37cee04926eb816c78058a8eb031d52bc119cd5c Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 3 May 2022 20:46:41 +0200 Subject: [PATCH 50/54] tests -> kt --- .../interaction/utils/DisplayFormatTest.java | 206 ------------------ .../interaction/utils/DisplayFormatTest.kt | 168 ++++++++++++++ .../interaction/utils/PairTest.java | 64 ------ .../androidaps/interaction/utils/PairTest.kt | 48 ++++ .../testing/mockers/RawDataMocker.java | 141 ------------ .../testing/mockers/RawDataMocker.kt | 118 ++++++++++ .../testing/mockers/WearUtilMocker.java | 102 --------- .../testing/mockers/WearUtilMocker.kt | 87 ++++++++ .../androidaps/testing/mocks/IntentMock.java | 40 ---- .../testing/mocks/SharedPreferencesMock.java | 159 -------------- .../testing/mocks/SharedPreferencesMock.kt | 123 +++++++++++ 11 files changed, 544 insertions(+), 712 deletions(-) delete mode 100644 wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java create mode 100644 wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt delete mode 100644 wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java create mode 100644 wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java create mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java create mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mocks/IntentMock.java delete mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.java create mode 100644 wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.kt 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 d563cdcddb..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(); - assertEquals(displayFormat.shortTrend(raw), "-- Δ--"); - - raw.getSingleBg().setTimeStamp(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/testing/mockers/RawDataMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java deleted file mode 100644 index b6aa2318e9..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java +++ /dev/null @@ -1,141 +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; -import info.nightscout.shared.weardata.EventData; - -@SuppressWarnings("PointlessArithmeticExpression") -public class RawDataMocker { - - private final WearUtilMocker wearUtilMocker; - - public RawDataMocker(WearUtil wearUtil) { - wearUtilMocker = new WearUtilMocker(wearUtil); - } - - public RawDisplayData rawSgv(String sgv, int m, String deltaString) { - RawDisplayData raw = new RawDisplayData(); - double delta = SafeParse.stringToDouble(deltaString); - String d; - - if (delta <= (-3.5 * 5)) { - d = "\u21ca"; - } else if (delta <= (-2 * 5)) { - d = "\u2193"; - } else if (delta <= (-1 * 5)) { - d = "\u2198"; - } else if (delta <= (1 * 5)) { - d = "\u2192"; - } else if (delta <= (2 * 5)) { - d = "\u2197"; - } else if (delta <= (3.5 * 5)) { - d = "\u2191"; - } else { - d = "\u21c8"; - } - raw.setSingleBg( - new EventData.SingleBg( - wearUtilMocker.backInTime(0, 0, m, 0), - sgv, - "", - d, - deltaString, - "", - 0, - 0.0, - 0.0, - 0.0, - 0 - ) - ); - return raw; - } - - public RawDisplayData rawDelta(int m, String delta) { - RawDisplayData raw = new RawDisplayData(); - raw.setSingleBg( - new EventData.SingleBg( - wearUtilMocker.backInTime(0, 0, m, 0), - "", - "", - "", - delta, - "", - 0, - 0.0, - 0.0, - 0.0, - 0 - ) - ); - return raw; - } - - public RawDisplayData rawCobIobBr(String cob, String iob, String br) { - RawDisplayData raw = new RawDisplayData(); - raw.setStatus( - new EventData.Status( - "", - iob, - "", - true, - cob, - br, - "", - "", - 0L, - "", - true, - 0 - - ) - ); - return raw; - } - - public RawDisplayData rawIob(String iob, String iob2) { - RawDisplayData raw = new RawDisplayData(); - raw.setStatus( - new EventData.Status( - "", - iob, - iob2, - true, - "", - "", - "", - "", - 0L, - "", - true, - 0 - - ) - ); - return raw; - } - - public RawDisplayData rawCob(String cob) { - RawDisplayData raw = new RawDisplayData(); - raw.setStatus( - new EventData.Status( - "", - "", - "", - true, - cob, - "", - "", - "", - 0L, - "", - true, - 0 - - ) - ); - 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..c9fa0b1ca5 --- /dev/null +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt @@ -0,0 +1,87 @@ +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()) + Mockito.doAnswer(bundleToDataMapMock).`when`(wearUtil).bundleToDataMap(ArgumentMatchers.any()) + } + + 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.isEmpty()) { + 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 From 3c292e711fcc18bb774077d489d505ae373fd16c Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 3 May 2022 23:05:17 +0200 Subject: [PATCH 51/54] utils -> kt --- .../interaction/utils/Constants.java | 14 --- .../androidaps/interaction/utils/Constants.kt | 13 ++ .../interaction/utils/DisplayFormat.java | 21 ++-- .../interaction/utils/Inevitable.java | 115 ------------------ .../interaction/utils/Inevitable.kt | 103 ++++++++++++++++ .../androidaps/interaction/utils/Pair.java | 43 ------- .../androidaps/interaction/utils/Pair.kt | 21 ++++ .../interaction/utils/WearUtil.java | 96 --------------- .../androidaps/interaction/utils/WearUtil.kt | 82 +++++++++++++ .../testing/mockers/WearUtilMocker.kt | 2 +- 10 files changed, 231 insertions(+), 279 deletions(-) delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.kt delete mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java create mode 100644 wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt 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 966b921db5..e74b659446 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 @@ -74,12 +75,12 @@ public class DisplayFormat { } // that only optimizes obvious things like 0 before . or at end, + at beginning - String delta = (new SmallestDoubleString(raw.getSingleBg().getDelta())).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.getSingleBg().getDelta())).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; } @@ -96,7 +97,7 @@ public class DisplayFormat { final String SEP_MIN = " "; String line = - raw.getStatus().getCob() + SEP_LONG + raw.getStatus().getIobSum() + SEP_LONG + basalRateSymbol()+raw.getStatus().getCurrentBasal(); + raw.getStatus().getCob() + SEP_LONG + raw.getStatus().getIobSum() + SEP_LONG + basalRateSymbol() + raw.getStatus().getCurrentBasal(); if (line.length() <= MAX_FIELD_LEN_LONG) { return line; } @@ -105,14 +106,14 @@ public class DisplayFormat { return line; } - int remainingMax = MAX_FIELD_LEN_LONG - (raw.getStatus().getCob().length() + raw.getStatus().getCurrentBasal().length() + SEP_SHORT_LEN*2); + 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.getStatus().getCurrentBasal().length() + SEP_SHORT_LEN*2); + 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.getStatus().getCurrentBasal(); @@ -135,13 +136,13 @@ public class DisplayFormat { 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 new Pair(iob1, iob2); } public Pair detailedCob(final RawDisplayData raw) { @@ -152,6 +153,6 @@ public class DisplayFormat { cob2 = cobMini.getExtra() + cobMini.getUnits(); } final String cob1 = cobMini.minimise(MAX_FIELD_LEN_SHORT); - return Pair.create(cob1, cob2); + return new Pair(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 5a268d3b7e..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java +++ /dev/null @@ -1,115 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.os.PowerManager; - -import java.util.concurrent.ConcurrentHashMap; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; - -/** - * 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 AAPSLogger aapsLogger; - @Inject DateUtil dateUtil; - - @Inject Inevitable() {} - - 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) - 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.put(id, new Task(id, idle_for, runnable)); - - if (debug) { - aapsLogger.debug(LTag.WEAR, - "Creating task: " + id + " due: " + dateUtil.dateAndTimeAndSecondsString(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 kill(final String id) { - tasks.remove(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) aapsLogger.debug(LTag.WEAR, "Executing task! " + this.id); - tasks.remove(this.id); // early remove to allow overlapping scheduling - what.run(); - return true; - } else if (till > MAX_QUEUE_TIME) { - aapsLogger.debug(LTag.WEAR, "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/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/WearUtil.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java deleted file mode 100644 index 38bb5b011e..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java +++ /dev/null @@ -1,96 +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.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<>(); - - //============================================================================================== - // Time related util methods - //============================================================================================== - - 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..9945246c50 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt @@ -0,0 +1,82 @@ +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 + } + } + + /** + * Taken out to helper method to allow testing + */ + fun bundleToDataMap(bundle: Bundle?): DataMap { + return DataMap.fromBundle(bundle) + } +} \ No newline at end of file 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 index c9fa0b1ca5..27199dc97c 100644 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt @@ -64,7 +64,7 @@ class WearUtilMocker(private val wearUtil: WearUtil) { if (v is String) map.putString(key, v) if (v is Array<*>) map.putStringArray(key, v as Array) if (v is ArrayList<*>) { - if (!v.isEmpty()) { + if (v.isNotEmpty()) { if (v[0] is Int) { map.putIntegerArrayList(key, v as ArrayList) } From 57d42431cc36b9fba0322497538e22ff94099327 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 3 May 2022 23:12:54 +0200 Subject: [PATCH 52/54] resolve warnings --- .../androidaps/interaction/utils/DisplayFormat.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 e74b659446..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 @@ -142,7 +142,7 @@ public class DisplayFormat { } iob2 = iobBolus + " " + iobBasal; } - return new Pair(iob1, iob2); + return Pair.Companion.create(iob1, iob2); } public Pair detailedCob(final RawDisplayData raw) { @@ -153,6 +153,6 @@ public class DisplayFormat { cob2 = cobMini.getExtra() + cobMini.getUnits(); } final String cob1 = cobMini.minimise(MAX_FIELD_LEN_SHORT); - return new Pair(cob1, cob2); + return Pair.Companion.create(cob1, cob2); } } From 5a8828334439107cf30ec7e6ed780b2867d26bc4 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 4 May 2022 21:18:28 +0200 Subject: [PATCH 53/54] remove unused code --- .../nightscout/androidaps/interaction/utils/WearUtil.kt | 7 ------- .../androidaps/testing/mockers/WearUtilMocker.kt | 1 - 2 files changed, 8 deletions(-) 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 index 9945246c50..1311e2dce6 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt @@ -72,11 +72,4 @@ class WearUtil @Inject constructor() { // we simply ignore if sleep was interrupted } } - - /** - * Taken out to helper method to allow testing - */ - fun bundleToDataMap(bundle: Bundle?): DataMap { - return DataMap.fromBundle(bundle) - } } \ No newline at end of file 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 index 27199dc97c..5453200be2 100644 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt @@ -25,7 +25,6 @@ class WearUtilMocker(private val wearUtil: WearUtil) { resetClock() Mockito.doAnswer { invocation: InvocationOnMock? -> REF_NOW + clockMsDiff }.`when`(wearUtil).timestamp() Mockito.doReturn(null).`when`(wearUtil).getWakeLock(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()) - Mockito.doAnswer(bundleToDataMapMock).`when`(wearUtil).bundleToDataMap(ArgumentMatchers.any()) } fun resetClock() { From b42167666f5dd19b3b171e5538e389e436be27bc Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 4 May 2022 22:20:18 +0200 Subject: [PATCH 54/54] remove unused code --- .../interaction/utils/WearUtilTest.kt | 22 ------------------- 1 file changed, 22 deletions(-) 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 3c4fbe283a..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 @@ -122,26 +122,4 @@ class WearUtilTest : TestBase() { 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