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/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt b/ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt index 6860585b08c4..c564b0848925 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,13 @@ class ErrorActivity : MetroAppCompatActivity() { aapsLogger.debug("Error activity displayed: $title - $status") setContent { + // 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 || !it.alarmRang } + if (!mutedHere) finish() + } val snackbarHostState = remember { SnackbarHostState() } CompositionLocalProvider( LocalPreferences provides preferences, @@ -124,6 +136,7 @@ class ErrorActivity : MetroAppCompatActivity() { }, onMute = { uel.log(Action.ERROR_DIALOG_MUTE, Sources.Unknown) + mutedHere = true stopAlarm("Mute") }, onMute5Min = { diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index f81253c8599a..b12437a1cae7 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -911,6 +911,10 @@ android:exported="false" android:taskAffinity="" android:theme="@style/WearAppCompatDark" /> + + ): 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/EatReminderReceiver.kt b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt new file mode 100644 index 000000000000..9e0a1f288811 --- /dev/null +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderReceiver.kt @@ -0,0 +1,31 @@ +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, the buttons of its notifications, and the swipe that dismisses the running one. */ +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() + ACTION_REPOST -> eatReminderWatch.repost() + } + } + + 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" + 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 new file mode 100644 index 000000000000..82a469b1d60a --- /dev/null +++ b/wear/src/main/kotlin/app/aaps/wear/eatreminder/EatReminderWatch.kt @@ -0,0 +1,225 @@ +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 android.text.format.DateFormat +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 java.util.Date +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. 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; 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. 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. + */ +@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()) + notificationManager.cancel(COUNTDOWN_NOTIFICATION_ID) + } else { + aapsLogger.debug(LTag.WEAR, "Eat reminder ends at $new") + schedule(new) + } + return true + } + + /** + * 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 + 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. */ + fun silence() { + send(EatReminderAction.STOP) + sp.remove(R.string.key_eat_reminder_ends_at) + alarmManager.cancel(ringIntent()) + notificationManager.cancel(COUNTDOWN_NOTIFICATION_ID) + 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) + } + + /** 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))) + } + + 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()) + 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. 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() + 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) + .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() + notificationManager.notify(COUNTDOWN_NOTIFICATION_ID, notification) + } + + private fun clearRing() { + 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. 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 { + 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) + .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() + 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 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 + 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. */ + 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) + } +} 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..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 @@ -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 @@ -53,23 +54,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 +92,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 +121,22 @@ 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), + // 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, 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,42 @@ 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. + * 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, 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 && visible) { + 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, + maxLines = 1 + ) + } +} + private fun CarbsType.iconRes(): Int = when (this) { CarbsType.BREAD -> R.drawable.ic_bread CarbsType.CAKE -> R.drawable.ic_cake @@ -229,9 +296,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,13 +347,37 @@ private fun WizardConfirmScreen(carbs: Int, carbsType: CarbsType?, percentage: I fontSize = 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 - ) + // 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 + ) + } + } } } } 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..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 @@ -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 minutes out, the line stays. + */ +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 (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() + if (minutesText != null) 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..255cee4d99df 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,17 @@ Bread Cake Pizza + Carb time\n[min] + Now + %1$+d + %1$+d min + Set alarm + Time to eat + Silence + Stop + Rings at %1$s + Time to eat, running + +%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" /> + +