From 3a6a51c3b1e628961501b9381d228aaf11787e90 Mon Sep 17 00:00:00 2001 From: olorinmaia Date: Tue, 27 Oct 2026 19:09:59 +0100 Subject: [PATCH 1/6] Wear: the "time to eat" timer on the watch, and a carb time page in the wizard The timer the phone starts after a bolus never reached the watch: nothing was sent, and its notifications are ongoing ones, which Wear OS does not bridge. Now the phone sends the timer's start and end with every status, also from a client's copy. The watch draws a dashed line at the end in its BG graph, on the graph screen and the tile, with the minutes left at it. The watch sets its own alarm at that time and rings by itself, so it rings with the phone out of reach too: a vibrating notification with Silence and +5 min, and a screen with the same two buttons over it. Both go to the phone, which stops or moves the timer; a client relays to its master. The next status closes the screen. The watch wizard gets a carb time page behind a new watch setting, off by default, next to the meal type one: minutes until the carbs are eaten, with a "Set alarm" bell that is on by default once the time is positive. The phone starts the timer after the bolus and moves the meal type's eCarbs with the meal, as its own wizard does. The custom watchface graph and the V4 face do not show the timer yet. --- .../core/interfaces/rx/weardata/EventData.kt | 21 ++- .../aaps/plugins/sync/wear/WearPluginTest.kt | 22 ++- .../DataHandlerMobileWearBolusTest.kt | 34 ++++ .../app/aaps/plugins/sync/wear/WearPlugin.kt | 4 + .../wear/wearintegration/DataHandlerMobile.kt | 36 +++- wear/src/main/AndroidManifest.xml | 12 ++ .../app/aaps/wear/comm/DataHandlerWear.kt | 6 +- .../app/aaps/wear/di/WearMemberInjectors.kt | 14 ++ .../wear/eatreminder/EatReminderActivity.kt | 129 +++++++++++++ .../wear/eatreminder/EatReminderReceiver.kt | 29 +++ .../aaps/wear/eatreminder/EatReminderWatch.kt | 172 ++++++++++++++++++ .../actions/PlusMinusInputScreen.kt | 4 + .../interaction/actions/WizardActivity.kt | 98 +++++++++- .../interaction/activities/BgGraphActivity.kt | 14 +- .../interaction/activities/BgGraphRenderer.kt | 45 ++++- .../app/aaps/wear/tile/BgGraphTileService.kt | 2 +- wear/src/main/res/values/strings.xml | 11 ++ .../main/res/xml/interface_preferences.xml | 9 + .../app/aaps/wear/comm/DataHandlerWearTest.kt | 4 +- 19 files changed, 644 insertions(+), 22 deletions(-) create mode 100644 wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt create mode 100644 wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt create mode 100644 wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt index 38ea55b79128..c641d7ce7a70 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt @@ -1,5 +1,6 @@ package app.aaps.core.interfaces.rx.weardata +import app.aaps.core.interfaces.alerts.EatReminderAction import app.aaps.core.data.model.CarbsType import app.aaps.core.interfaces.rx.events.Event import kotlinx.serialization.ExperimentalSerializationApi @@ -124,9 +125,12 @@ sealed class EventData : Event() { @Serializable data class ActionProfileSwitchPreCheck(val timeShift: Int, val percentage: Int, val duration: Int) : EventData() + /** + * [carbsType] came later. A watch without it sends none, and bread is what it did before: all carbs now, no eCarbs. + * [carbTime] is minutes from now until the carbs are eaten, as on the phone, and [alarm] starts the "time to eat" timer then. + */ @Serializable - /** [carbsType] came later. A watch without it sends none, and bread is what it did before: all carbs now, no eCarbs. */ - data class ActionWizardPreCheck(val carbs: Int, val percentage: Int, val carbsType: CarbsType = CarbsType.BREAD) : EventData() + data class ActionWizardPreCheck(val carbs: Int, val percentage: Int, val carbsType: CarbsType = CarbsType.BREAD, val carbTime: Int = 0, val alarm: Boolean = false) : EventData() @Serializable data class ActionQuickWizardPreCheck(val guid: String) : EventData() @@ -437,7 +441,11 @@ sealed class EventData : Event() { // End time (epoch ms) of a temporary running mode (suspend/disconnect/superbolus); null when permanent or older sender val modeEndTime: Long? = null, // Whether the active scene set the running mode, so the picker can mark it; false from an older sender - val modeFromScene: Boolean = false + val modeFromScene: Boolean = false, + // The "time to eat" timer: when it was started and when it rings. Null when none runs, or from an older sender. + // The watch draws the end in its BG graph and rings itself at that time. + val eatReminderStartedAt: Long? = null, + val eatReminderEndsAt: Long? = null ) : EventData(), EventDataSet @Serializable @@ -601,6 +609,13 @@ sealed class EventData : Event() { @Serializable data class SnoozeAlert(val timeStamp: Long) : EventData() + /** + * Stop or +5 min of the "time to eat" timer, from the watch's ring screen. The phone runs it on the + * master, a client relays it to its master. + */ + @Serializable + data class ActionEatReminder(val action: EatReminderAction) : EventData() + // Wear -> Wear (workaround) @Serializable data class RunningModePreSelect( diff --git a/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt b/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt index 81b5b472083d..f239ce718fec 100644 --- a/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt +++ b/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/WearPluginTest.kt @@ -7,6 +7,8 @@ import app.aaps.core.interfaces.pump.BolusProgressData import app.aaps.core.interfaces.rx.events.EventAutosensCalculationFinished import app.aaps.core.interfaces.rx.events.EventLoopUpdateGui import app.aaps.core.interfaces.rx.events.EventNsClientStatusUpdated +import app.aaps.core.interfaces.alerts.EatReminder +import app.aaps.core.interfaces.alerts.EatReminderState import app.aaps.core.interfaces.scenes.SceneAutomationApi import app.aaps.plugins.sync.tidepool.utils.RateLimit import app.aaps.plugins.sync.wear.wearintegration.DataHandlerMobile @@ -16,6 +18,7 @@ import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher @@ -36,16 +39,19 @@ class WearPluginTest : TestBaseWithProfile() { @Mock lateinit var dataLayerListenerServiceMobileHelper: DataLayerListenerServiceMobileHelper @Mock lateinit var persistenceLayer: PersistenceLayer @Mock lateinit var scenes: SceneAutomationApi + @Mock lateinit var eatReminder: EatReminder private lateinit var wearPlugin: WearPlugin private lateinit var rateLimit: RateLimit private val temporaryTargets = MutableSharedFlow>() private val runningModes = MutableSharedFlow>() + private val eatReminderState = MutableStateFlow(null) @BeforeEach fun prepare() { rateLimit = RateLimit(dateUtil) - wearPlugin = WearPlugin(aapsLogger, rh, preferences, rxBus, context, dataHandlerMobile, dataLayerListenerServiceMobileHelper, config, BolusProgressData(ch, CoroutineScope(Dispatchers.Unconfined)), persistenceLayer, scenes, mock()) + whenever(eatReminder.state).thenReturn(eatReminderState) + wearPlugin = WearPlugin(aapsLogger, rh, preferences, rxBus, context, dataHandlerMobile, dataLayerListenerServiceMobileHelper, config, BolusProgressData(ch, CoroutineScope(Dispatchers.Unconfined)), persistenceLayer, scenes, eatReminder, mock()) whenever(persistenceLayer.observeChanges(TT::class)).thenReturn(temporaryTargets) whenever(persistenceLayer.observeChanges(RM::class)).thenReturn(runningModes) } @@ -149,4 +155,18 @@ class WearPluginTest : TestBaseWithProfile() { assertThat(reasons).containsExactly("EventLoopUpdateGui") } + + @Test + fun `a change of the eat reminder is resent at once, its first value is not a change`() = runTest { + val reasons = collectResends() + advanceTimeBy(10.seconds) + runCurrent() + assertThat(reasons).isEmpty() + + eatReminderState.value = EatReminderState(startedAt = 1_000L, endsAt = 901_000L, durationMs = 900_000L) + advanceTimeBy(5.seconds) + runCurrent() + + assertThat(reasons).containsExactly("EatReminderChange") + } } diff --git a/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobileWearBolusTest.kt b/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobileWearBolusTest.kt index fb1e80f50f7f..cea898754d49 100644 --- a/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobileWearBolusTest.kt +++ b/plugins/sync/src/androidHostTest/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobileWearBolusTest.kt @@ -364,6 +364,40 @@ class DataHandlerMobileWearBolusTest : TestBaseWithProfile() { assertThat(inputs.eCarbsDelayMinutes).isEqualTo(60) assertThat(inputs.eCarbsDurationHours).isEqualTo(3) } + + @Test fun `wizard precheck with a carb time starts the eat reminder and moves the eCarbs with the meal`() = runTest { + // The watch's carb time page: the carbs come 15 min later and the alarm is on. The eCarbs of the + // meal type start relative to the meal, as on the phone (60 + 15). + val ads = mock() + whenever(iobCobCalculator.ads).thenReturn(ads) + whenever(ads.actualBg()).thenReturn(mock()) + whenever(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) + whenever(preferences.get(any())).thenReturn(true) + stubWizardPrepared(555L, lines = emptyList()) + capturedConfirm { sut.handleWizardPreCheck(EventData.ActionWizardPreCheck(carbs = 65, percentage = 100, carbsType = CarbsType.PIZZA, carbTime = 15, alarm = true)) } + val captor = argumentCaptor() + verifyBlocking(wizardExecutor) { prepare(captor.capture(), any()) } + val inputs = (captor.firstValue as WizardExecutor.WizardSource.Manual).inputs + assertThat(inputs.carbTime).isEqualTo(15) + assertThat(inputs.alarm).isTrue() + assertThat(inputs.eCarbsDelayMinutes).isEqualTo(75) + } + + @Test fun `wizard precheck drops the alarm when the carbs are not later`() = runTest { + // Nothing to wait for: the alarm only counts with a carb time in the future. + val ads = mock() + whenever(iobCobCalculator.ads).thenReturn(ads) + whenever(ads.actualBg()).thenReturn(mock()) + whenever(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) + whenever(preferences.get(any())).thenReturn(true) + stubWizardPrepared(555L, lines = emptyList()) + capturedConfirm { sut.handleWizardPreCheck(EventData.ActionWizardPreCheck(carbs = 30, percentage = 100, carbTime = 0, alarm = true)) } + val captor = argumentCaptor() + verifyBlocking(wizardExecutor) { prepare(captor.capture(), any()) } + val inputs = (captor.firstValue as WizardExecutor.WizardSource.Manual).inputs + assertThat(inputs.carbTime).isEqualTo(0) + assertThat(inputs.alarm).isFalse() + } // --- QuickWizard tile modes (branch on entry.mode() exactly like the phone's MainViewModel) ----------- // // The wear QuickWizard handler used to ALWAYS recompute via WizardExecutor, so a fixed INSULIN button diff --git a/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt b/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt index 1fa64bd306c4..ed2e5c3f940a 100644 --- a/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt +++ b/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/WearPlugin.kt @@ -31,6 +31,7 @@ import app.aaps.core.interfaces.rx.events.EventWearUpdateTiles import app.aaps.core.interfaces.rx.weardata.CwfData import app.aaps.core.interfaces.rx.weardata.CwfMetadataKey import app.aaps.core.interfaces.rx.weardata.EventData +import app.aaps.core.interfaces.alerts.EatReminder import app.aaps.core.interfaces.scenes.SceneAutomationApi import app.aaps.core.keys.BooleanKey import app.aaps.core.keys.DoubleKey @@ -89,6 +90,7 @@ class WearPlugin( private val bolusProgressData: BolusProgressData, private val persistenceLayer: PersistenceLayer, private val scenes: SceneAutomationApi, + private val eatReminder: EatReminder, notificationManager: NotificationManager, ) : PluginBaseWithPreferences( pluginDescription = PluginDescription() @@ -240,6 +242,8 @@ class WearPlugin( forward(rxBus.toFlow(EventNsClientStatusUpdated::class), "EventNsClientStatusUpdated") // Push status to watch quickly when a TT changes, without waiting for the loop's 10s debounce forward(persistenceLayer.observeChanges().drop(1), "TempTargetChange") // drop: the initial emission on collection start + // The "time to eat" timer: the watch draws its end and rings at it, so a start, stop or +5 min goes out at once + forward(eatReminder.state.drop(1), "EatReminderChange") // drop: the current state on collection start // Push status to watch quickly when the running mode changes on the phone, so the // running-mode complication and tile do not wait for the next loop run. A wear-side // change already refreshes through handleRunningModeConfirmed. diff --git a/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt b/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt index 250412023fdb..ffc652c26a78 100644 --- a/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataHandlerMobile.kt @@ -34,7 +34,6 @@ import app.aaps.core.interfaces.bolus.BatchAction import app.aaps.core.interfaces.bolus.BatchExecutor import app.aaps.core.interfaces.bolus.MasterActionExecutor import app.aaps.core.interfaces.bolus.WizardExecutor -import app.aaps.core.interfaces.clientcontrol.ActionProgress import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.constraints.ConstraintsChecker import app.aaps.core.interfaces.db.PersistenceLayer @@ -73,6 +72,10 @@ import app.aaps.core.interfaces.rx.weardata.ProfileInfo import app.aaps.core.interfaces.rx.weardata.TargetRange import app.aaps.core.interfaces.rx.weardata.TempTargetInfo import app.aaps.core.interfaces.scenes.ActiveSceneSync +import app.aaps.core.interfaces.alerts.EatReminder +import app.aaps.core.interfaces.alerts.EatReminderAction +import app.aaps.core.interfaces.clientcontrol.ActionProgress +import app.aaps.core.interfaces.clientcontrol.ClientControlActionDispatcher import app.aaps.core.interfaces.scenes.SceneActions import app.aaps.core.interfaces.scenes.SceneAutomationApi import app.aaps.core.interfaces.scenes.SceneAutomationResult @@ -180,6 +183,8 @@ class DataHandlerMobile( @Inject lateinit var activeSceneSync: ActiveSceneSync @Inject lateinit var sceneChainResolver: SceneChainResolver @Inject lateinit var sensitivityOverview: SensitivityOverview + @Inject lateinit var eatReminder: EatReminder + @Inject lateinit var clientControlDispatcher: ClientControlActionDispatcher // App lifetime: this is a @Singleton that subscribes in init and // never tears down. Dispatchers.IO because that is what the io scheduler gave these handlers, and @@ -395,6 +400,8 @@ class DataHandlerMobile( onCommitResult(sceneActions.stop(triggerChain = it.triggerChain)) } onEventSync { uiInteraction.stopAlarm("Muted from wear") } + // Not gated by the wear control switch, like the mute above: it only ends or moves a reminder + onEvent { handleEatReminder(it) } onEventSync { fabricPrivacy.logWearException(it) } // Coalesce Wear reconnect-flush bursts (Data Layer replays queued events back-to-back). // chunkedOnQuietPeriod keeps the timer idle when no events arrive, unlike a fixed window. @@ -706,16 +713,17 @@ class DataHandlerMobile( carbs = command.carbsType.carbsNow(command.carbs), percentage = command.percentage, directCorrection = 0.0, - carbTime = 0, + carbTime = command.carbTime, useBg = preferences.get(BooleanKey.WearWizardBg), useCob = preferences.get(BooleanKey.WearWizardCob), useIob = preferences.get(BooleanKey.WearWizardIob), useTt = preferences.get(BooleanKey.WearWizardTt), useTrend = preferences.get(BooleanKey.WearWizardTrend), - alarm = false, + alarm = command.alarm && command.carbTime > 0, notes = "", eCarbsGrams = command.carbsType.eCarbs(command.carbs), - eCarbsDelayMinutes = command.carbsType.eCarbsDelayMinutes, + // The eCarbs start relative to the meal, as on the phone + eCarbsDelayMinutes = command.carbsType.eCarbsDelayMinutes + command.carbTime, eCarbsDurationHours = command.carbsType.eCarbsDurationHours, source = Sources.Wear ) @@ -1625,6 +1633,8 @@ class DataHandlerMobile( // Current running mode (+ end time of a temporary one) for the running-mode complication and picker val runningModeRecord = loop.runningModeRecord() + // The "time to eat" timer, on a client the copy of the master's + val eatReminderState = eatReminder.state.value sendToWear( EventData.Status( @@ -1649,7 +1659,9 @@ class DataHandlerMobile( reservoirLevel = reservoirLevel, loopMode = runningModeRecord.mode.toLoopMode(), modeEndTime = runningModeRecord.endTimeForWatch(), - modeFromScene = runningModeRecord.id == activeSceneSync.getActiveState()?.scopedRecords?.rmId + modeFromScene = runningModeRecord.id == activeSceneSync.getActiveState()?.scopedRecords?.rmId, + eatReminderStartedAt = eatReminderState?.startedAt, + eatReminderEndsAt = eatReminderState?.endsAt ) ) } @@ -1851,6 +1863,20 @@ class DataHandlerMobile( return status } + /** Stop or +5 min from the watch. On a master the timer changes here; a client asks its master, as its own bar does. */ + private suspend fun handleEatReminder(command: EventData.ActionEatReminder) { + clientControlDispatcher.execute( + ClientControlActionDispatcher.Command.EatReminderControl(command.action), + rh.gs(CoreUiStrings.clientcontrol_action_eat_reminder) + ) { + when (command.action) { + EatReminderAction.STOP -> eatReminder.stop() + EatReminderAction.EXTEND -> eatReminder.extend() + } + ActionProgress.Applied + } + } + private fun sendError(errorMessage: String) { sendToWear(EventData.ConfirmAction(rh.gs(CoreUiStrings.error), errorMessage, returnCommand = EventData.Error(dateUtil.now()))) // ignore return path } diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index f81253c8599a..608c40f3bf08 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -911,6 +911,18 @@ android:exported="false" android:taskAffinity="" android:theme="@style/WearAppCompatDark" /> + + + ): MembersInjector<*> = injector + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(EatReminderActivity::class) + fun bindEatReminderActivity(injector: MembersInjector): MembersInjector<*> = injector + + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(EatReminderReceiver::class) + fun bindEatReminderReceiver(injector: MembersInjector): MembersInjector<*> = injector + @Provides @FeatureMemberInjectors @IntoMap diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt new file mode 100644 index 000000000000..8ecb2fd71c95 --- /dev/null +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt @@ -0,0 +1,129 @@ +package app.aaps.wear.eatreminder + +import android.os.Bundle +import android.os.VibrationEffect +import android.os.Vibrator +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.wear.compose.material3.Button +import androidx.wear.compose.material3.ButtonDefaults +import androidx.wear.compose.material3.Icon +import androidx.wear.compose.material3.MaterialTheme +import androidx.wear.compose.material3.Text +import app.aaps.core.interfaces.alerts.EatReminder +import app.aaps.wear.R +import app.aaps.wear.di.WearMetroActivity +import app.aaps.wear.interaction.actions.CarbsOrange +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.delay + +/** + * The "time to eat" timer rang: the watch vibrates and offers Silence and +5 min. Both go to the phone + * through [EatReminderWatch]. The screen is closed by it when the phone ends or moves the timer. + * + * Opened from a broadcast receiver, which Android may refuse from the background; the notification + * [EatReminderWatch] posts at the same time has the same two buttons, so nothing is lost then. + */ +class EatReminderActivity : WearMetroActivity() { + + @Inject lateinit var eatReminderWatch: EatReminderWatch + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + current = this + setShowWhenLocked(true) + setTurnScreenOn(true) + val vibrator = getSystemService(Vibrator::class.java) + vibrator?.vibrate(VibrationEffect.createWaveform(RING_PATTERN, 0)) + setContent { + MaterialTheme { + // The screen stays until the user acts, the vibration does not + LaunchedEffect(Unit) { + delay(VIBRATE_MS) + vibrator?.cancel() + } + EatReminderScreen( + onSilence = { eatReminderWatch.silence() }, + onExtend = { eatReminderWatch.extend() } + ) + } + } + } + + override fun onDestroy() { + super.onDestroy() + getSystemService(Vibrator::class.java)?.cancel() + if (current === this) current = null + } + + companion object { + + private val RING_PATTERN = longArrayOf(0, 500, 300, 500, 1500) + private const val VIBRATE_MS = 60_000L + + // One screen at a time, so the phone's answer can close it + @Volatile private var current: EatReminderActivity? = null + + fun close() { + current?.finish() + } + } +} + +@Composable +private fun EatReminderScreen(onSilence: () -> Unit, onExtend: () -> Unit) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 24.dp, vertical = 8.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Icon( + painter = painterResource(R.drawable.ic_alarm), + contentDescription = null, + tint = CarbsOrange, + modifier = Modifier.size(28.dp) + ) + Spacer(Modifier.height(4.dp)) + Text( + text = stringResource(R.string.eat_reminder_title), + color = Color.White, + fontSize = 18.sp, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center + ) + Spacer(Modifier.height(12.dp)) + Button( + onClick = onSilence, + modifier = Modifier.fillMaxWidth(), + colors = ButtonDefaults.buttonColors(containerColor = Color.White.copy(alpha = 0.15f), contentColor = Color.White), + label = { Text(stringResource(R.string.eat_reminder_silence)) } + ) + Spacer(Modifier.height(8.dp)) + Button( + onClick = onExtend, + modifier = Modifier.fillMaxWidth(), + colors = ButtonDefaults.buttonColors(containerColor = CarbsOrange, contentColor = Color.Black), + label = { Text(stringResource(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES)) } + ) + } +} diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt new file mode 100644 index 000000000000..346081c6c6fe --- /dev/null +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt @@ -0,0 +1,29 @@ +package app.aaps.wear.eatreminder + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import app.aaps.core.interfaces.di.injectMetroMembers +import dev.zacsweers.metro.Inject + +/** The alarm of the "time to eat" timer, and the Silence and +5 min buttons of its notification. */ +class EatReminderReceiver : BroadcastReceiver() { + + @Inject lateinit var eatReminderWatch: EatReminderWatch + + override fun onReceive(context: Context, intent: Intent) { + context.injectMetroMembers(this) + when (intent.action) { + ACTION_RING -> eatReminderWatch.ring() + ACTION_STOP -> eatReminderWatch.silence() + ACTION_EXTEND -> eatReminderWatch.extend() + } + } + + companion object { + + const val ACTION_RING = "app.aaps.wear.eatReminder.RING" + const val ACTION_STOP = "app.aaps.wear.eatReminder.STOP" + const val ACTION_EXTEND = "app.aaps.wear.eatReminder.EXTEND" + } +} diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt new file mode 100644 index 000000000000..45771d0e57ba --- /dev/null +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt @@ -0,0 +1,172 @@ +package app.aaps.wear.eatreminder + +import android.app.AlarmManager +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.core.app.NotificationCompat +import app.aaps.core.interfaces.alerts.EatReminder +import app.aaps.core.interfaces.alerts.EatReminderAction +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.rx.bus.RxBus +import app.aaps.core.interfaces.rx.events.EventWearToMobile +import app.aaps.core.interfaces.rx.weardata.EventData +import app.aaps.core.interfaces.sharedPreferences.SP +import app.aaps.wear.R +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlin.math.abs +import kotlin.math.max + +/** + * The watch's copy of the phone's "time to eat" timer. + * + * The phone owns the timer and sends its end time with every status. The watch draws the end in its BG + * graph and sets its own alarm at that time, so it rings also when the phone is out of reach at that + * moment. The ring is a vibrating notification with Silence and +5 min, and [EatReminderActivity] over + * it. Both buttons go to the phone, which stops or moves the timer, and the next status brings the + * result back. Until then the watch acts on its own copy, so it reads right also with the phone away. + */ +@SingleIn(AppScope::class) +@Inject +class EatReminderWatch( + private val context: Context, + private val sp: SP, + private val rxBus: RxBus, + private val aapsLogger: AAPSLogger +) { + + private val alarmManager get() = context.getSystemService(AlarmManager::class.java) + private val notificationManager get() = context.getSystemService(NotificationManager::class.java) + + /** When the timer the watch knows rings, 0 when none runs. */ + val endsAt: Long get() = sp.getLong(R.string.key_eat_reminder_ends_at, 0L) + + /** + * The phone's timer, from a status. Null ends it. Returns true when the end time changed, so the + * caller can redraw the graph tile. + */ + fun onStatus(endsAt: Long?): Boolean { + val new = endsAt ?: 0L + if (new == this.endsAt) return false + sp.putLong(R.string.key_eat_reminder_ends_at, new) + // Whatever rang is over: the timer ended, or it was moved later + clearRing() + if (new == 0L) { + aapsLogger.debug(LTag.WEAR, "Eat reminder ended on the phone") + alarmManager.cancel(ringIntent()) + } else { + aapsLogger.debug(LTag.WEAR, "Eat reminder ends at $new") + schedule(new) + } + return true + } + + /** The alarm fired. Rings only for the timer the watch knows now, not for one that was moved or ended. */ + fun ring() { + val endsAt = this.endsAt + if (endsAt == 0L || abs(System.currentTimeMillis() - endsAt) > RING_TOLERANCE_MS) { + aapsLogger.debug(LTag.WEAR, "Eat reminder alarm ignored: no timer due now") + return + } + aapsLogger.debug(LTag.WEAR, "Eat reminder rings") + postRingNotification() + try { + context.startActivity( + Intent(context, EatReminderActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + ) + } catch (e: Exception) { + // Android may refuse a start from the background; the notification has the same buttons + aapsLogger.error(LTag.WEAR, "Eat reminder screen not opened", e) + } + } + + /** Silence: the timer ends. The phone silences its own alarm too. */ + fun silence() { + send(EatReminderAction.STOP) + sp.remove(R.string.key_eat_reminder_ends_at) + alarmManager.cancel(ringIntent()) + clearRing() + } + + /** + * +5 min: the end moves later, as on the phone: 5 minutes on top of the end while the timer runs, + * 5 minutes from now once it has rung. The phone's own answer comes with the next status. + */ + fun extend() { + send(EatReminderAction.EXTEND) + val newEnd = max(endsAt, System.currentTimeMillis()) + EXTEND_MS + sp.putLong(R.string.key_eat_reminder_ends_at, newEnd) + clearRing() + schedule(newEnd) + } + + private fun send(action: EatReminderAction) { + rxBus.send(EventWearToMobile(EventData.ActionEatReminder(action))) + } + + private fun schedule(endsAt: Long) { + // Long past: the phone rang while the watch was away, no use ringing here now + if (endsAt < System.currentTimeMillis() - RING_TOLERANCE_MS) return + // Exact, so a kitchen timer is not minutes late. The watch app targets API 30, so no permission is asked for + alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endsAt, ringIntent()) + } + + private fun clearRing() { + notificationManager.cancel(NOTIFICATION_ID) + EatReminderActivity.close() + } + + private fun postRingNotification() { + notificationManager.createNotificationChannel( + NotificationChannel(CHANNEL_ID, context.getString(R.string.eat_reminder_title), NotificationManager.IMPORTANCE_HIGH).apply { + enableVibration(true) + vibrationPattern = RING_VIBRATION + } + ) + val notification = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_alarm) + .setContentTitle(context.getString(R.string.eat_reminder_title)) + .setCategory(NotificationCompat.CATEGORY_ALARM) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .setContentIntent( + PendingIntent.getActivity( + context, OPEN_REQUEST_CODE, Intent(context, EatReminderActivity::class.java), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + ) + .addAction(0, context.getString(R.string.eat_reminder_silence), actionIntent(EatReminderReceiver.ACTION_STOP, STOP_REQUEST_CODE)) + .addAction(0, context.getString(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES), actionIntent(EatReminderReceiver.ACTION_EXTEND, EXTEND_REQUEST_CODE)) + .build() + notificationManager.notify(NOTIFICATION_ID, notification) + } + + private fun ringIntent(): PendingIntent = actionIntent(EatReminderReceiver.ACTION_RING, RING_REQUEST_CODE) + + private fun actionIntent(action: String, requestCode: Int): PendingIntent = + PendingIntent.getBroadcast( + context, requestCode, + Intent(context, EatReminderReceiver::class.java).setAction(action), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + + private companion object { + + const val CHANNEL_ID = "AndroidAPS-EatReminder" + const val NOTIFICATION_ID = 4720 + const val RING_REQUEST_CODE = 4720 + const val STOP_REQUEST_CODE = 4721 + const val EXTEND_REQUEST_CODE = 4722 + const val OPEN_REQUEST_CODE = 4723 + const val EXTEND_MS = EatReminder.EXTEND_MINUTES * 60_000L + + /** An alarm may come a little early or late; further from the end it belongs to an older timer. */ + const val RING_TOLERANCE_MS = 2 * 60_000L + val RING_VIBRATION = longArrayOf(0, 500, 300, 500, 300, 500) + } +} diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/PlusMinusInputScreen.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/PlusMinusInputScreen.kt index a556c95c8670..8c5b9e2e9f19 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/PlusMinusInputScreen.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/PlusMinusInputScreen.kt @@ -110,6 +110,8 @@ internal fun PlusMinusInputScreen( valueColor: Color = Color.White, stepLabels: List? = null, title: String? = null, + /** Drawn under the label, for a small control that belongs to the value, such as a switch. */ + footer: (@Composable () -> Unit)? = null, ) { val haptic = LocalHapticFeedback.current val focusRequester = remember { FocusRequester() } @@ -213,6 +215,7 @@ internal fun PlusMinusInputScreen( textAlign = TextAlign.Center, ) } + footer?.invoke() } StepButton(step = stepValues[0], isIncrement = true, onStep = ::step, enabled = enabled) } @@ -240,6 +243,7 @@ internal fun PlusMinusInputScreen( textAlign = TextAlign.Center, ) } + footer?.invoke() } // Bottom-left: decrement (fine step) diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt index 3f7431b6e55a..3dd615824d8a 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt @@ -53,23 +53,29 @@ import app.aaps.wear.R import app.aaps.wear.di.WearMetroActivity import dev.zacsweers.metro.Inject +/** The carb time page: the phone wizard's range and step. */ +private val CARB_TIME_RANGE = -60.0..60.0 +private const val CARB_TIME_STEP = 5.0 + class WizardActivity : WearMetroActivity() { @Inject lateinit var rxBus: RxBus @Inject lateinit var preferences: Preferences @Inject lateinit var sp: SP - /** The pages of the wizard, in order. Two of them are settings, so the list is built once per start. */ - private enum class Page { CARBS, CARBS_TYPE, PERCENTAGE, CONFIRM } + /** The pages of the wizard, in order. Three of them are settings, so the list is built once per start. */ + private enum class Page { CARBS, CARBS_TYPE, CARB_TIME, PERCENTAGE, CONFIRM } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val hasCarbsType = sp.getBoolean(getString(R.string.key_wizard_carbs_type), false) + val hasCarbTime = sp.getBoolean(getString(R.string.key_wizard_carb_time), false) val hasPercentage = sp.getBoolean(getString(R.string.key_wizard_percentage), false) val pages = buildList { add(Page.CARBS) if (hasCarbsType) add(Page.CARBS_TYPE) + if (hasCarbTime) add(Page.CARB_TIME) if (hasPercentage) add(Page.PERCENTAGE) add(Page.CONFIRM) } @@ -85,6 +91,10 @@ class WizardActivity : WearMetroActivity() { MaterialTheme { var carbs by remember { mutableStateOf(0.0) } var carbsType by remember { mutableStateOf(CarbsType.BREAD) } + // Minutes from now until the carbs are eaten, as on the phone. The alarm is the "time to eat" + // timer, on by default; it only counts when the carbs come later + var carbTime by remember { mutableStateOf(0.0) } + var alarm by remember { mutableStateOf(true) } var percentage by remember { mutableStateOf(defaultPercentage) } val pagerState = rememberPagerState(pageCount = { pages.size }) @@ -110,6 +120,23 @@ class WizardActivity : WearMetroActivity() { onSelect = { carbsType = it }, enabled = !pagerState.isScrollInProgress, ) + Page.CARB_TIME -> PlusMinusInputScreen( + value = carbTime, + onValueChange = { carbTime = it }, + valueRange = CARB_TIME_RANGE, + stepValues = listOf(CARB_TIME_STEP, CARB_TIME_STEP, CARB_TIME_STEP), + format = NumberFormat.INTEGER, + label = stringResource(R.string.wizard_carb_time), + displayText = if (carbTime == 0.0) stringResource(R.string.wizard_carb_time_now) else stringResource(R.string.wizard_carb_time_offset, carbTime.toInt()), + allowZero = true, + isActive = pagerState.currentPage == page, + simpleMode = true, + enabled = !pagerState.isScrollInProgress, + title = stringResource(R.string.menu_wizard), + footer = if (carbTime > 0) { + { AlarmToggle(checked = alarm, onToggle = { alarm = it }, enabled = !pagerState.isScrollInProgress) } + } else null, + ) Page.PERCENTAGE -> PlusMinusInputScreen( value = percentage, onValueChange = { percentage = it }, @@ -126,8 +153,12 @@ class WizardActivity : WearMetroActivity() { Page.CONFIRM -> WizardConfirmScreen( carbs = carbs.toInt(), carbsType = if (hasCarbsType) carbsType else null, + carbTime = if (hasCarbTime) carbTime.toInt() else 0, + alarm = alarm, percentage = if (hasPercentage) percentage.toInt() else null, - onConfirm = { confirmWizard(carbs.toInt(), percentage.toInt(), carbsType) }, + onConfirm = { + confirmWizard(carbs.toInt(), percentage.toInt(), carbsType, if (hasCarbTime) carbTime.toInt() else 0, alarm) + }, ) } } @@ -140,8 +171,8 @@ class WizardActivity : WearMetroActivity() { } } - private fun confirmWizard(carbs: Int, percentage: Int, carbsType: CarbsType) { - rxBus.send(EventWearToMobile(ActionWizardPreCheck(carbs, percentage, carbsType))) + private fun confirmWizard(carbs: Int, percentage: Int, carbsType: CarbsType, carbTime: Int, alarm: Boolean) { + rxBus.send(EventWearToMobile(ActionWizardPreCheck(carbs, percentage, carbsType, carbTime, alarm && carbTime > 0))) startActivity( Intent(this, ConfirmationActivity::class.java).apply { putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION) @@ -217,6 +248,37 @@ private fun CarbsTypeScreen(carbs: Int, selected: CarbsType, onSelect: (CarbsTyp } } +/** The "time to eat" alarm of the carb time page: a bell that is lit when the alarm is on. One tap flips it. */ +@Composable +private fun AlarmToggle(checked: Boolean, onToggle: (Boolean) -> Unit, enabled: Boolean) { + val haptic = LocalHapticFeedback.current + Row( + modifier = Modifier + .padding(top = 4.dp) + .clip(CircleShape) + .clickable(enabled = enabled) { + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) + onToggle(!checked) + } + .semantics { this.selected = checked } + .padding(horizontal = 8.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + painter = painterResource(R.drawable.ic_alarm), + contentDescription = null, + tint = if (checked) CarbsOrange else WearSecondaryText, + modifier = Modifier.size(16.dp) + ) + Spacer(Modifier.size(4.dp)) + Text( + text = stringResource(R.string.wizard_set_alarm), + color = if (checked) Color.White else WearSecondaryText, + fontSize = 12.sp + ) + } +} + private fun CarbsType.iconRes(): Int = when (this) { CarbsType.BREAD -> R.drawable.ic_bread CarbsType.CAKE -> R.drawable.ic_cake @@ -229,9 +291,12 @@ private fun CarbsType.nameRes(): Int = when (this) { CarbsType.PIZZA -> R.string.wizard_carbs_type_pizza } -/** [carbsType] is null when the meal type page is off. Then the carbs line is the whole entry, as before. */ +/** + * [carbsType] is null when the meal type page is off. Then the carbs line is the whole entry, as before. + * [carbTime] is shown when it is not zero, with the bell when the alarm will be set. + */ @Composable -private fun WizardConfirmScreen(carbs: Int, carbsType: CarbsType?, percentage: Int?, onConfirm: () -> Unit) { +private fun WizardConfirmScreen(carbs: Int, carbsType: CarbsType?, carbTime: Int, alarm: Boolean, percentage: Int?, onConfirm: () -> Unit) { val haptic = LocalHapticFeedback.current var confirmationSent by remember { mutableStateOf(false) } val carbsNow = carbsType?.carbsNow(carbs) ?: carbs @@ -277,6 +342,25 @@ private fun WizardConfirmScreen(carbs: Int, carbsType: CarbsType?, percentage: I fontSize = 20.sp, fontWeight = FontWeight.Bold ) + if (carbTime != 0) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = stringResource(R.string.wizard_result_carb_time, carbTime), + color = WearSecondaryText, + fontSize = 16.sp, + fontWeight = FontWeight.Bold + ) + if (alarm && carbTime > 0) { + Spacer(Modifier.size(4.dp)) + Icon( + painter = painterResource(R.drawable.ic_alarm), + contentDescription = stringResource(R.string.wizard_set_alarm), + tint = CarbsOrange, + modifier = Modifier.size(14.dp) + ) + } + } + } if (percentage != null) { Text( text = stringResource(R.string.wizard_result_correction_percentage, percentage), diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphActivity.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphActivity.kt index e84a9ce0013a..b2049579c3d6 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphActivity.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphActivity.kt @@ -19,9 +19,11 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment @@ -47,6 +49,7 @@ import app.aaps.wear.interaction.actions.CarbsOrange import app.aaps.wear.interaction.actions.InsulinBlue import app.aaps.wear.interaction.menus.MainMenuActivity import app.aaps.wear.interaction.utils.DisplayFormat +import kotlinx.coroutines.delay import dev.zacsweers.metro.Inject class BgGraphActivity : AppCompatActivity() { @@ -72,6 +75,15 @@ class BgGraphActivity : AppCompatActivity() { private fun BgGraphScreen(repository: ComplicationDataRepository, displayFormat: DisplayFormat) { val data by repository.complicationData.collectAsState(initial = ComplicationData()) var windowIdx by remember { mutableIntStateOf(0) } + val context = LocalContext.current + // The graph's clock, a minute at a time, so the minutes left of the eat reminder stay right between data updates + var clock by remember { mutableLongStateOf(System.currentTimeMillis()) } + LaunchedEffect(Unit) { + while (true) { + delay(60_000L) + clock = System.currentTimeMillis() + } + } val historyHours = historyHoursCycle[windowIdx] val bgData = data.bgData @@ -185,7 +197,7 @@ private fun BgGraphScreen(repository: ComplicationDataRepository, displayFormat: .weight(1f) .clickable { windowIdx = (windowIdx + 1) % historyHoursCycle.size } ) { - renderBgGraph(data, historyHours) + renderBgGraph(data, historyHours, now = clock, minutesText = { context.getString(R.string.action_minutes_format, it) }) } } } diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt index b9be8a2c3cf2..20d7ad42608e 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt @@ -4,9 +4,11 @@ import android.graphics.Paint import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path +import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.drawIntoCanvas import androidx.compose.ui.graphics.nativeCanvas +import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.dp import app.aaps.core.data.ui.MarkerSizeClasses import app.aaps.core.data.ui.MarkerTier @@ -151,8 +153,18 @@ internal fun markerAnchorTime(time: Long, partners: List): Long { return if (partner != null && partner < time) partner else time } -internal fun DrawScope.renderBgGraph(data: ComplicationData, historyHours: Int, showNowLabel: Boolean = true) { - val now = System.currentTimeMillis() +/** + * [now] is the moment the graph is drawn for; a screen that ticks passes its own clock, so the drawing + * follows it. [minutesText] writes the minutes left of the "time to eat" timer at its end line; null + * leaves the timer out. + */ +internal fun DrawScope.renderBgGraph( + data: ComplicationData, + historyHours: Int, + showNowLabel: Boolean = true, + now: Long = System.currentTimeMillis(), + minutesText: ((Int) -> String)? = null +) { val historyMs = historyHours * 60 * 60 * 1000L // Cap predictions at the history span so short ranges (1h) aren't dominated by the prediction area val predictionMs = min(90 * 60 * 1000L, historyMs) @@ -244,6 +256,35 @@ internal fun DrawScope.renderBgGraph(data: ComplicationData, historyHours: Int, } } + // The "time to eat" timer: a dashed line where it rings, with the minutes left at it, one line under + // the now label so the two never meet. Past the window's end the line stands at the edge + val eatAt = data.statusData.eatReminderEndsAt + if (minutesText != null && eatAt != null && eatAt > now) { + val x = timeToX(min(eatAt, endTime)) + drawLine( + color = CarbsOrange, + start = Offset(x, pad), + end = Offset(x, pad + graphH), + strokeWidth = 1.dp.toPx(), + pathEffect = PathEffect.dashPathEffect(floatArrayOf(4.dp.toPx(), 3.dp.toPx())) + ) + val minutesLeft = ((eatAt - now + 59_999L) / 60_000L).toInt() + drawIntoCanvas { canvas -> + val paint = Paint().apply { + color = CarbsOrange.toArgb() + textSize = 8.dp.toPx() + isAntiAlias = true + isFakeBoldText = true + } + val text = minutesText(minutesLeft) + val margin = 2.dp.toPx() + // Right of the line when there is room, else left of it + val fits = x + margin + paint.measureText(text) <= pad + drawW + paint.textAlign = if (fits) Paint.Align.LEFT else Paint.Align.RIGHT + canvas.nativeCanvas.drawText(text, if (fits) x + margin else x - margin, pad + paint.textSize * 2 + 4f, paint) + } + } + val high = bgData.high.toFloat() if (high in yMin..yMax) { drawLine( diff --git a/wear/src/main/kotlin/app/aaps/wear/tile/BgGraphTileService.kt b/wear/src/main/kotlin/app/aaps/wear/tile/BgGraphTileService.kt index 9e5d1c98b030..f685e932e7d1 100644 --- a/wear/src/main/kotlin/app/aaps/wear/tile/BgGraphTileService.kt +++ b/wear/src/main/kotlin/app/aaps/wear/tile/BgGraphTileService.kt @@ -210,7 +210,7 @@ class BgGraphTileService : TileService() { canvas = composeCanvas, size = Size(widthPx.toFloat(), graphHeightPx.toFloat()) ) { - renderBgGraph(data, sp.getString("tile_bg_graph_hours", "3").toIntOrNull() ?: 3) + renderBgGraph(data, sp.getString("tile_bg_graph_hours", "3").toIntOrNull() ?: 3, minutesText = { getString(R.string.action_minutes_format, it) }) } } diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 6e5cc2a8ecc1..552b0cf8d8b5 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -62,6 +62,7 @@ Single Target Calculator Percentage Calculator Meal Type + Calculator Carb Time Complication Tap Action BG graph time range 1 hour @@ -223,6 +224,8 @@ singletarget wizardpercentage wizardcarbstype + wizardcarbtime + eat_reminder_ends_at show_graph_basal show_graph_temp_basal show_graph_carbs @@ -367,6 +370,14 @@ Bread Cake Pizza + Carb time\n[minutes] + Now + %1$+d + %1$+d min + Set alarm + Time to eat + Silence + +%1$d min %1$d+%2$d g U %1$d g diff --git a/wear/src/main/res/xml/interface_preferences.xml b/wear/src/main/res/xml/interface_preferences.xml index c7daf734f456..cfee9de81421 100644 --- a/wear/src/main/res/xml/interface_preferences.xml +++ b/wear/src/main/res/xml/interface_preferences.xml @@ -11,6 +11,15 @@ app:wear_iconOff="@drawable/settings_off" app:wear_iconOn="@drawable/settings_on" /> + + Date: Tue, 27 Oct 2026 20:03:35 +0100 Subject: [PATCH 2/6] Wear eat reminder: the notification is the ring, and the carb time page fits The ring screen is gone: Android does not start an activity from an alarm in the background, so it only showed up behind the notification's "Open app". The vibrating notification with Silence and +5 min is the ring now. The carb time page says "Carb time [min]" on two lines and keeps the bell row on one line, so the - and + buttons sit still from "Now" to "+60". The face's graph complication writes the minutes left at the timer's line too. --- wear/src/main/AndroidManifest.xml | 10 +- .../wear/complications/BgGraphComplication.kt | 2 +- .../app/aaps/wear/di/WearMemberInjectors.kt | 6 - .../wear/eatreminder/EatReminderActivity.kt | 129 ------------------ .../aaps/wear/eatreminder/EatReminderWatch.kt | 24 +--- .../interaction/actions/WizardActivity.kt | 19 ++- .../interaction/activities/BgGraphRenderer.kt | 6 +- wear/src/main/res/values/strings.xml | 2 +- 8 files changed, 22 insertions(+), 176 deletions(-) delete mode 100644 wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 608c40f3bf08..b12437a1cae7 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -911,18 +911,10 @@ android:exported="false" android:taskAffinity="" android:theme="@style/WearAppCompatDark" /> - + - ): MembersInjector<*> = injector - @Provides - @FeatureMemberInjectors - @IntoMap - @ClassKey(EatReminderActivity::class) - fun bindEatReminderActivity(injector: MembersInjector): MembersInjector<*> = injector @Provides @FeatureMemberInjectors diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt deleted file mode 100644 index 8ecb2fd71c95..000000000000 --- a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderActivity.kt +++ /dev/null @@ -1,129 +0,0 @@ -package app.aaps.wear.eatreminder - -import android.os.Bundle -import android.os.VibrationEffect -import android.os.Vibrator -import androidx.activity.compose.setContent -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.res.painterResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import androidx.wear.compose.material3.Button -import androidx.wear.compose.material3.ButtonDefaults -import androidx.wear.compose.material3.Icon -import androidx.wear.compose.material3.MaterialTheme -import androidx.wear.compose.material3.Text -import app.aaps.core.interfaces.alerts.EatReminder -import app.aaps.wear.R -import app.aaps.wear.di.WearMetroActivity -import app.aaps.wear.interaction.actions.CarbsOrange -import dev.zacsweers.metro.Inject -import kotlinx.coroutines.delay - -/** - * The "time to eat" timer rang: the watch vibrates and offers Silence and +5 min. Both go to the phone - * through [EatReminderWatch]. The screen is closed by it when the phone ends or moves the timer. - * - * Opened from a broadcast receiver, which Android may refuse from the background; the notification - * [EatReminderWatch] posts at the same time has the same two buttons, so nothing is lost then. - */ -class EatReminderActivity : WearMetroActivity() { - - @Inject lateinit var eatReminderWatch: EatReminderWatch - - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - current = this - setShowWhenLocked(true) - setTurnScreenOn(true) - val vibrator = getSystemService(Vibrator::class.java) - vibrator?.vibrate(VibrationEffect.createWaveform(RING_PATTERN, 0)) - setContent { - MaterialTheme { - // The screen stays until the user acts, the vibration does not - LaunchedEffect(Unit) { - delay(VIBRATE_MS) - vibrator?.cancel() - } - EatReminderScreen( - onSilence = { eatReminderWatch.silence() }, - onExtend = { eatReminderWatch.extend() } - ) - } - } - } - - override fun onDestroy() { - super.onDestroy() - getSystemService(Vibrator::class.java)?.cancel() - if (current === this) current = null - } - - companion object { - - private val RING_PATTERN = longArrayOf(0, 500, 300, 500, 1500) - private const val VIBRATE_MS = 60_000L - - // One screen at a time, so the phone's answer can close it - @Volatile private var current: EatReminderActivity? = null - - fun close() { - current?.finish() - } - } -} - -@Composable -private fun EatReminderScreen(onSilence: () -> Unit, onExtend: () -> Unit) { - Column( - modifier = Modifier - .fillMaxSize() - .padding(horizontal = 24.dp, vertical = 8.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Center - ) { - Icon( - painter = painterResource(R.drawable.ic_alarm), - contentDescription = null, - tint = CarbsOrange, - modifier = Modifier.size(28.dp) - ) - Spacer(Modifier.height(4.dp)) - Text( - text = stringResource(R.string.eat_reminder_title), - color = Color.White, - fontSize = 18.sp, - fontWeight = FontWeight.Bold, - textAlign = TextAlign.Center - ) - Spacer(Modifier.height(12.dp)) - Button( - onClick = onSilence, - modifier = Modifier.fillMaxWidth(), - colors = ButtonDefaults.buttonColors(containerColor = Color.White.copy(alpha = 0.15f), contentColor = Color.White), - label = { Text(stringResource(R.string.eat_reminder_silence)) } - ) - Spacer(Modifier.height(8.dp)) - Button( - onClick = onExtend, - modifier = Modifier.fillMaxWidth(), - colors = ButtonDefaults.buttonColors(containerColor = CarbsOrange, contentColor = Color.Black), - label = { Text(stringResource(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES)) } - ) - } -} diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt index 45771d0e57ba..0059b44d318c 100644 --- a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt @@ -27,9 +27,10 @@ import kotlin.math.max * * The phone owns the timer and sends its end time with every status. The watch draws the end in its BG * graph and sets its own alarm at that time, so it rings also when the phone is out of reach at that - * moment. The ring is a vibrating notification with Silence and +5 min, and [EatReminderActivity] over - * it. Both buttons go to the phone, which stops or moves the timer, and the next status brings the - * result back. Until then the watch acts on its own copy, so it reads right also with the phone away. + * moment. The ring is a vibrating notification with Silence and +5 min; a screen of its own was tried, + * but Android does not open one from an alarm in the background. Both buttons go to the phone, which + * stops or moves the timer, and the next status brings the result back. Until then the watch acts on + * its own copy, so it reads right also with the phone away. */ @SingleIn(AppScope::class) @Inject @@ -75,15 +76,6 @@ class EatReminderWatch( } aapsLogger.debug(LTag.WEAR, "Eat reminder rings") postRingNotification() - try { - context.startActivity( - Intent(context, EatReminderActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) - ) - } catch (e: Exception) { - // Android may refuse a start from the background; the notification has the same buttons - aapsLogger.error(LTag.WEAR, "Eat reminder screen not opened", e) - } } /** Silence: the timer ends. The phone silences its own alarm too. */ @@ -119,7 +111,6 @@ class EatReminderWatch( private fun clearRing() { notificationManager.cancel(NOTIFICATION_ID) - EatReminderActivity.close() } private fun postRingNotification() { @@ -134,12 +125,6 @@ class EatReminderWatch( .setContentTitle(context.getString(R.string.eat_reminder_title)) .setCategory(NotificationCompat.CATEGORY_ALARM) .setPriority(NotificationCompat.PRIORITY_HIGH) - .setContentIntent( - PendingIntent.getActivity( - context, OPEN_REQUEST_CODE, Intent(context, EatReminderActivity::class.java), - PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE - ) - ) .addAction(0, context.getString(R.string.eat_reminder_silence), actionIntent(EatReminderReceiver.ACTION_STOP, STOP_REQUEST_CODE)) .addAction(0, context.getString(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES), actionIntent(EatReminderReceiver.ACTION_EXTEND, EXTEND_REQUEST_CODE)) .build() @@ -162,7 +147,6 @@ class EatReminderWatch( const val RING_REQUEST_CODE = 4720 const val STOP_REQUEST_CODE = 4721 const val EXTEND_REQUEST_CODE = 4722 - const val OPEN_REQUEST_CODE = 4723 const val EXTEND_MS = EatReminder.EXTEND_MINUTES * 60_000L /** An alarm may come a little early or late; further from the end it belongs to an older timer. */ diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt index 3dd615824d8a..c28f69f9a634 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt @@ -22,6 +22,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.hapticfeedback.HapticFeedbackType @@ -133,9 +134,8 @@ class WizardActivity : WearMetroActivity() { simpleMode = true, enabled = !pagerState.isScrollInProgress, title = stringResource(R.string.menu_wizard), - footer = if (carbTime > 0) { - { AlarmToggle(checked = alarm, onToggle = { alarm = it }, enabled = !pagerState.isScrollInProgress) } - } else null, + // Always in the layout, so the value does not jump when the bell comes and goes + footer = { AlarmToggle(checked = alarm, onToggle = { alarm = it }, visible = carbTime > 0, enabled = !pagerState.isScrollInProgress) }, ) Page.PERCENTAGE -> PlusMinusInputScreen( value = percentage, @@ -248,15 +248,19 @@ private fun CarbsTypeScreen(carbs: Int, selected: CarbsType, onSelect: (CarbsTyp } } -/** The "time to eat" alarm of the carb time page: a bell that is lit when the alarm is on. One tap flips it. */ +/** + * The "time to eat" alarm of the carb time page: a bell that is lit when the alarm is on. One tap flips it. + * Not [visible] while the carbs are not later, but still in the layout, so the page does not move. + */ @Composable -private fun AlarmToggle(checked: Boolean, onToggle: (Boolean) -> Unit, enabled: Boolean) { +private fun AlarmToggle(checked: Boolean, onToggle: (Boolean) -> Unit, visible: Boolean, enabled: Boolean) { val haptic = LocalHapticFeedback.current Row( modifier = Modifier .padding(top = 4.dp) + .alpha(if (visible) 1f else 0f) .clip(CircleShape) - .clickable(enabled = enabled) { + .clickable(enabled = enabled && visible) { haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) onToggle(!checked) } @@ -274,7 +278,8 @@ private fun AlarmToggle(checked: Boolean, onToggle: (Boolean) -> Unit, enabled: Text( text = stringResource(R.string.wizard_set_alarm), color = if (checked) Color.White else WearSecondaryText, - fontSize = 12.sp + fontSize = 12.sp, + maxLines = 1 ) } } diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt index 20d7ad42608e..20a37fb2e455 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/activities/BgGraphRenderer.kt @@ -156,7 +156,7 @@ internal fun markerAnchorTime(time: Long, partners: List): Long { /** * [now] is the moment the graph is drawn for; a screen that ticks passes its own clock, so the drawing * follows it. [minutesText] writes the minutes left of the "time to eat" timer at its end line; null - * leaves the timer out. + * leaves the minutes out, the line stays. */ internal fun DrawScope.renderBgGraph( data: ComplicationData, @@ -259,7 +259,7 @@ internal fun DrawScope.renderBgGraph( // The "time to eat" timer: a dashed line where it rings, with the minutes left at it, one line under // the now label so the two never meet. Past the window's end the line stands at the edge val eatAt = data.statusData.eatReminderEndsAt - if (minutesText != null && eatAt != null && eatAt > now) { + if (eatAt != null && eatAt > now) { val x = timeToX(min(eatAt, endTime)) drawLine( color = CarbsOrange, @@ -269,7 +269,7 @@ internal fun DrawScope.renderBgGraph( pathEffect = PathEffect.dashPathEffect(floatArrayOf(4.dp.toPx(), 3.dp.toPx())) ) val minutesLeft = ((eatAt - now + 59_999L) / 60_000L).toInt() - drawIntoCanvas { canvas -> + if (minutesText != null) drawIntoCanvas { canvas -> val paint = Paint().apply { color = CarbsOrange.toArgb() textSize = 8.dp.toPx() diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 552b0cf8d8b5..3e75324e2f28 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -370,7 +370,7 @@ Bread Cake Pizza - Carb time\n[minutes] + Carb time\n[min] Now %1$+d %1$+d min From 7e01008cc0ad92e4580e55caa553cb83b94edee2 Mon Sep 17 00:00:00 2001 From: olorinmaia Date: Tue, 27 Oct 2026 20:49:28 +0100 Subject: [PATCH 3/6] Wear eat reminder: a silent countdown notification with Stop and +5 min Between the start and the ring the watch only showed the line in the graph, so the timer could not be stopped from the watch before it rang. While it runs, a silent notification now sits in the stream: "Time to eat, Rings at 19:25", with Stop and +5 min. It follows every new end time, goes away when the timer ends, and times out by itself at the ring, when the ring's own notification takes over. --- .../aaps/wear/eatreminder/EatReminderWatch.kt | 48 +++++++++++++++++-- wear/src/main/res/values/strings.xml | 3 ++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt index 0059b44d318c..711dab22fff8 100644 --- a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt @@ -6,6 +6,7 @@ import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent +import android.text.format.DateFormat import androidx.core.app.NotificationCompat import app.aaps.core.interfaces.alerts.EatReminder import app.aaps.core.interfaces.alerts.EatReminderAction @@ -19,6 +20,7 @@ import app.aaps.wear.R import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn +import java.util.Date import kotlin.math.abs import kotlin.math.max @@ -27,10 +29,11 @@ import kotlin.math.max * * The phone owns the timer and sends its end time with every status. The watch draws the end in its BG * graph and sets its own alarm at that time, so it rings also when the phone is out of reach at that - * moment. The ring is a vibrating notification with Silence and +5 min; a screen of its own was tried, - * but Android does not open one from an alarm in the background. Both buttons go to the phone, which - * stops or moves the timer, and the next status brings the result back. Until then the watch acts on - * its own copy, so it reads right also with the phone away. + * moment. While it runs a silent notification with Stop and +5 min sits in the stream, so the timer can + * be handled from the watch before it rings. The ring is a vibrating notification with Silence and + * +5 min; a screen of its own was tried, but Android does not open one from an alarm in the background. + * The buttons go to the phone, which stops or moves the timer, and the next status brings the result + * back. Until then the watch acts on its own copy, so it reads right also with the phone away. */ @SingleIn(AppScope::class) @Inject @@ -60,6 +63,7 @@ class EatReminderWatch( if (new == 0L) { aapsLogger.debug(LTag.WEAR, "Eat reminder ended on the phone") alarmManager.cancel(ringIntent()) + notificationManager.cancel(COUNTDOWN_NOTIFICATION_ID) } else { aapsLogger.debug(LTag.WEAR, "Eat reminder ends at $new") schedule(new) @@ -75,6 +79,7 @@ class EatReminderWatch( return } aapsLogger.debug(LTag.WEAR, "Eat reminder rings") + notificationManager.cancel(COUNTDOWN_NOTIFICATION_ID) postRingNotification() } @@ -83,6 +88,7 @@ class EatReminderWatch( send(EatReminderAction.STOP) sp.remove(R.string.key_eat_reminder_ends_at) alarmManager.cancel(ringIntent()) + notificationManager.cancel(COUNTDOWN_NOTIFICATION_ID) clearRing() } @@ -107,6 +113,38 @@ class EatReminderWatch( if (endsAt < System.currentTimeMillis() - RING_TOLERANCE_MS) return // Exact, so a kitchen timer is not minutes late. The watch app targets API 30, so no permission is asked for alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, endsAt, ringIntent()) + postCountdownNotification(endsAt) + } + + /** + * The running timer in the stream: silent, with Stop and +5 min, and the ring time as its time. It + * goes away by itself at the end, when the ring takes over. A live countdown is not reliable on a + * watch, so the text names the time instead. + */ + private fun postCountdownNotification(endsAt: Long) { + val left = endsAt - System.currentTimeMillis() + if (left <= 0) return + notificationManager.createNotificationChannel( + NotificationChannel(COUNTDOWN_CHANNEL_ID, context.getString(R.string.eat_reminder_countdown_channel), NotificationManager.IMPORTANCE_LOW).apply { + enableVibration(false) + setSound(null, null) + } + ) + val notification = NotificationCompat.Builder(context, COUNTDOWN_CHANNEL_ID) + .setSmallIcon(R.drawable.ic_alarm) + .setContentTitle(context.getString(R.string.eat_reminder_title)) + .setContentText(context.getString(R.string.eat_reminder_rings_at, DateFormat.getTimeFormat(context).format(Date(endsAt)))) + .setCategory(NotificationCompat.CATEGORY_REMINDER) + .setWhen(endsAt) + .setShowWhen(true) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setSilent(true) + .setTimeoutAfter(left) + .addAction(0, context.getString(R.string.eat_reminder_stop), actionIntent(EatReminderReceiver.ACTION_STOP, STOP_REQUEST_CODE)) + .addAction(0, context.getString(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES), actionIntent(EatReminderReceiver.ACTION_EXTEND, EXTEND_REQUEST_CODE)) + .build() + notificationManager.notify(COUNTDOWN_NOTIFICATION_ID, notification) } private fun clearRing() { @@ -143,7 +181,9 @@ class EatReminderWatch( private companion object { const val CHANNEL_ID = "AndroidAPS-EatReminder" + const val COUNTDOWN_CHANNEL_ID = "AndroidAPS-EatReminder-Countdown" const val NOTIFICATION_ID = 4720 + const val COUNTDOWN_NOTIFICATION_ID = 4724 const val RING_REQUEST_CODE = 4720 const val STOP_REQUEST_CODE = 4721 const val EXTEND_REQUEST_CODE = 4722 diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 3e75324e2f28..9ed7e8099d75 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -377,6 +377,9 @@ Set alarm Time to eat Silence + Stop + Rings at %1$s + Time to eat, running +%1$d min %1$d+%2$d g U From 02c35ae1dec2ee39cffce72203082d706823f46b Mon Sep 17 00:00:00 2001 From: olorinmaia Date: Tue, 27 Oct 2026 21:36:13 +0100 Subject: [PATCH 4/6] Eat reminder: the phone's alarm screen closes when the timer is stopped elsewhere Silence from the watch, or Stop from a client or from the notification, ended the timer and muted the sound, but the alarm screen on the phone stayed open with nothing left to offer. It now closes when the timer is gone. The phone's own "Silence alarm" keeps it open, as for every alarm. Also on the watch wizard's request page: the carb time and the percentage share one line when both are there, since a third line under the check fell off the screen. And a note for translators that the carb time label must stay short. --- .../app/aaps/ui/activities/ErrorActivity.kt | 12 +++++ .../interaction/actions/WizardActivity.kt | 51 ++++++++++--------- wear/src/main/res/values/strings.xml | 2 +- 3 files changed, 41 insertions(+), 24 deletions(-) diff --git a/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt b/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt index 6860585b08c4..e4cdc102dfc9 100644 --- a/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt +++ b/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt @@ -12,6 +12,7 @@ import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @@ -44,6 +45,7 @@ import app.aaps.core.ui.compose.LocalSnackbarHostState import app.aaps.core.ui.compose.MetroAppCompatActivity import app.aaps.core.ui.compose.dialogs.GlobalSnackbarHost import dev.zacsweers.metro.Inject +import kotlinx.coroutines.flow.first /** * Full-screen alarm UI. Audio playback (looping MediaPlayer + volume ramp) lives in the shared @@ -69,6 +71,9 @@ class ErrorActivity : MetroAppCompatActivity() { private var status by mutableStateOf("") private var title by mutableStateOf("") private var eatReminderAlarm by mutableStateOf(false) + + /** The eat reminder's alarm was silenced on this screen. The screen then stays, as for every alarm. */ + private var mutedHere = false private var sound: AlarmSound = AlarmSound.ERROR /** @@ -100,6 +105,12 @@ class ErrorActivity : MetroAppCompatActivity() { aapsLogger.debug("Error activity displayed: $title - $status") setContent { + // The timer ended somewhere else (the watch, a client, the notification's Mute): its alarm is + // silenced there, and this screen has nothing left to offer, so it closes + if (eatReminderAlarm) LaunchedEffect(Unit) { + eatReminder.state.first { it == null } + if (!mutedHere) finish() + } val snackbarHostState = remember { SnackbarHostState() } CompositionLocalProvider( LocalPreferences provides preferences, @@ -124,6 +135,7 @@ class ErrorActivity : MetroAppCompatActivity() { }, onMute = { uel.log(Action.ERROR_DIALOG_MUTE, Sources.Unknown) + mutedHere = true stopAlarm("Mute") }, onMute5Min = { diff --git a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt index c28f69f9a634..1b49997304d3 100644 --- a/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt +++ b/wear/src/main/kotlin/app/aaps/wear/interaction/actions/WizardActivity.kt @@ -347,32 +347,37 @@ private fun WizardConfirmScreen(carbs: Int, carbsType: CarbsType?, carbTime: Int fontSize = 20.sp, fontWeight = FontWeight.Bold ) - if (carbTime != 0) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text( - text = stringResource(R.string.wizard_result_carb_time, carbTime), - color = WearSecondaryText, - fontSize = 16.sp, - fontWeight = FontWeight.Bold - ) - if (alarm && carbTime > 0) { - Spacer(Modifier.size(4.dp)) - Icon( - painter = painterResource(R.drawable.ic_alarm), - contentDescription = stringResource(R.string.wizard_set_alarm), - tint = CarbsOrange, - modifier = Modifier.size(14.dp) + // The carb time and the percentage share one line when both are there, so the page stays as tall + // as with one of them: a third line under the check fell off the bottom of the screen + if (carbTime != 0 || percentage != null) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + if (carbTime != 0) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + text = stringResource(R.string.wizard_result_carb_time, carbTime), + color = WearSecondaryText, + fontSize = 16.sp, + fontWeight = FontWeight.Bold + ) + if (alarm && carbTime > 0) { + Icon( + painter = painterResource(R.drawable.ic_alarm), + contentDescription = stringResource(R.string.wizard_set_alarm), + tint = CarbsOrange, + modifier = Modifier.size(14.dp) + ) + } + } + } + if (percentage != null) { + Text( + text = stringResource(R.string.wizard_result_correction_percentage, percentage), + color = WearSecondaryText, + fontSize = if (carbTime != 0) 16.sp else 20.sp, + fontWeight = FontWeight.Bold ) } } } - if (percentage != null) { - Text( - text = stringResource(R.string.wizard_result_correction_percentage, percentage), - color = WearSecondaryText, - fontSize = 20.sp, - fontWeight = FontWeight.Bold - ) - } } } diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 9ed7e8099d75..255cee4d99df 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -370,7 +370,7 @@ Bread Cake Pizza - Carb time\n[min] + Carb time\n[min] Now %1$+d %1$+d min From ef5747e0aa0b38b2af7839ce97898fbeadf330d9 Mon Sep 17 00:00:00 2001 From: olorinmaia Date: Wed, 28 Oct 2026 00:55:41 +0100 Subject: [PATCH 5/6] Eat reminder: a swipe on the watch keeps the running timer's notification and silences the ring Wear OS lets the user swipe an ongoing notification away. For the running timer that notification is the only Stop and +5 min on the watch, so it comes back at once: its delete intent posts it again while the timer runs. Our own cancel does not fire the delete intent, so Stop, the ring and a timer ended on the phone still clear it. A swipe on the ringing notification silences the timer, as on a clock's alarm. Before, the phone kept ringing with nothing left on the watch to stop it. On the phone, the alarm screen now also closes when the timer is moved +5 min from the watch or a client, not only when it is stopped there. The alarm has rung when that screen opens, so a timer that has not rung is one that was extended. --- .../app/aaps/ui/activities/ErrorActivity.kt | 7 ++++--- .../wear/eatreminder/EatReminderReceiver.kt | 4 +++- .../aaps/wear/eatreminder/EatReminderWatch.kt | 21 ++++++++++++++++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt b/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt index e4cdc102dfc9..c564b0848925 100644 --- a/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt +++ b/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt @@ -105,10 +105,11 @@ class ErrorActivity : MetroAppCompatActivity() { aapsLogger.debug("Error activity displayed: $title - $status") setContent { - // The timer ended somewhere else (the watch, a client, the notification's Mute): its alarm is - // silenced there, and this screen has nothing left to offer, so it closes + // The timer ended or was moved +5 min somewhere else (the watch, a client, the notification): its + // alarm is silenced there, and this screen has nothing left to offer, so it closes. The alarm has + // rung when this screen opens, so a timer that has not rung is one that was extended. if (eatReminderAlarm) LaunchedEffect(Unit) { - eatReminder.state.first { it == null } + eatReminder.state.first { it == null || !it.alarmRang } if (!mutedHere) finish() } val snackbarHostState = remember { SnackbarHostState() } diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt index 346081c6c6fe..9e0a1f288811 100644 --- a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt @@ -6,7 +6,7 @@ import android.content.Intent import app.aaps.core.interfaces.di.injectMetroMembers import dev.zacsweers.metro.Inject -/** The alarm of the "time to eat" timer, and the Silence and +5 min buttons of its notification. */ +/** The alarm of the "time to eat" timer, the buttons of its notifications, and the swipe that dismisses the running one. */ class EatReminderReceiver : BroadcastReceiver() { @Inject lateinit var eatReminderWatch: EatReminderWatch @@ -17,6 +17,7 @@ class EatReminderReceiver : BroadcastReceiver() { ACTION_RING -> eatReminderWatch.ring() ACTION_STOP -> eatReminderWatch.silence() ACTION_EXTEND -> eatReminderWatch.extend() + ACTION_REPOST -> eatReminderWatch.repost() } } @@ -25,5 +26,6 @@ class EatReminderReceiver : BroadcastReceiver() { const val ACTION_RING = "app.aaps.wear.eatReminder.RING" const val ACTION_STOP = "app.aaps.wear.eatReminder.STOP" const val ACTION_EXTEND = "app.aaps.wear.eatReminder.EXTEND" + const val ACTION_REPOST = "app.aaps.wear.eatReminder.REPOST" } } diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt index 711dab22fff8..ce4c0841ac72 100644 --- a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt @@ -30,8 +30,10 @@ import kotlin.math.max * The phone owns the timer and sends its end time with every status. The watch draws the end in its BG * graph and sets its own alarm at that time, so it rings also when the phone is out of reach at that * moment. While it runs a silent notification with Stop and +5 min sits in the stream, so the timer can - * be handled from the watch before it rings. The ring is a vibrating notification with Silence and - * +5 min; a screen of its own was tried, but Android does not open one from an alarm in the background. + * be handled from the watch before it rings; it is the only way to do that on the watch, so it comes + * back when it is swiped away. The ring is a vibrating notification with Silence and +5 min, and a + * swipe silences it, as on a clock's alarm; a screen of its own was tried, but Android does not open one + * from an alarm in the background. * The buttons go to the phone, which stops or moves the timer, and the next status brings the result * back. Until then the watch acts on its own copy, so it reads right also with the phone away. */ @@ -104,6 +106,14 @@ class EatReminderWatch( schedule(newEnd) } + /** The running timer's notification was swiped away. It comes back while the timer runs: it is the watch's only Stop. */ + fun repost() { + val endsAt = this.endsAt + if (endsAt == 0L) return + aapsLogger.debug(LTag.WEAR, "Eat reminder notification dismissed, posted again") + postCountdownNotification(endsAt) + } + private fun send(action: EatReminderAction) { rxBus.send(EventWearToMobile(EventData.ActionEatReminder(action))) } @@ -119,7 +129,8 @@ class EatReminderWatch( /** * The running timer in the stream: silent, with Stop and +5 min, and the ring time as its time. It * goes away by itself at the end, when the ring takes over. A live countdown is not reliable on a - * watch, so the text names the time instead. + * watch, so the text names the time instead. Wear OS lets the user swipe an ongoing notification + * away, so the swipe posts it again; our own cancel does not fire the delete intent. */ private fun postCountdownNotification(endsAt: Long) { val left = endsAt - System.currentTimeMillis() @@ -141,6 +152,7 @@ class EatReminderWatch( .setOnlyAlertOnce(true) .setSilent(true) .setTimeoutAfter(left) + .setDeleteIntent(actionIntent(EatReminderReceiver.ACTION_REPOST, REPOST_REQUEST_CODE)) .addAction(0, context.getString(R.string.eat_reminder_stop), actionIntent(EatReminderReceiver.ACTION_STOP, STOP_REQUEST_CODE)) .addAction(0, context.getString(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES), actionIntent(EatReminderReceiver.ACTION_EXTEND, EXTEND_REQUEST_CODE)) .build() @@ -151,6 +163,7 @@ class EatReminderWatch( notificationManager.cancel(NOTIFICATION_ID) } + /** The ring: Silence and +5 min as buttons, and a swipe silences too. Our own cancel does not fire the delete intent. */ private fun postRingNotification() { notificationManager.createNotificationChannel( NotificationChannel(CHANNEL_ID, context.getString(R.string.eat_reminder_title), NotificationManager.IMPORTANCE_HIGH).apply { @@ -163,6 +176,7 @@ class EatReminderWatch( .setContentTitle(context.getString(R.string.eat_reminder_title)) .setCategory(NotificationCompat.CATEGORY_ALARM) .setPriority(NotificationCompat.PRIORITY_HIGH) + .setDeleteIntent(actionIntent(EatReminderReceiver.ACTION_STOP, STOP_REQUEST_CODE)) .addAction(0, context.getString(R.string.eat_reminder_silence), actionIntent(EatReminderReceiver.ACTION_STOP, STOP_REQUEST_CODE)) .addAction(0, context.getString(R.string.eat_reminder_extend, EatReminder.EXTEND_MINUTES), actionIntent(EatReminderReceiver.ACTION_EXTEND, EXTEND_REQUEST_CODE)) .build() @@ -187,6 +201,7 @@ class EatReminderWatch( const val RING_REQUEST_CODE = 4720 const val STOP_REQUEST_CODE = 4721 const val EXTEND_REQUEST_CODE = 4722 + const val REPOST_REQUEST_CODE = 4723 const val EXTEND_MS = EatReminder.EXTEND_MINUTES * 60_000L /** An alarm may come a little early or late; further from the end it belongs to an older timer. */ From 6a8464f6e72e48db449b38bd00949f55edffde35 Mon Sep 17 00:00:00 2001 From: olorinmaia Date: Wed, 28 Oct 2026 01:47:34 +0100 Subject: [PATCH 6/6] Eat reminder: the watch rings again every half minute for five minutes A watch vibrates once per notification, while the phone rings until it is answered. So the ring is posted again every 30 s until 5 minutes after the end, with the same alarm intent: Silence, +5 min and a swipe on the watch, and a timer stopped or moved on the phone, cancel or replace that alarm and the repeats with it. The window for a valid alarm grows from 2 minutes around the end to 2 minutes before and 7 minutes after, so the repeats pass and an old timer is still ignored. --- .../aaps/wear/eatreminder/EatReminderWatch.kt | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt index ce4c0841ac72..82a469b1d60a 100644 --- a/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt @@ -21,7 +21,6 @@ import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn import java.util.Date -import kotlin.math.abs import kotlin.math.max /** @@ -33,7 +32,8 @@ import kotlin.math.max * be handled from the watch before it rings; it is the only way to do that on the watch, so it comes * back when it is swiped away. The ring is a vibrating notification with Silence and +5 min, and a * swipe silences it, as on a clock's alarm; a screen of its own was tried, but Android does not open one - * from an alarm in the background. + * from an alarm in the background. A watch vibrates once per notification, so the ring is posted again + * every half minute for five minutes, as the phone rings until it is answered. * The buttons go to the phone, which stops or moves the timer, and the next status brings the result * back. Until then the watch acts on its own copy, so it reads right also with the phone away. */ @@ -73,16 +73,23 @@ class EatReminderWatch( return true } - /** The alarm fired. Rings only for the timer the watch knows now, not for one that was moved or ended. */ + /** + * The alarm fired, or one of its repeats. Rings only for the timer the watch knows now, not for one that + * was moved or ended. Then it sets the next repeat, every [RING_REPEAT_MS] until [RING_REPEAT_FOR_MS] after + * the end. Every answer, on the watch or on the phone, cancels or replaces the alarm, and the repeats with it. + */ fun ring() { val endsAt = this.endsAt - if (endsAt == 0L || abs(System.currentTimeMillis() - endsAt) > RING_TOLERANCE_MS) { + val now = System.currentTimeMillis() + if (endsAt == 0L || now < endsAt - RING_TOLERANCE_MS || now > endsAt + RING_REPEAT_FOR_MS + RING_TOLERANCE_MS) { aapsLogger.debug(LTag.WEAR, "Eat reminder alarm ignored: no timer due now") return } aapsLogger.debug(LTag.WEAR, "Eat reminder rings") notificationManager.cancel(COUNTDOWN_NOTIFICATION_ID) postRingNotification() + val next = now + RING_REPEAT_MS + if (next <= endsAt + RING_REPEAT_FOR_MS) alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, next, ringIntent()) } /** Silence: the timer ends. The phone silences its own alarm too. */ @@ -163,7 +170,10 @@ class EatReminderWatch( notificationManager.cancel(NOTIFICATION_ID) } - /** The ring: Silence and +5 min as buttons, and a swipe silences too. Our own cancel does not fire the delete intent. */ + /** + * The ring: Silence and +5 min as buttons, and a swipe silences too. Our own cancel does not fire the delete + * intent. Posted again on every repeat, so the watch vibrates again: not alert-once on purpose. + */ private fun postRingNotification() { notificationManager.createNotificationChannel( NotificationChannel(CHANNEL_ID, context.getString(R.string.eat_reminder_title), NotificationManager.IMPORTANCE_HIGH).apply { @@ -206,6 +216,10 @@ class EatReminderWatch( /** An alarm may come a little early or late; further from the end it belongs to an older timer. */ const val RING_TOLERANCE_MS = 2 * 60_000L + + /** The ring is repeated this often, for this long after the end, until it is answered. */ + const val RING_REPEAT_MS = 30_000L + const val RING_REPEAT_FOR_MS = 5 * 60_000L val RING_VIBRATION = longArrayOf(0, 500, 300, 500, 300, 500) } }