Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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<List<TT>>()
private val runningModes = MutableSharedFlow<List<RM>>()
private val eatReminderState = MutableStateFlow<EatReminderState?>(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)
}
Expand Down Expand Up @@ -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")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<AutosensDataStore>()
whenever(iobCobCalculator.ads).thenReturn(ads)
whenever(ads.actualBg()).thenReturn(mock())
whenever(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL)
whenever(preferences.get(any<BooleanKey>())).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<WizardExecutor.WizardSource>()
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<AutosensDataStore>()
whenever(iobCobCalculator.ads).thenReturn(ads)
whenever(ads.actualBg()).thenReturn(mock())
whenever(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL)
whenever(preferences.get(any<BooleanKey>())).thenReturn(true)
stubWizardPrepared(555L, lines = emptyList())
capturedConfirm { sut.handleWizardPreCheck(EventData.ActionWizardPreCheck(carbs = 30, percentage = 100, carbTime = 0, alarm = true)) }
val captor = argumentCaptor<WizardExecutor.WizardSource>()
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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<TT>().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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -395,6 +400,8 @@ class DataHandlerMobile(
onCommitResult(sceneActions.stop(triggerChain = it.triggerChain))
}
onEventSync<EventData.SnoozeAlert> { uiInteraction.stopAlarm("Muted from wear") }
// Not gated by the wear control switch, like the mute above: it only ends or moves a reminder
onEvent<EventData.ActionEatReminder> { handleEatReminder(it) }
onEventSync<EventData.WearException> { 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.
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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(
Expand All @@ -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
)
)
}
Expand Down Expand Up @@ -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
}
Expand Down
13 changes: 13 additions & 0 deletions ui/src/androidMain/kotlin/app/aaps/ui/activities/ErrorActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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

/**
Expand Down Expand Up @@ -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,
Expand All @@ -124,6 +136,7 @@ class ErrorActivity : MetroAppCompatActivity() {
},
onMute = {
uel.log(Action.ERROR_DIALOG_MUTE, Sources.Unknown)
mutedHere = true
stopAlarm("Mute")
},
onMute5Min = {
Expand Down
4 changes: 4 additions & 0 deletions wear/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,10 @@
android:exported="false"
android:taskAffinity=""
android:theme="@style/WearAppCompatDark" />
<!-- The "time to eat" timer: its alarm, and the buttons of its notification -->
<receiver
android:name=".eatreminder.EatReminderReceiver"
android:exported="false" />
<activity
android:name="androidx.wear.activity.ConfirmationActivity"
android:exported="false"
Expand Down
6 changes: 5 additions & 1 deletion wear/src/main/kotlin/app/aaps/wear/comm/DataHandlerWear.kt
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import app.aaps.wear.complications.SgvLargeComplication
import app.aaps.wear.complications.TargetComplication
import app.aaps.wear.complications.UploaderBatteryComplication
import app.aaps.wear.data.ComplicationDataRepository
import app.aaps.wear.eatreminder.EatReminderWatch
import app.aaps.wear.interaction.WatchfaceConfigurationActivity
import app.aaps.wear.interaction.actions.AcceptActivity
import app.aaps.wear.interaction.actions.ContactingMasterActivity
Expand Down Expand Up @@ -86,7 +87,8 @@ class DataHandlerWear(
private val preferences: Preferences,
private val aapsLogger: AAPSLogger,
private val complicationDataRepository: ComplicationDataRepository,
private val watchFacePushHelper: WatchFacePushHelper
private val watchFacePushHelper: WatchFacePushHelper,
private val eatReminderWatch: EatReminderWatch
) {

// Coroutine scope for DataStore operations
Expand Down Expand Up @@ -198,6 +200,8 @@ class DataHandlerWear(
sp.putBoolean(R.string.key_temp_target_active, tempTargetActive)
TileService.getUpdater(context).requestUpdate(TempTargetTileService::class.java)
}
// The "time to eat" timer: the graph draws its end, the watch rings at it
if (eatReminderWatch.onStatus(it.eatReminderEndsAt)) TileService.getUpdater(context).requestUpdate(BgGraphTileService::class.java)
}
// Store in DataStore - supports all datasets (0, 1, 2)
dataStoreScope.launch {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class BgGraphComplication : ModernBaseComplicationProviderService() {
canvas = ComposeCanvas(Canvas(bitmap)),
size = Size(widthPx.toFloat(), heightPx.toFloat())
) {
renderBgGraph(data, historyHours, showNowLabel = false)
renderBgGraph(data, historyHours, showNowLabel = false, minutesText = { getString(R.string.action_minutes_format, it) })
}
return bitmap
}
Expand Down
Loading
Loading