diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e87519eeacbd..e4ff1d730ed1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -96,6 +96,16 @@ android:name="app.aaps.implementation.androidNotification.AlarmMuteReceiver" android:exported="false" /> + + + + + + ): MembersInjector<*> = injector + // "Hypo treated" action on the low glucose alarm notification. Same reason as AlarmMuteReceiver: + // without this entry, tapping the button would crash with "No Metro binding". + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(HypoTreatedReceiver::class) + fun bindHypoTreatedReceiver(injector: MembersInjector): MembersInjector<*> = injector + + // "Acknowledge" action on a CGM alarm notification. Same reason as AlarmMuteReceiver. + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(CgmAlarmAcknowledgeReceiver::class) + fun bindCgmAlarmAcknowledgeReceiver(injector: MembersInjector): MembersInjector<*> = injector + // The "time to eat" alarm and its notification buttons - same story as AlarmMuteReceiver above. @Provides @FeatureMemberInjectors diff --git a/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt b/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt index b13276363e6c..d1b51a931dab 100644 --- a/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt +++ b/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt @@ -123,6 +123,7 @@ import app.aaps.database.AppRepository import app.aaps.database.di.DatabaseConfig import app.aaps.di.ExternalOptionsOverride import app.aaps.implementation.lifecycle.ProcessLifecycleListener +import app.aaps.implementation.maintenance.PeriodicMaintenance import app.aaps.implementation.maintenance.cloud.CloudStorageManager import app.aaps.implementation.notifications.SnackbarNotificationFallback import app.aaps.implementation.plugin.PluginStore @@ -338,6 +339,7 @@ interface AppRootGraph : MetroViewModelMultibindings { val commandQueue: CommandQueue val commandExecutor: CommandExecutor val localAlertUtils: LocalAlertUtils + val periodicMaintenance: PeriodicMaintenance val bolusProgressData: BolusProgressData val persistenceLayer: PersistenceLayer val cloudStorageManager: CloudStorageManager diff --git a/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt b/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt index 396e43eb38c1..c6d15337ea47 100644 --- a/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt +++ b/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt @@ -58,6 +58,7 @@ import app.aaps.di.ExternalOptionsOverride import app.aaps.di.PluginSource import app.aaps.di.mergePlugins import app.aaps.implementation.lifecycle.ProcessLifecycleListener +import app.aaps.implementation.maintenance.PeriodicMaintenance import app.aaps.implementation.notifications.SnackbarNotificationFallback import app.aaps.implementation.plugin.PluginStore import app.aaps.implementation.profile.ProfileSwitchScheduler @@ -279,6 +280,7 @@ class MetroGraphs( val widgetUpdater: WidgetUpdater get() = root.widgetUpdater val commandQueue: CommandQueue get() = root.commandQueue val localAlertUtils: LocalAlertUtils get() = root.localAlertUtils + val periodicMaintenance: PeriodicMaintenance get() = root.periodicMaintenance val persistenceLayer: PersistenceLayer get() = root.persistenceLayer val appRepository: AppRepository get() = root.appRepository val constraintsChecker: ConstraintsChecker get() = root.constraintsChecker diff --git a/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt b/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt index 5d8d78c7e132..00dd903bb2e8 100644 --- a/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt +++ b/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt @@ -37,7 +37,7 @@ class ContributedPluginsTest { // sensitivity 100, 110, 120, 200, 210, 220, 230, 240, - 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, + 400, 410, 420, 430, 440, 446, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, // sync - the every-build part of the 300 block. SmsCommunicator 300 and Tidepool 320 are // @NotNSClient; 340 (OpenHumans) comes from its own graph extension. 310, 330, 350, 360, 370, diff --git a/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt b/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt index 9f0b20309085..45e52f40c7dc 100644 --- a/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt +++ b/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt @@ -2,6 +2,8 @@ package app.aaps.di.metro import app.aaps.implementation.alerts.EatReminderReceiver import app.aaps.implementation.androidNotification.AlarmMuteReceiver +import app.aaps.implementation.androidNotification.CgmAlarmAcknowledgeReceiver +import app.aaps.implementation.androidNotification.HypoTreatedReceiver import app.aaps.persistentNotification.DummyService import app.aaps.plugins.automation.TimerReminderReceiver import app.aaps.plugins.automation.services.LocationService @@ -48,6 +50,18 @@ class ReceiverInjectorsTest { assertThat(injectors.keys).contains(AlarmMuteReceiver::class) } + /** Same case for the "Hypo treated" button on the low glucose alarm notification. */ + @Test + fun `the hypo treated receiver has an injector`() { + assertThat(injectors.keys).contains(HypoTreatedReceiver::class) + } + + /** Same case for the "Acknowledge" button on a CGM alarm notification. */ + @Test + fun `the cgm alarm acknowledge receiver has an injector`() { + assertThat(injectors.keys).contains(CgmAlarmAcknowledgeReceiver::class) + } + /** The "time to eat" alarm and its Stop / +5 min buttons; a missing entry is a crash when the timer ends. */ @Test fun `the eat reminder receiver has an injector`() { diff --git a/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt b/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt index 3b4dcf696f15..c6bbc4f31e37 100644 --- a/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt +++ b/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt @@ -179,6 +179,7 @@ class GraphScopeStabilityTest { "pairingOfferFetcher", "pairingOfferPublisher", "passwordCheck", + "periodicMaintenance", "persistenceLayer", "pluginPermissions", "pluginStore", diff --git a/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt b/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt index 7cccc8c7b676..9895d16da618 100644 --- a/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt +++ b/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt @@ -114,6 +114,15 @@ class RawPreferenceStoreScanTest { "pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/Delegates.kt" to "ComboV2, same migration", "pump/insight/src/main/kotlin/app/aaps/pump/insight/utils/PairingDataStorage.kt" to "Insight pump pairing. Open question 6.2: moving it into registered keys would make 'restore pump configuration' work after a reinstall, but it would also put a pump secret in the export file. Needs an answer before it moves.", + // Added with the Dexcom ONE+ / G7 driver. This file stores the driver's own sensor state: the + // sensor identity and the pairing key, in one preference file per sensor slot. It is in this + // list and not in `allowed` because it fits none of the reasons there: registered composed + // keys (one argument per sensor slot) could hold it. It can move to registered keys later, + // with a migration that copies the values from the old file. + // The store itself is shared code and never touches the file. This small Android adapter is the + // only place that opens it. + "plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefsAndroid.kt" to + "Dexcom ONE+ / G7 sensor identity, including the pairing key. Live device state like the Insight pairing above, so it needs a migration, not a removal. 14 keys, in one file per sensor slot (production or pre-soak sensor), so the move needs registered per-slot keys plus a migration that copies from the old file and keeps it until the move is confirmed on a real sensor. Whether the keys are exportable (a sensor would then survive a change of phone, but the pairing key would be in the export file) needs an answer before it moves.", ) @Test diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index c51f7e72cda4..95d47551ef49 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -77,7 +77,37 @@ active_scene|StringNonKey|false actual_basal_profile|MedtrumStringNonKey|true age|StringKey|true alarm_setting|MedtrumStringKey|true +alert_cgm_expiring_lead_hours|IntKey|true +alert_cgm_fall_rate_repeat_minutes|IntKey|true +alert_cgm_fall_rate_sound|StringKey|true +alert_cgm_high_delay_minutes|IntKey|true +alert_cgm_high_repeat_minutes|IntKey|true +alert_cgm_high_sound|StringKey|true +alert_cgm_low_repeat_minutes|IntKey|true +alert_cgm_low_sound|StringKey|true +alert_cgm_rise_rate_repeat_minutes|IntKey|true +alert_cgm_rise_rate_sound|StringKey|true +alert_cgm_sensor_ended_sound|StringKey|true +alert_cgm_sensor_expired_repeat_minutes|IntKey|true +alert_cgm_sensor_failed_repeat_minutes|IntKey|true +alert_cgm_sensor_failed_sound|StringKey|true +alert_cgm_sensor_issue_minutes|IntKey|true +alert_cgm_sensor_issue_repeat_minutes|IntKey|true +alert_cgm_sensor_issue_sound|StringKey|true +alert_cgm_signal_loss_sound|StringKey|true +alert_cgm_signal_lost_minutes|IntKey|true +alert_cgm_signal_lost_repeat_minutes|IntKey|true +alert_cgm_urgent_low_repeat_minutes|IntKey|true +alert_cgm_urgent_low_soon_repeat_minutes|IntKey|true +alert_cgm_urgent_low_soon_sound|StringKey|true +alert_cgm_urgent_low_sound|StringKey|true +alert_hyper_threshold|UnitDoubleKey|true +alert_hypo_threshold|UnitDoubleKey|true alert_override_dnd|BooleanKey|true +alert_rapid_fall_drop_mgdl|IntKey|true +alert_rapid_fall_window|IntKey|true +alert_rapid_rise_mgdl|IntKey|true +alert_rapid_rise_window|IntKey|true allow_hardware_pump|BooleanNonKey|true always_use_shortavg|BooleanKey|true app_expiration_%s|LongComposedKey|true @@ -108,6 +138,7 @@ bolussnooze_dia_divisor|DoubleKey|true boluswizard_percentage|IntKey|true bt_watchdog_last|LongNonKey|true bt_watchdog|BooleanKey|true +calibration_entries_valid_from|CalibrationLongKey|false carbsReqThreshold|IntKey|true carbs_button_increment_1|IntKey|true carbs_button_increment_2|IntKey|true @@ -122,6 +153,10 @@ carelevo_patch_info|CarelevoStringNonKey|false carelevo_temp_basal_infusion_info|CarelevoStringNonKey|false carelevo_user_setting_info|CarelevoStringNonKey|false categorize_uam_as_basal|BooleanKey|true +cgmAlarmRuntime|LocalAlertStringKey|false +cgmAlarmSource|LocalAlertStringKey|false +cgmAlarmsMutedUntil|LocalAlertLongKey|false +cgm_alarm_controls|CgmAlarmIntentKey|false combov2-bt-address-key|ComboStringNonKey|true combov2-cp-cipher-key|ComboStringNonKey|true combov2-key-response-address-key|ComboIntNonKey|true @@ -159,6 +194,13 @@ danars_v3_randompairing_key_%s|DanaStringComposedKey|true danars_v3_randomsync_key_%s|DanaStringComposedKey|true device_type|MedtrumIntNonKey|true dexcom_lognssensorchange|BooleanKey|true +dexcom_oneplus_own_sensor_change_at|DexcomOnePlusLongKey|false +dexcom_oneplus_send_calibration_to_sensor|DexcomOnePlusBooleanKey|false +dexcom_oneplus_staging_auto_promote_hours|DexcomOnePlusIntKey|true +dexcom_oneplus_staging_auto_promote|DexcomOnePlusBooleanKey|false +dexcom_oneplus_start|DexcomOnePlusIntentKey|false +dexcom_oneplus_warmup|DexcomOnePlusIntentKey|false +dexcom_oneplus_watch_direct|DexcomOnePlusBooleanKey|false dexcomg5_nsupload|BooleanKey|true diaconn_bt_selector|DiaconnIntentKey|false diaconn_g8_appuid|DiaconnStringNonKey|true @@ -178,9 +220,22 @@ enableSMB_with_COB|BooleanKey|true enableSMB_with_high_temptarget|BooleanKey|true enableSMB_with_temptarget|BooleanKey|true enable_carbs_required_alert_local|BooleanKey|true +enable_cgm_rise_rate_alert|BooleanKey|true +enable_cgm_second_sensor_ready_alert|BooleanKey|true +enable_cgm_sensor_expired_alert|BooleanKey|true +enable_cgm_sensor_expiring_alert|BooleanKey|true +enable_cgm_sensor_failed_alert|BooleanKey|true +enable_cgm_sensor_issue_alert|BooleanKey|true +enable_cgm_signal_lost_alert|BooleanKey|true +enable_cgm_urgent_low_alert|BooleanKey|true +enable_cgm_urgent_low_soon_alert|BooleanKey|true +enable_cgm_warmup_done_alert|BooleanKey|true enable_fabric2|BooleanKey|true +enable_hyper_alert|BooleanKey|true +enable_hypo_alert|BooleanKey|true enable_missed_bg_readings|BooleanKey|true enable_pump_unreachable_alert|BooleanKey|true +enable_rapid_fall_alert|BooleanKey|true enable_unattended_export|BooleanKey|true eopatch_alarms|EopatchStringNonKey|true eopatch_bolus_current|EopatchStringNonKey|true diff --git a/appshell/build.gradle.kts b/appshell/build.gradle.kts index c4780b81231a..a67597e877c0 100644 --- a/appshell/build.gradle.kts +++ b/appshell/build.gradle.kts @@ -4,6 +4,19 @@ plugins { alias(libs.plugins.metro) } +/** + * Modules under `:plugins:` that are libraries, not feature plugins. They register nothing into the + * plugin map, so this shell does not need them: the plugin that uses one depends on it directly. + * They are also left out because they have no Apple targets, and listing one in commonMain would make + * every iOS build of this module fail at dependency resolution. + */ +val PLUGIN_LIBRARIES = setOf( + // KEKS authentication for Dexcom ONE+ / G7 (Android and JVM only). + ":plugins:libkeks", + // The Dexcom ONE+ / G7 BLE driver (Android only). The plugin itself is in :plugins:source. + ":plugins:dexcom_oneplus", +) + /** * The app's shell: navigation and the composable root. * @@ -52,7 +65,7 @@ kotlin { // with the navigation graph that routes to them; `api` so `:app` still builds its // graph against them. Adding or removing a plugin stays an edit in settings.gradle. rootProject.subprojects - .filter { it.path.startsWith(":plugins:") && it.buildFile.exists() } + .filter { it.path.startsWith(":plugins:") && it.buildFile.exists() && it.path !in PLUGIN_LIBRARIES } .forEach { api(project(it.path)) } api(libs.jetbrains.compose.runtime) diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt index e7e3f98ddbde..1435bbdaa34b 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt @@ -16,6 +16,9 @@ enum class SourceSensor(val text: String, val aliases: Set = emptySet()) DEXCOM_UNKNOWN("Dexcom", setOf("AAPS-Dexcom", "Share Follow")), DEXCOM_G6("Dexcom G6", setOf("AAPS-DexcomG6", "G6 Native")), DEXCOM_G7("Dexcom G7", setOf("AAPS-DexcomG7", "G7 Native", "G7")), + + /** Dexcom ONE+ and G7, read directly over Bluetooth by the AAPS Dexcom ONE+ / G7 source plugin. */ + DEXCOM_ONEPLUS_NATIVE("AAPS-DexcomOnePlus"), LIBRE_1( "Libre1", setOf("Other App", "Network libre", "BlueReader", "Transmiter PL", "Blucon", "Tomato", "Rfduino", "LimiTTer", "Bubble", "Atom", "Glimp") diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt index 6eedcffb8d25..8cf2844edf71 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt @@ -20,6 +20,8 @@ private val ADVANCED_FILTERING_SENSORS = setOf( SourceSensor.DEXCOM_UNKNOWN, SourceSensor.DEXCOM_G6, SourceSensor.DEXCOM_G7, + // Dexcom ONE+ / G7 read by the AAPS native plugin. The sensor filters internally, as above. + SourceSensor.DEXCOM_ONEPLUS_NATIVE, SourceSensor.LIBRE_2, SourceSensor.LIBRE_3, SourceSensor.SYAI_TAG, diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt index c161476c2a5a..f3efd93f1979 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt @@ -29,6 +29,7 @@ enum class Sources { BG, //From BG plugin => Add One Source per BG Source for Calibration or Sensor Change Aidex, Dexcom, + DexcomOnePlus, Eversense, Glimp, MM640g, diff --git a/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt b/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt index 3757d506c281..3363929f9d65 100644 --- a/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt +++ b/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt @@ -1,6 +1,7 @@ package app.aaps.core.data.model import kotlin.test.Test +import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -18,6 +19,13 @@ class SourceSensorExtensionsTest { assertTrue(SourceSensor.DEXCOM_G6.advancedFilteringSupported()) assertTrue(SourceSensor.DEXCOM_G7.advancedFilteringSupported()) assertTrue(SourceSensor.DEXCOM_G7.advancedFilteringSupported()) + assertTrue(SourceSensor.DEXCOM_ONEPLUS_NATIVE.advancedFilteringSupported()) + } + + @Test + fun `dexcom one plus native is found by its text`() { + assertEquals(SourceSensor.DEXCOM_ONEPLUS_NATIVE, SourceSensor.fromString("AAPS-DexcomOnePlus")) + assertEquals("AAPS-DexcomOnePlus", SourceSensor.DEXCOM_ONEPLUS_NATIVE.text) } @Test diff --git a/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt b/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt index 8218c80e408a..a96df5046dff 100644 --- a/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt +++ b/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt @@ -345,4 +345,57 @@ class EventDataTest { assertThat(old).doesNotContain("carbsType") assertThat(EventData.deserialize(old)).isEqualTo(EventData.ActionWizardPreCheck(30, 100, CarbsType.BREAD)) } + + @Test + fun cgmAlarmMessagesRoundTrip() { + listOf( + EventData.CgmAlarm(id = "urgent_low", title = "Urgent low", message = "52 mg/dL", vibrationSeconds = 10, urgent = true), + EventData.CgmAlarm(id = "high", title = "High", message = "", vibrationSeconds = 0, urgent = false), + EventData.CgmAlarmCancel("urgent_low"), + EventData.CgmAlarmAcknowledge("signal_loss") + ).forEach { + assertThat(EventData.deserializeByte(it.serializeByte())).isEqualTo(it) + assertThat(EventData.deserialize(it.serialize())).isEqualTo(it) + } + } + + @Test + fun directToWatchMessagesSurviveBothWireFormats() { + listOf( + EventData.CgmWatchDirect(active = true, pairingCode = "1234", address = "AA:BB:CC:DD:EE:FF", serial = "SN1", sensorName = "DXCM12"), + EventData.CgmWatchDirect(active = false), + EventData.CgmWatchStatus(EventData.CgmWatchState.CONNECTED, address = "AA:BB:CC:DD:EE:FF", latestReadingAt = 5L, batteryRestricted = true), + EventData.CgmWatchStatus(EventData.CgmWatchState.REFUSED, detail = "slot in use") + ).forEach { + assertThat(EventData.deserializeByte(it.serializeByte())).isEqualTo(it) + assertThat(EventData.deserialize(it.serialize())).isEqualTo(it) + } + } + + @Test + fun cgmAlarmMessagesDoNotChangeTheEncodingOfOlderMessages() { + // The CGM alarm messages are appended at the end of EventData. An older message must still + // decode to itself, and must not decode to one of the new ones. + val old = EventData.AlarmStopped(5L) + assertThat(EventData.deserializeByte(old.serializeByte())).isEqualTo(old) + assertThat(EventData.deserialize(old.serialize())).isEqualTo(old) + assertThat(EventData.CgmAlarmCancel("x").serialize()).contains("CgmAlarmCancel") + } + + @Test + fun directToWatchNeverPrintsThePairingCode() { + val message = EventData.CgmWatchDirect(active = true, pairingCode = "9876", address = "AA:BB") + assertThat(message.toString()).doesNotContain("9876") + } + + @Test + fun aReadingFromTheSensorKeepsItsMarkAndAnOldReadingHasNone() { + val fromWatch = EventData.SingleBg(dataset = 0, timeStamp = 1L, sgv = 100.0, high = 180.0, low = 70.0, fromSensor = true) + assertThat((EventData.deserializeByte(fromWatch.serializeByte()) as EventData.SingleBg).fromSensor).isTrue() + assertThat((EventData.deserialize(fromWatch.serialize()) as EventData.SingleBg).fromSensor).isTrue() + // A phone without direct-to-watch sends no such field: the value is the phone's own. + val fromPhone = EventData.SingleBg(dataset = 0, timeStamp = 1L, sgv = 100.0, high = 180.0, low = 70.0) + assertThat(fromPhone.serialize()).doesNotContain("fromSensor") + assertThat((EventData.deserialize(fromPhone.serialize()) as EventData.SingleBg).fromSensor).isFalse() + } } diff --git a/core/interfaces/src/androidMain/res/values/strings.xml b/core/interfaces/src/androidMain/res/values/strings.xml index a9303e1fa71d..1c86a834e6c3 100644 --- a/core/interfaces/src/androidMain/res/values/strings.xml +++ b/core/interfaces/src/androidMain/res/values/strings.xml @@ -39,6 +39,13 @@ days hours minutes + + minute + hour + hours + day + days + %1$s %2$s m %1$dh %2$dm remaining %1$dm remaining diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt new file mode 100644 index 000000000000..e6293f830491 --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt @@ -0,0 +1,63 @@ +package app.aaps.core.interfaces.alerts + +import app.aaps.core.interfaces.notifications.NotificationId + +/** + * Alarms that stand in for one another. While one is going off, the ones after it in the same + * group stay quiet: an urgent low needs no low alarm on top, and an ended sensor needs no "ending + * soon" on top. [INFO] alarms never quiet each other. + */ +enum class CgmAlarmGroup { LOW, HIGH, SENSOR, INFO } + +/** + * The CGM alarms, most important first. That order decides which alarm of a [group] goes off when + * several conditions hold at the same time. + * + * One alarm layer for every BG source: the glucose alarms read the stored glucose, the sensor + * alarms read the sensor state of a source that reports it + * ([app.aaps.core.interfaces.source.CgmSensorAlertProvider]). The alarms only notify. They never + * change the glucose values the loop receives, and never change dosing. + * + * @param id stable name, used in the stored alarm state and in the messages to the watch. It must + * not change once released. + * @param notificationId the notification this alarm posts. + * @param reminds true for an alarm that goes off again every few minutes until it is acknowledged. + * False for an information that is shown once per episode. + */ +enum class CgmAlarmType( + val id: String, + val group: CgmAlarmGroup, + val notificationId: NotificationId, + val reminds: Boolean = true, +) { + + URGENT_LOW("urgent_low", CgmAlarmGroup.LOW, NotificationId.CGM_URGENT_LOW), + SENSOR_FAILED("sensor_failed", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_FAILED), + URGENT_LOW_SOON("urgent_low_soon", CgmAlarmGroup.LOW, NotificationId.CGM_URGENT_LOW_SOON), + LOW("low", CgmAlarmGroup.LOW, NotificationId.BG_HYPO), + FALL_RATE("fall_rate", CgmAlarmGroup.LOW, NotificationId.BG_RAPID_FALL), + SENSOR_ENDED("sensor_ended", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_EXPIRED), + HIGH("high", CgmAlarmGroup.HIGH, NotificationId.BG_HYPER), + RISE_RATE("rise_rate", CgmAlarmGroup.HIGH, NotificationId.CGM_RAPID_RISE), + SIGNAL_LOSS("signal_loss", CgmAlarmGroup.SENSOR, NotificationId.CGM_SIGNAL_LOST), + SENSOR_ISSUE("sensor_issue", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_ISSUE), + SENSOR_ENDING_SOON("sensor_ending_soon", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_EXPIRING, reminds = false), + SECOND_SENSOR_READY("second_sensor_ready", CgmAlarmGroup.INFO, NotificationId.CGM_SECOND_SENSOR_READY, reminds = false), + WARMUP_DONE("warmup_done", CgmAlarmGroup.INFO, NotificationId.CGM_WARMUP_DONE, reminds = false); + + /** True for the alarms that read glucose. The others read the sensor state. */ + val isGlucose: Boolean get() = group == CgmAlarmGroup.LOW || group == CgmAlarmGroup.HIGH + + /** + * The mute timer can never silence this alarm. Only urgent low: a person who muted the alarms for + * a meeting must still be woken by a glucose of 55 mg/dL or less. + */ + val neverMuted: Boolean get() = this == URGENT_LOW + + companion object { + + fun byId(id: String): CgmAlarmType? = entries.firstOrNull { it.id == id } + + fun byNotificationId(id: NotificationId): CgmAlarmType? = entries.firstOrNull { it.notificationId == id } + } +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt index 0c1bfc46fd0a..99090cfc26fb 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt @@ -1,5 +1,7 @@ package app.aaps.core.interfaces.alerts +import kotlinx.coroutines.flow.StateFlow + interface LocalAlertUtils { /** @@ -32,4 +34,53 @@ interface LocalAlertUtils { * Overview notification with sound, Therapy event */ suspend fun checkStaleBGAlert() + + /** + * Run the CGM alarms (see [CgmAlarmType]): check the current glucose against the glucose alarms + * the user has set up (urgent low, urgent low soon, low, fall rate, high, rise rate), and the + * sensor state of the active BG source against the sensor alarms, then raise, repeat or clear + * their notifications. + * + * The glucose alarms work for any CGM source, because they read the last stored glucose. The + * sensor alarms work for a source that reports its sensor state + * ([app.aaps.core.interfaces.source.CgmSensorAlertProvider]). It only notifies: it never changes + * dosing, the loop or the glucose values the loop receives. The glucose alarms do nothing on stale + * data, because the stale-data alarm owns that case. + */ + suspend fun checkGlucoseAlerts() + + /** + * The user says they treated the current hypo (took carbs): clear the low-glucose alarm and hold + * it for about the time carbs need to work, instead of the shorter automatic repeat. + * + * This only silences. The alarm comes back by itself if glucose is still low when the hold ends, + * and [checkGlucoseAlerts] clears the hold as soon as glucose has recovered. + * + * Returns at once. The hold is written in the background, after a check that is running at that + * moment has finished, so the check cannot overwrite it. + */ + fun snoozeHypoAfterTreatment() + + /** + * The user acknowledged a CGM alarm ([type]), or every CGM alarm that is going off when [type] is + * null: it stops, and stays quiet for its repeat time. When the repeat time is over and the + * condition is still there, it goes off again. Returns at once. + */ + fun acknowledgeCgmAlarms(type: CgmAlarmType? = null) + + /** + * Mute the CGM alarms for [minutes], or end the mute with 0. Urgent low is never muted + * ([CgmAlarmType.neverMuted]). Returns at once. + */ + fun muteCgmAlarms(minutes: Int) + + /** When the mute of the CGM alarms ends (epoch ms), 0 when they are not muted. */ + val cgmAlarmsMutedUntil: StateFlow + + /** + * Play [type] once as a test, with its sound and on the same path as a real alarm, so the user + * hears what it sounds like at night. It goes on until the user dismisses it. It changes nothing + * in the state of the real alarm. + */ + fun testCgmAlarm(type: CgmAlarmType) } \ No newline at end of file diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt index 41b56e40e7ab..ae1e26b3c96c 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt @@ -47,4 +47,26 @@ interface Calibration { * re-evaluates everything. This is a UX hint, not a contract. */ suspend fun checkPreconditions(): AddEntryResult + + /** + * Leave every calibration entry older than [timestamp] (epoch ms) out of the fit from now on. + * + * For a BG source that swaps sensors inside one recorded sensor session: a pre-soaked sensor + * that is made the production sensor gets a session that starts at its own start, hours before + * the swap. Without this cut, fingersticks paired with the retired sensor would be fitted onto + * the new one. + * + * Rules: + * - The cut only moves forward. A [timestamp] that is not later than the current cut is ignored. + * - A [timestamp] in the future (more than a few minutes after now) is ignored and logged, so a + * wrong clock cannot hide every new fingerstick. + * - The fit uses entries from max(session start, cut). So a later SENSOR_CHANGE wins over an + * older cut, and the cut needs no reset at the next sensor. + * - A SENSOR_CHANGE that is entered with a time older than the cut is still clipped by the cut: + * entries between that SENSOR_CHANGE and the cut stay out of the fit. + * - The cut is cleared when the database is cleared. + * + * A plugin that fits nothing has nothing to cut, so the default does nothing. + */ + suspend fun ignoreEntriesBefore(timestamp: Long) {} } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt new file mode 100644 index 000000000000..5c71c00dfd3d --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt @@ -0,0 +1,24 @@ +package app.aaps.core.interfaces.notifications + +/** + * Action button an alarm carries on its **system** notification (lock screen, notification shade), + * on top of the in-app notification card. + * + * Declared per [NotificationId] and not passed where the alarm is posted, because the button must + * survive a trip through the operating system: on Android it goes through a `PendingIntent` to a + * `BroadcastReceiver`, on iOS through a notification category and the notification delegate. The + * in-app [NotificationAction] holds a lambda, which cannot make that trip. Each platform resolves + * the label and what the button does. + */ +enum class AlarmAction { + + /** "Hypo treated": the user took carbs, so hold the low-glucose alarms while they work. */ + HYPO_TREATED, + + /** + * "Acknowledge" on a CGM alarm: every CGM alarm that is going off stops and stays quiet for its + * repeat time. It is not a mute: when the repeat time is over and the condition is still there, + * the alarm goes off again. + */ + CGM_ACKNOWLEDGE +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt index 30ab5df22703..edef69d3cf5a 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt @@ -13,24 +13,101 @@ package app.aaps.core.interfaces.notifications * extra, and a resource id is a build specific number - the same value means something else in * the next build. The stable [name] travels instead. * - * Deliberately a closed set: the sound files live in `:core:ui/res/raw` and there are five of them. - * Adding one means adding an entry here, which makes the `when` in the Android resolver stop - * compiling until it is handled. + * Deliberately a closed set: the sound files live in `:core:ui/res/raw`. Adding one means adding an + * entry here, which makes the `when` in the Android resolver stop compiling until it is handled. + * + * The `TRIO_*` sounds come from Trio (MIT licence, see `core/ui/SOUNDS.md`). Only the CGM alarms + * offer them, as the sound the user chose for one alarm. The iOS build copies every file named + * here into the app bundle, so [fileName] and [fileExtension] must match the file in `res/raw`. + * + * @param fileName the file name without extension, the same on Android and iOS. + * @param fileExtension the file type, `mp3` for the AAPS sounds, `m4a` for the Trio sounds. + * @param trioSet the Trio alarm this sound was made for, null for an AAPS sound or a Trio tone that + * any alarm may use. */ -enum class AlarmSound { +enum class AlarmSound( + val fileName: String, + val fileExtension: String = "mp3", + val trioSet: TrioSoundSet? = null, +) { /** Standard alarm. */ - ALARM, + ALARM("alarm"), /** Urgent alarm - used for the Nightscout urgent announcement path. */ - URGENT_ALARM, + URGENT_ALARM("urgentalarm"), /** General error. */ - ERROR, + ERROR("error"), /** Bolus delivery failure. */ - BOLUS_ERROR, + BOLUS_ERROR("boluserror"), /** The "time to eat" timer. A soft kitchen timer, so it is not taken for a warning. */ - EAT_REMINDER + EAT_REMINDER("eatreminder"), + + // Trio sounds: style (acoustic, electronic), the alarm they were made for, urgency level. + TRIO_ACOUSTIC_URGENT_LOW_MILD("trio_acoustic_ulg_mild", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ACOUSTIC_URGENT_LOW_MEDIUM("trio_acoustic_ulg_medium", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ACOUSTIC_URGENT_LOW_HARSH("trio_acoustic_ulg_harsh", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ACOUSTIC_LOW_MILD("trio_acoustic_lg_mild", "m4a", TrioSoundSet.LOW), + TRIO_ACOUSTIC_LOW_MEDIUM("trio_acoustic_lg_medium", "m4a", TrioSoundSet.LOW), + TRIO_ACOUSTIC_LOW_HARSH("trio_acoustic_lg_harsh", "m4a", TrioSoundSet.LOW), + TRIO_ACOUSTIC_LOW_SOON_MILD("trio_acoustic_lgs_mild", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ACOUSTIC_LOW_SOON_MEDIUM("trio_acoustic_lgs_medium", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ACOUSTIC_LOW_SOON_HARSH("trio_acoustic_lgs_harsh", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ACOUSTIC_HIGH_MILD("trio_acoustic_hg_mild", "m4a", TrioSoundSet.HIGH), + TRIO_ACOUSTIC_HIGH_MEDIUM("trio_acoustic_hg_medium", "m4a", TrioSoundSet.HIGH), + TRIO_ACOUSTIC_HIGH_HARSH("trio_acoustic_hg_harsh", "m4a", TrioSoundSet.HIGH), + TRIO_ACOUSTIC_DEVICE_CRITICAL_MILD("trio_acoustic_dcr_mild", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ACOUSTIC_DEVICE_CRITICAL_MEDIUM("trio_acoustic_dcr_medium", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ACOUSTIC_DEVICE_CRITICAL_HARSH("trio_acoustic_dcr_harsh", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ACOUSTIC_DEVICE_TIME_SENSITIVE_MILD("trio_acoustic_dts_mild", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ACOUSTIC_DEVICE_TIME_SENSITIVE_MEDIUM("trio_acoustic_dts_medium", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ACOUSTIC_DEVICE_TIME_SENSITIVE_HARSH("trio_acoustic_dts_harsh", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ELECTRONIC_URGENT_LOW_MILD("trio_electronic_ulg_mild", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ELECTRONIC_URGENT_LOW_MEDIUM("trio_electronic_ulg_medium", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ELECTRONIC_URGENT_LOW_HARSH("trio_electronic_ulg_harsh", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ELECTRONIC_LOW_MILD("trio_electronic_lg_mild", "m4a", TrioSoundSet.LOW), + TRIO_ELECTRONIC_LOW_MEDIUM("trio_electronic_lg_medium", "m4a", TrioSoundSet.LOW), + TRIO_ELECTRONIC_LOW_HARSH("trio_electronic_lg_harsh", "m4a", TrioSoundSet.LOW), + TRIO_ELECTRONIC_LOW_SOON_MILD("trio_electronic_lgs_mild", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ELECTRONIC_LOW_SOON_MEDIUM("trio_electronic_lgs_medium", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ELECTRONIC_LOW_SOON_HARSH("trio_electronic_lgs_harsh", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ELECTRONIC_HIGH_MILD("trio_electronic_hg_mild", "m4a", TrioSoundSet.HIGH), + TRIO_ELECTRONIC_HIGH_MEDIUM("trio_electronic_hg_medium", "m4a", TrioSoundSet.HIGH), + TRIO_ELECTRONIC_HIGH_HARSH("trio_electronic_hg_harsh", "m4a", TrioSoundSet.HIGH), + TRIO_ELECTRONIC_DEVICE_CRITICAL_MILD("trio_electronic_dcr_mild", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ELECTRONIC_DEVICE_CRITICAL_MEDIUM("trio_electronic_dcr_medium", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ELECTRONIC_DEVICE_CRITICAL_HARSH("trio_electronic_dcr_harsh", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ELECTRONIC_DEVICE_TIME_SENSITIVE_MILD("trio_electronic_dts_mild", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ELECTRONIC_DEVICE_TIME_SENSITIVE_MEDIUM("trio_electronic_dts_medium", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ELECTRONIC_DEVICE_TIME_SENSITIVE_HARSH("trio_electronic_dts_harsh", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_TONE_GLASS_BELL("trio_tone_glass_bell", "m4a", null), + TRIO_TONE_HARP("trio_tone_harp", "m4a", null), + TRIO_TONE_MEOW("trio_tone_meow", "m4a", null), + TRIO_TONE_SAW_WAVE("trio_tone_saw_wave", "m4a", null), + TRIO_TONE_HARD_SAW_WAVE("trio_tone_hard_saw_wave", "m4a", null), + TRIO_TONE_SINE_WAVE("trio_tone_sine_wave", "m4a", null), + TRIO_TONE_OPEN_CAN("trio_tone_open_can", "m4a", null), + TRIO_TONE_OPEN_WRAPPER("trio_tone_open_wrapper", "m4a", null); + + /** True for a sound from Trio, see `core/ui/SOUNDS.md`. */ + val isTrio: Boolean get() = fileName.startsWith("trio_") + + companion object { + + /** The Trio tones that any alarm may use. */ + val trioTones: List get() = entries.filter { it.isTrio && it.trioSet == null } + + /** The Trio sounds made for [set], mild to harsh, acoustic first. */ + fun trioSoundsFor(set: TrioSoundSet): List = entries.filter { it.trioSet == set } + } } + +/** + * The Trio alarm a sound set was written for. Several CGM alarms share a set where Trio has none of + * their own: the rate alarms use the low soon and high sets, and the sensor alarms use the device + * sets. + */ +enum class TrioSoundSet { URGENT_LOW, LOW, LOW_SOON, HIGH, DEVICE_CRITICAL, DEVICE_TIME_SENSITIVE } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt index 560093ac5224..284d4a7f1768 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt @@ -31,7 +31,9 @@ import app.aaps.core.interfaces.notifications.NotificationLevel.URGENT enum class NotificationId( val defaultLevel: NotificationLevel, val category: NotificationCategory, - val allowMultiple: Boolean = false + val allowMultiple: Boolean = false, + /** Extra action button carried by this alarm's system notification, if any. */ + val alarmAction: AlarmAction? = null ) { // Profile @@ -262,7 +264,33 @@ enum class NotificationId( // A real pump is selected, but AAPS has no Bluetooth (Nearby devices) permission, so no command can reach the // pump and the queue fails them (#5440). It removes itself once the permission is back. IMPORTANT, not URGENT: // a bolus that fails because of it raises its own alarm. Appended at the END for the same reason as above. - BLUETOOTH_PERMISSION_MISSING(IMPORTANT, PUMP); + BLUETOOTH_PERMISSION_MISSING(IMPORTANT, PUMP), + + // A pre-soak sensor of a native CGM driver was made the production sensor by the app itself, without the + // user pressing the promote button. Appended at the END for the same reason as above. + CGM_STAGING_AUTO_PROMOTED(NORMAL, CGM), + + // CGM alarms (`CgmAlarmType`), one alarm layer for every BG source. The glucose ones read the + // stored glucose; the sensor ones are raised only for a source that reports its sensor state + // ([app.aaps.core.interfaces.source.CgmSensorAlertProvider]). They only notify; they never change + // dosing. An alarm the user gave a sound is posted URGENT, whatever its level here. Appended at + // the END for the same reason as above. + BG_HYPO(URGENT, CGM, alarmAction = AlarmAction.HYPO_TREATED), + BG_HYPER(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + BG_RAPID_FALL(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_URGENT_LOW(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_URGENT_LOW_SOON(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_RAPID_RISE(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_FAILED(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_EXPIRED(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_EXPIRING(IMPORTANT, CGM), + CGM_SIGNAL_LOST(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_ISSUE(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_WARMUP_DONE(NORMAL, CGM), + CGM_SECOND_SENSOR_READY(NORMAL, CGM), + + /** The test button of a CGM alarm: its sound and text, once, until the user dismisses it. */ + CGM_ALARM_TEST(URGENT, CGM); companion object { 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 1eb8e4182d96..fb0b72f9b39e 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 @@ -337,7 +337,11 @@ sealed class EventData : Event() { val color: Int = 0, val deltaMgdl: Double? = null, val avgDeltaMgdl: Double? = null, - val id: Int = 0 + val id: Int = 0, + // True when the watch read this value from the sensor itself (direct-to-watch), not from the phone. + // Such a value is for the watch faces only. Keep new fields at the END of this class: the ProtoBuf + // wire format numbers fields by declaration order. + val fromSensor: Boolean = false ) : EventDataSet, EventData(), Comparable { override fun equals(other: Any?): Boolean = @@ -672,4 +676,89 @@ sealed class EventData : Event() { val durations: List, val title: String = "" ) : EventData() + + // CGM alarms. Appended at the END of the class on purpose, so nothing above them moves. + + /** + * Mobile -> Wear: a CGM alarm is going off on the phone (sent again for each reminder). The watch + * shows it with an Acknowledge button and vibrates through its silent mode, for [vibrationSeconds] + * (0 = no vibration), stronger when [urgent]. [id] is the `CgmAlarmType.id`, so a later + * [CgmAlarmCancel] or [CgmAlarmAcknowledge] can name it. + */ + @Serializable + data class CgmAlarm( + val id: String, + val title: String, + val message: String, + val vibrationSeconds: Int, + val urgent: Boolean + ) : EventData() + + /** Mobile -> Wear: the CGM alarm [id] is over (acknowledged somewhere, or its cause is gone). Stop and remove it. */ + @Serializable + data class CgmAlarmCancel(val id: String) : EventData() + + /** Wear -> Mobile: the wearer acknowledged the CGM alarm [id] on the watch. */ + @Serializable + data class CgmAlarmAcknowledge(val id: String) : EventData() + + /** + * Mobile -> Wear: direct-to-watch for the Dexcom ONE+ / G7 the phone reads. With [active] the watch + * connects to the sensor itself, in the sensor's watch slot, next to the phone. It makes its own key + * from [pairingCode]; the phone's key never leaves the phone. Without [active] the watch lets the + * sensor go and forgets it. + * + * The watch's readings go to its faces only. They are never sent back to the phone and never reach + * the loop. + */ + @Serializable + data class CgmWatchDirect( + val active: Boolean, + val pairingCode: String? = null, + val address: String? = null, + val serial: String? = null, + val sensorName: String? = null + ) : EventData() { + + // Never print the pairing code in a log line. + override fun toString(): String = + "CgmWatchDirect(active=$active, address=$address, serial=$serial, sensorName=$sensorName, pairingCode=${if (pairingCode == null) "null" else "***"})" + } + + /** Wear -> Mobile: how the watch's own connection to the sensor is doing (direct-to-watch). */ + @Serializable + data class CgmWatchStatus( + val state: CgmWatchState, + /** The sensor the watch is set up for, so the phone can see when the watch holds an old one. */ + val address: String? = null, + val latestReadingAt: Long? = null, + /** The last problem, in plain words, for the phone's status line. */ + val detail: String? = null, + /** True when the watch may put the app to sleep in the background and miss readings. */ + val batteryRestricted: Boolean = false + ) : EventData() + + @Serializable + enum class CgmWatchState { + + /** Direct-to-watch is off. */ + OFF, + + /** The watch runs Android 11 or older; the sensor code needs Android 12. */ + NOT_SUPPORTED, + + /** The wearer has to allow Bluetooth on the watch. */ + NEEDS_PERMISSION, + BLUETOOTH_OFF, + + /** No key yet: the next connection runs the key exchange and the pairing prompt. */ + PAIRING, + + /** Paired, waiting for the sensor's next reading. The normal state between readings. */ + WAITING, + CONNECTED, + + /** The sensor refused the watch. [CgmWatchStatus.detail] says why. */ + REFUSED + } } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt index 95dda4a25a8b..4c58eb74db65 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt @@ -16,4 +16,34 @@ interface BgSource { * @return true if sensor has error and BG values should not be displayed */ fun hasSensorError(): Boolean = false -} \ No newline at end of file + + /** + * True when a fingerstick should go to the SENSOR instead of being fitted in the app. + * + * False for every source by default, and false even on a source that can do it until the user + * has switched it on. While it is true the app must not also fit a line on top of the same + * sensor's readings, or the correction is applied twice. + */ + fun calibratesInSensor(): Boolean = false + + /** + * Hand a fingerstick to the sensor's own algorithm. + * + * A sensor keeps a calibration it accepts for good: it cannot be edited or deleted + * afterwards, unlike a calibration entry stored in the app. Only ever call this for an explicit + * user action. + * + * @param glucoseMgdl the blood value + * @param bloodAtMs wall clock (epoch ms) used as the time of the blood. The calibration dialog + * passes the moment the user confirmed the value, not the moment of the finger prick. + */ + fun calibrateSensor(glucoseMgdl: Int, bloodAtMs: Long): SensorCalibrationResult = + SensorCalibrationResult.NotSupported + + /** + * Why the sensor must not get this fingerstick now, already readable by the user, or null when + * it may. Asked before the user confirms, so a refusal is shown before anything is sent. + * Only meaningful while [calibratesInSensor] is true. + */ + fun sensorCalibrationRefusal(glucoseMgdl: Int, bloodAtMs: Long): String? = null +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt new file mode 100644 index 000000000000..d6b750cc4e5d --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt @@ -0,0 +1,179 @@ +package app.aaps.core.interfaces.source + +/** + * Implemented by a [BgSource] that knows the state of its sensor and wants AAPS to raise the + * sensor alarms for it (sensor failed, ended, ending soon, no signal, sensor issue, warm-up done, + * second sensor ready). + * + * Optional: a source that does not implement it gets no sensor alarm at all, and nothing changes + * for it. The alarms are raised in one central place (`LocalAlertUtils.checkGlucoseAlerts`), which + * reads the active source as `activeBgSource as? CgmSensorAlertProvider`. + * + * The source only says what is true now. The user settings (which alarm is on, how long a signal + * may be lost before it warns, how often it repeats) are applied by the central check. The one + * exception is the warning time before the end, which the check passes in, see + * [CgmSensorAlertState.Expiring]. + * + * "Ending soon" and "ended" are measured against the end of the sensor's usable time, including + * any grace period the source knows of (a Dexcom ONE+ / G7 has 12 hours). The + * source shows the same end on its own status screen. + * + * The alarms only notify. Nothing here may change the glucose values the loop receives or dosing. + */ +interface CgmSensorAlertProvider { + + /** + * The most important sensor state at [nowMs]. One state at a time, in this order: + * [CgmSensorAlertState.Failed] > [CgmSensorAlertState.Expired] > [CgmSensorAlertState.SignalLost] > + * [CgmSensorAlertState.SensorIssue] > [CgmSensorAlertState.Expiring] > + * [CgmSensorAlertState.SecondSensorReady] > [CgmSensorAlertState.WarmupDone] > [CgmSensorAlertState.Ok]. + * + * A stopped source answers [CgmSensorAlertState.Ok]. + * + * A function and not a flow on purpose: several states only depend on the clock (ending soon, + * ended, no reading for a while), so the answer is computed when it is asked for. It must be + * cheap and safe to call from any thread. [CgmSensorAlertRules.map] holds the order, so every + * source keeps the same one. + * + * @param expiringLeadMs how long before the end the user wants "ending soon". Before that the + * source must not answer [CgmSensorAlertState.Expiring], so that a less important state, for + * example a ready second sensor, is not hidden while there is nothing to warn about yet. + */ + fun sensorAlertState(nowMs: Long, expiringLeadMs: Long): CgmSensorAlertState +} + +/** + * State of the sensor, for the sensor alarms. Times are wall-clock epoch ms. + * + * Each timestamp also names the episode: the same state with the same timestamp is the same + * episode, and its alarm is raised only once for it. + */ +sealed interface CgmSensorAlertState { + + /** Nothing to report. */ + data object Ok : CgmSensorAlertState + + /** The first usable reading after a warm-up arrived at [atEpochMs]. */ + data class WarmupDone(val atEpochMs: Long) : CgmSensorAlertState + + /** The usable time of the sensor ends at [endsAtEpochMs], including any grace period. */ + data class Expiring(val endsAtEpochMs: Long) : CgmSensorAlertState + + /** + * The usable time of the sensor ended at [atEpochMs], including any grace period. + * + * [atEpochMs] must stay the same for the whole episode: the end of the usable time when the + * source knows it, also when the sensor reports its end by itself and after an app restart. + * Never the moment a message happened to be seen, because each new value is a new episode and + * sounds the alarm again. + */ + data class Expired(val atEpochMs: Long) : CgmSensorAlertState + + /** The sensor cannot be used. No free text, so the user always sees a translated message. */ + data class Failed(val reason: CgmSensorFailure) : CgmSensorAlertState + + /** + * There has been no link to the sensor, or no reading from it, since [sinceEpochMs]. The source + * says so at once; the central check waits for the delay the user has set before it warns, and + * it counts that delay from [sinceEpochMs]. + */ + data class SignalLost(val sinceEpochMs: Long) : CgmSensorAlertState + + /** + * The sensor is linked and sends, but without a usable glucose value (for example too much + * noise), since [sinceEpochMs]. It has not failed and has not ended. The central check waits for + * the delay the user has set, counted from [sinceEpochMs]. + */ + data class SensorIssue(val sinceEpochMs: Long) : CgmSensorAlertState + + /** A pre-soaked second sensor is ready since [atEpochMs], so the user can switch to it. */ + data class SecondSensorReady(val atEpochMs: Long) : CgmSensorAlertState +} + +/** Why a sensor cannot be used, see [CgmSensorAlertState.Failed]. */ +enum class CgmSensorFailure { + + /** The sensor itself reports a fault. */ + SENSOR_ERROR, + + /** The sensor stopped before the end of its life. */ + ENDED_EARLY, + + /** Any other final failure, for example the sensor cannot be paired. */ + OTHER +} + +/** + * The priority order of [CgmSensorAlertProvider.sensorAlertState], in one place, so every source + * answers the same way. A source fills [Input] from what its driver knows and calls [map]. + * + * Pure: no clock of its own, no platform code. + */ +object CgmSensorAlertRules { + + /** + * No reading for this long, while a reading is expected, is a lost signal. This only makes the + * state visible: the central check waits for the delay the user has set before it warns. + */ + const val SILENCE_MS: Long = 5L * 60L * 1000L + + /** + * Everything the order needs. Times are wall-clock epoch ms. + * + * @param stopped the source is stopped: no state at all. + * @param sensorStored a sensor is set up in the main slot. Without one only a ready second + * sensor is worth a message. + * @param failure the sensor cannot be used, null when it can. + * @param endedBySensor the sensor itself says its session has ended. It is [CgmSensorAlertState.Expired] + * when the usable time is over, else [CgmSensorFailure.ENDED_EARLY]. + * @param expiresAtMs end of the usable time including any grace period, null when not known. + * @param linkLostSinceMs the link is down since then, null while it is up. + * @param lastReadingAtMs the last usable reading, null when none yet. + * @param readingExpected false while no reading comes on purpose (warm-up, pairing), so silence + * is not a lost signal then. + * @param issueSinceMs the sensor sends without a usable value since then, null when it does not. + * @param secondSensorReadyAtMs a pre-soak sensor is ready since then, null when it is not. + * @param warmupDoneAtMs the first usable reading after a warm-up, null when none or too old. + * @param expiringLeadMs see [CgmSensorAlertProvider.sensorAlertState]. + */ + data class Input( + val stopped: Boolean, + val sensorStored: Boolean, + val failure: CgmSensorFailure?, + val endedBySensor: Boolean, + val expiresAtMs: Long?, + val linkLostSinceMs: Long?, + val lastReadingAtMs: Long?, + val readingExpected: Boolean, + val issueSinceMs: Long?, + val secondSensorReadyAtMs: Long?, + val warmupDoneAtMs: Long?, + val expiringLeadMs: Long, + val nowMs: Long, + ) + + fun map(input: Input): CgmSensorAlertState { + if (input.stopped) return CgmSensorAlertState.Ok + if (!input.sensorStored) { + return input.secondSensorReadyAtMs?.let { CgmSensorAlertState.SecondSensorReady(it) } ?: CgmSensorAlertState.Ok + } + val now = input.nowMs + val expiresAt = input.expiresAtMs + // The end, once it has come. Null before it, or when the end is not known. + val endedAt = expiresAt?.takeIf { now >= it } + input.failure?.let { return CgmSensorAlertState.Failed(it) } + if (input.endedBySensor) { + return if (endedAt != null) CgmSensorAlertState.Expired(endedAt) + else CgmSensorAlertState.Failed(CgmSensorFailure.ENDED_EARLY) + } + if (endedAt != null) return CgmSensorAlertState.Expired(endedAt) + input.linkLostSinceMs?.let { return CgmSensorAlertState.SignalLost(it) } + val last = input.lastReadingAtMs + if (last != null && input.readingExpected && now - last >= SILENCE_MS) return CgmSensorAlertState.SignalLost(last) + input.issueSinceMs?.let { return CgmSensorAlertState.SensorIssue(it) } + if (expiresAt != null && expiresAt - now <= input.expiringLeadMs) return CgmSensorAlertState.Expiring(expiresAt) + input.secondSensorReadyAtMs?.let { return CgmSensorAlertState.SecondSensorReady(it) } + input.warmupDoneAtMs?.let { return CgmSensorAlertState.WarmupDone(it) } + return CgmSensorAlertState.Ok + } +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt new file mode 100644 index 000000000000..e204d870afec --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt @@ -0,0 +1,124 @@ +package app.aaps.core.interfaces.source + +import kotlinx.coroutines.flow.StateFlow + +/** + * Which logical sensor a reading belongs to when a CGM source can overlap a new sensor + * over the outgoing one (pre-soak / staging). + * + * [PRODUCTION] feeds the loop. [STAGING] is warmed in parallel and is never published + * until the user promotes it. + */ +enum class SensorSlot { PRODUCTION, STAGING } + +/** + * State of the optional STAGING slot, for a "new sensor" card. + * + * - [ABSENT] no staging sensor started. + * - [WARMUP] staging sensor warming up / reconnecting (no glucose yet). + * - [SETTLING] warmed up, collecting glucose, not settled long enough to promote. + * - [READY] settled and producing valid glucose → promotion allowed. + */ +enum class StagingState { ABSENT, WARMUP, SETTLING, READY } + +/** + * Generic sensor life info so the UI can show the sensor age and the end of life (time to start a + * new sensor) without naming a vendor. + * + * Times are in ms. Fields are null when the source cannot know them. + */ +data class CgmSensorLifecycle( + val startedAtEpochMs: Long?, + val ageMs: Long?, + val endOfLife: Boolean, +) + +/** + * Proof that the collect-only staging sensor is really producing data. + * + * A pre-soak asks the user to wait many hours on a sensor whose readings are never + * published. Without this, a working sensor and a dead one look the same. + */ +data class CgmStagingEvidence( + val validCount: Int, + val lastValueMgdl: Double?, + val lastValueAtEpochMs: Long?, +) + +/** Why a promote-staging-to-production request was refused. */ +enum class PromotionRejectReason { + STAGING_ABSENT, + STAGING_NOT_SETTLED, + STAGING_NO_VALID_GLUCOSE, + + /** Early promotion asked, but the staging sensor has not sent a recent reading. */ + STAGING_NO_RECENT_GLUCOSE, +} + +/** + * Result of a promote-staging-to-production request. + * + * [OkBoundFailed] and [OkFollowUpFailed] say that the sensors were swapped but a later step + * failed. They are not a silent [Ok], so the user can be told. + */ +sealed interface PromotionResult { + /** Promotion succeeded: the staging sensor now feeds the loop, and older calibration entries are ignored. */ + data object Ok : PromotionResult + + /** + * The exchange already happened and is kept. + * [app.aaps.core.interfaces.calibration.Calibration.ignoreEntriesBefore] threw, so older + * calibration entries were not ignored. Not a rollback, and not a full success. + */ + data object OkBoundFailed : PromotionResult + + /** + * The exchange already happened, older calibration entries are ignored, and a later step + * (loading or resuming the session) threw. + * [productionIdentityPresent] is read from the production store after that throw. + */ + data class OkFollowUpFailed(val productionIdentityPresent: Boolean) : PromotionResult + + /** Promotion refused; [reason] says why (no state changed). */ + data class Rejected(val reason: PromotionRejectReason) : PromotionResult +} + +/** + * Implemented by a [BgSource] that can overlap a second (staging) sensor over production. + * Extends [CgmWarmupProvider]: production warm-up stays the source of truth for the warm-up display. + * + * The STAGING slot is collect-only until [promoteStagingToProduction]. + */ +interface CgmSensorStatusProvider : CgmWarmupProvider { + + /** Production sensor lifecycle, or null when unknown / no sensor. */ + val lifecycle: StateFlow + + /** Staging sensor lifecycle, or null when there is no staging sensor. */ + val stagingLifecycle: StateFlow + + /** Coarse staging slot state for the "new sensor" card. */ + val stagingState: StateFlow + + /** Evidence that staging is collecting, or null when there is no staging sensor. */ + val stagingEvidence: StateFlow + + /** + * Milliseconds left before the staging sensor has settled long enough to be promoted, or null + * when there is no staging sensor or the wait is already over. + * + * The source owns the settle rule, so the UI can show a countdown without knowing it. A UI that + * kept its own copy of the threshold would drift from the rule that really gates promotion. + */ + val stagingSettleRemainingMs: StateFlow + + /** + * Promote the staging sensor to production. This is the only action that changes + * the loop glucose source. + * + * @param allowEarly the user promotes a sensor that has not finished its soak, + * because production stopped early. Soak is skipped, but evidence gates are not: + * staging must have enough valid readings and one recent reading. + */ + suspend fun promoteStagingToProduction(allowEarly: Boolean = false): PromotionResult +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt new file mode 100644 index 000000000000..8adcd1bc5c50 --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt @@ -0,0 +1,37 @@ +package app.aaps.core.interfaces.source + +import kotlinx.coroutines.flow.StateFlow + +/** + * Generic warm-up / reconnect status of an active CGM source. + * + * A [BgSource] that can report this implements [CgmWarmupProvider]. UI and safety can then + * react to a sensor that is warming up or reconnecting (no glucose yet) without naming a vendor. + * + * @param active true while warm-up or reconnect is in progress. + * @param phase honest phase of the current wait. + * @param remainingMs countdown in ms if the protocol knows it, else null. + * @param endsAtEpochMs wall-clock end in epoch ms if known, else null. + * @param totalMs full warm-up length in ms if known; lets UI draw a determinate ring. + */ +data class CgmWarmupStatus( + val active: Boolean, + val phase: Phase, + val remainingMs: Long?, + val endsAtEpochMs: Long?, + val totalMs: Long? = null, +) { + + enum class Phase { CONNECTING, RECONNECTING, WARMING, PAIRING } +} + +/** + * Implemented by a [BgSource] plugin that can report a generic [CgmWarmupStatus]. + * + * Consumers cast the active BG source: `(activeBgSource as? CgmWarmupProvider)?.warmupStatus`. + */ +interface CgmWarmupProvider { + + /** Current warm-up status, or null when there is nothing to show (READY / IDLE / FAILED). */ + val warmupStatus: StateFlow +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt new file mode 100644 index 000000000000..d70c4dc52d3b --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt @@ -0,0 +1,25 @@ +package app.aaps.core.interfaces.source + +/** + * What happened when a fingerstick was handed to the sensor itself. + * + * Only says whether the app managed to pass the value on. What the SENSOR then did with it comes + * back later, over the radio, and belongs to the source's own status screen: the sensor is asleep + * between its radio windows, so there is nothing to report at the moment the user taps OK. + */ +sealed interface SensorCalibrationResult { + + /** This source does not hold calibrations in the sensor, or the user has not switched it on. */ + data object NotSupported : SensorCalibrationResult + + /** Handed over. It reaches the sensor at the next radio window, normally within a few minutes. */ + data object Queued : SensorCalibrationResult + + /** + * The app will not pass it on. + * + * @param reason short, already user-readable, e.g. no session, value out of range, one already + * waiting + */ + data class Refused(val reason: String) : SensorCalibrationResult +} diff --git a/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt b/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt new file mode 100644 index 000000000000..f0a16dfeca85 --- /dev/null +++ b/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt @@ -0,0 +1,101 @@ +package app.aaps.core.interfaces.source + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The priority order of [CgmSensorAlertRules.map], the same for every BG source. */ +class CgmSensorAlertRulesTest { + + private val now = 1_000_000_000L + private val hour = 3_600_000L + + private fun input( + stopped: Boolean = false, + sensorStored: Boolean = true, + failure: CgmSensorFailure? = null, + endedBySensor: Boolean = false, + expiresAtMs: Long? = now + 100 * hour, + linkLostSinceMs: Long? = null, + lastReadingAtMs: Long? = now, + readingExpected: Boolean = true, + issueSinceMs: Long? = null, + secondSensorReadyAtMs: Long? = null, + warmupDoneAtMs: Long? = null, + expiringLeadMs: Long = 12 * hour, + ) = CgmSensorAlertRules.Input( + stopped, sensorStored, failure, endedBySensor, expiresAtMs, linkLostSinceMs, lastReadingAtMs, readingExpected, + issueSinceMs, secondSensorReadyAtMs, warmupDoneAtMs, expiringLeadMs, now + ) + + private fun map(i: CgmSensorAlertRules.Input) = CgmSensorAlertRules.map(i) + + @Test + fun aHealthySensorIsOk() { + assertEquals(CgmSensorAlertState.Ok, map(input())) + } + + @Test + fun aStoppedSourceSaysNothing() { + assertEquals(CgmSensorAlertState.Ok, map(input(stopped = true, failure = CgmSensorFailure.SENSOR_ERROR))) + } + + @Test + fun withoutASensorOnlyAReadySecondSensorCounts() { + assertEquals(CgmSensorAlertState.Ok, map(input(sensorStored = false, linkLostSinceMs = now - hour))) + assertEquals(CgmSensorAlertState.SecondSensorReady(5L), map(input(sensorStored = false, secondSensorReadyAtMs = 5L))) + } + + @Test + fun failureComesFirst() { + assertEquals( + CgmSensorAlertState.Failed(CgmSensorFailure.SENSOR_ERROR), + map(input(failure = CgmSensorFailure.SENSOR_ERROR, expiresAtMs = now - hour, linkLostSinceMs = now - hour)) + ) + } + + @Test + fun anEndTheSensorReportsIsExpiredAfterTheUsableTimeElseEndedEarly() { + val endsAt = now - hour + assertEquals(CgmSensorAlertState.Expired(endsAt), map(input(endedBySensor = true, expiresAtMs = endsAt))) + assertEquals(CgmSensorAlertState.Failed(CgmSensorFailure.ENDED_EARLY), map(input(endedBySensor = true))) + } + + @Test + fun theEndKeepsItsTimeSoItIsOneEpisode() { + val endsAt = now - hour + assertEquals(CgmSensorAlertState.Expired(endsAt), map(input(expiresAtMs = endsAt))) + assertEquals(CgmSensorAlertState.Expired(endsAt), map(input(expiresAtMs = endsAt, linkLostSinceMs = now - 1))) + } + + @Test + fun aLostLinkOrSilenceIsASignalLoss() { + assertEquals(CgmSensorAlertState.SignalLost(now - 60_000L), map(input(linkLostSinceMs = now - 60_000L))) + val last = now - CgmSensorAlertRules.SILENCE_MS + assertEquals(CgmSensorAlertState.SignalLost(last), map(input(lastReadingAtMs = last))) + assertEquals(CgmSensorAlertState.Ok, map(input(lastReadingAtMs = last + 1))) + // No reading on purpose (warm-up): silence is not a loss. + assertEquals(CgmSensorAlertState.Ok, map(input(lastReadingAtMs = now - hour, readingExpected = false))) + } + + @Test + fun aSensorIssueComesAfterASignalLoss() { + assertEquals(CgmSensorAlertState.SensorIssue(7L), map(input(issueSinceMs = 7L))) + assertEquals(CgmSensorAlertState.SignalLost(3L), map(input(issueSinceMs = 7L, linkLostSinceMs = 3L))) + } + + @Test + fun endingSoonOnlyInsideTheLeadTime() { + val endsAt = now + 12 * hour + assertEquals(CgmSensorAlertState.Expiring(endsAt), map(input(expiresAtMs = endsAt))) + assertEquals(CgmSensorAlertState.Ok, map(input(expiresAtMs = endsAt + 1))) + // Before the lead time a ready second sensor is not hidden. + assertEquals(CgmSensorAlertState.SecondSensorReady(9L), map(input(expiresAtMs = endsAt + 1, secondSensorReadyAtMs = 9L))) + assertEquals(CgmSensorAlertState.Expiring(endsAt), map(input(expiresAtMs = endsAt, secondSensorReadyAtMs = 9L))) + } + + @Test + fun warmupDoneIsTheLeastImportant() { + assertEquals(CgmSensorAlertState.WarmupDone(4L), map(input(warmupDoneAtMs = 4L))) + assertEquals(CgmSensorAlertState.SecondSensorReady(9L), map(input(warmupDoneAtMs = 4L, secondSensorReadyAtMs = 9L))) + } +} diff --git a/core/keys/src/androidMain/res/values/strings.xml b/core/keys/src/androidMain/res/values/strings.xml index f96d37b3c2a5..8439ffc63bd3 100644 --- a/core/keys/src/androidMain/res/values/strings.xml +++ b/core/keys/src/androidMain/res/values/strings.xml @@ -36,6 +36,66 @@ Gradually increase notification volume Override Do Not Disturb mode On: alarms ring even when the phone is silent or in Do Not Disturb. Off: alarms do not ring then. In Do Not Disturb they only vibrate. + AAPS sound + Alert on low glucose + Sound an alarm when glucose is at or below the low threshold. + Low glucose alarm threshold + Alert on high glucose + Notify when glucose is at or above the high threshold. + High glucose alarm threshold + Alert on rapid fall + Sound an alarm when glucose drops by at least the configured amount within the configured time window. + Rapid fall drop threshold + How much glucose must drop to sound the alarm. Always in mg/dL, also when AAPS shows mmol/L (18 mg/dL is about 1 mmol/L). + Rapid fall time window + Urgent low alarm + Sound an alarm when glucose is at or below 55 mg/dL (3.1 mmol/L). The mute timer never silences it. + Urgent low soon alarm + Sound an alarm when glucose is falling and will be at or below 55 mg/dL (3.1 mmol/L) within 20 minutes. + Alert on rapid rise + Notify when glucose rises by at least the set amount within the set time window. + Rapid rise threshold + How much glucose must rise for the alarm. Always in mg/dL, also when AAPS shows mmol/L (18 mg/dL is about 1 mmol/L). + Rapid rise time window + Delay the first alarm + The alarm goes off only when the condition has lasted this long. 0 = at once. + Repeat after acknowledge + An alarm that is not acknowledged goes off again every 5 minutes. After you acknowledge it, it stays quiet this long, then goes off again if the cause is still there. 0 = not again until the cause has gone. + An alarm that is not acknowledged goes off again every 5 minutes. After you acknowledge it, it stays quiet this long, then goes off again if glucose is still urgent low. It always comes back, after 30 minutes at most. + Sound + The AAPS sound is the standard AAPS alarm sound. Without sound, the alarm shows a notification only. + No sound + Trio acoustic, mild + Trio acoustic, medium + Trio acoustic, harsh + Trio electronic, mild + Trio electronic, medium + Trio electronic, harsh + Glass bell + Harp + Meow + Saw wave + Hard saw wave + Sine wave + Open can + Open wrapper + Alert when the CGM sensor fails + Sound an alarm when the sensor reports an error or cannot be used. Only for BG sources that report their sensor state. + Alert when the CGM sensor has ended + Sound an alarm when the usable time of the sensor has ended. Only for BG sources that report their sensor state. + Warn before the CGM sensor ends + Notify some hours before the usable time of the sensor ends, so you can prepare a new sensor. Only for BG sources that report their sensor state. + Warn this long before the sensor ends + Alert on lost CGM signal + Notify when the phone has had no link to the sensor, or no reading from it, for some time. Only for BG sources that report their sensor state. + Signal lost for at least + Alert on a CGM sensor issue + Notify when the sensor is linked but sends no usable glucose value, for example because of noise. Only for BG sources that report their sensor state. + Sensor issue for at least + Notify when sensor warm-up is done + Notify when a new sensor sends its first usable reading. Only for BG sources that report their sensor state. + Notify when a second sensor is ready + Notify when a pre-soaked second sensor is ready and you can switch to it. Only for BG sources that support a second sensor. Upload BG data to NS diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt index 6717d798a66c..cb3de1d60680 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt @@ -83,6 +83,22 @@ enum class BooleanKey( ), AlertIncreaseVolume("gradually_increase_notification_volume", true, KeysStrings.pref_title_alert_increase_volume), AlertOverrideDoNotDisturb("alert_override_dnd", true, KeysStrings.pref_title_alert_override_dnd, KeysStrings.pref_summary_alert_override_dnd, defaultedBySM = true), + // CGM alarms (see CgmAlarmType). The glucose alarms are off by default: the user opts in. + AlertHypo("enable_hypo_alert", false, KeysStrings.pref_title_alert_hypo, KeysStrings.pref_summary_alert_hypo), + AlertHyper("enable_hyper_alert", false, KeysStrings.pref_title_alert_hyper, KeysStrings.pref_summary_alert_hyper), + AlertRapidFall("enable_rapid_fall_alert", false, KeysStrings.pref_title_alert_rapid_fall, KeysStrings.pref_summary_alert_rapid_fall), + AlertUrgentLow("enable_cgm_urgent_low_alert", false, KeysStrings.pref_title_alert_urgent_low, KeysStrings.pref_summary_alert_urgent_low), + AlertUrgentLowSoon("enable_cgm_urgent_low_soon_alert", false, KeysStrings.pref_title_alert_urgent_low_soon, KeysStrings.pref_summary_alert_urgent_low_soon), + AlertRapidRise("enable_cgm_rise_rate_alert", false, KeysStrings.pref_title_alert_rapid_rise, KeysStrings.pref_summary_alert_rapid_rise), + // Sensor state alarms. They are raised only for a BG source that reports its sensor state + // (CgmSensorAlertProvider); for every other source they do nothing, so they can default to on. + AlertCgmSensorFailed("enable_cgm_sensor_failed_alert", true, KeysStrings.pref_title_alert_cgm_sensor_failed, KeysStrings.pref_summary_alert_cgm_sensor_failed), + AlertCgmSensorExpired("enable_cgm_sensor_expired_alert", true, KeysStrings.pref_title_alert_cgm_sensor_expired, KeysStrings.pref_summary_alert_cgm_sensor_expired), + AlertCgmSensorExpiring("enable_cgm_sensor_expiring_alert", true, KeysStrings.pref_title_alert_cgm_sensor_expiring, KeysStrings.pref_summary_alert_cgm_sensor_expiring), + AlertCgmSignalLost("enable_cgm_signal_lost_alert", true, KeysStrings.pref_title_alert_cgm_signal_lost, KeysStrings.pref_summary_alert_cgm_signal_lost), + AlertCgmSensorIssue("enable_cgm_sensor_issue_alert", true, KeysStrings.pref_title_alert_cgm_sensor_issue, KeysStrings.pref_summary_alert_cgm_sensor_issue), + AlertCgmWarmupDone("enable_cgm_warmup_done_alert", true, KeysStrings.pref_title_alert_cgm_warmup_done, KeysStrings.pref_summary_alert_cgm_warmup_done), + AlertCgmSecondSensorReady("enable_cgm_second_sensor_ready_alert", true, KeysStrings.pref_title_alert_cgm_second_sensor_ready, KeysStrings.pref_summary_alert_cgm_second_sensor_ready), BgSourceUploadToNs("dexcomg5_nsupload", true, KeysStrings.pref_title_bg_source_upload_to_ns, defaultedBySM = true, hideParentScreenIfHidden = true, defaultedByHardenedMode = true), BgSourceCreateSensorChange("dexcom_lognssensorchange", true, KeysStrings.pref_title_bg_source_create_sensor_change, KeysStrings.pref_summary_bg_source_create_sensor_change, defaultedBySM = true), diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt index 6a99e2e4df9b..a66c15292734 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt @@ -413,6 +413,195 @@ enum class IntKey( dependency = BooleanKey.AlertPumpUnreachable, unitType = UnitType.MIN ), + /** + * Rapid-fall drop size: a glucose *difference*, stored and shown in mg/dL for both unit settings. + * + * It must NOT be a `UnitDoubleKey`. That type guesses the unit from the number (below 36 means + * mmol/L), which is right for a glucose level but wrong for a small difference: 30 mg/dL was shown + * as 540, and a typed 25 was stored as 450, so the alarm could never fire. The key string ends in + * `_mgdl` because the old `alert_rapid_fall_drop` holds a float, which an int read cannot load, + * and its value was often wrong. `PreferenceMigrations` copies the old value once, and only when + * it is inside 15-60 mg/dL; any other old value is dropped and the default applies. + */ + AlertRapidFallDrop( + key = "alert_rapid_fall_drop_mgdl", + defaultValue = 30, + min = 15, + max = 60, + title = KeysStrings.pref_title_alert_rapid_fall_drop, + summary = KeysStrings.pref_summary_alert_rapid_fall_drop, + dependency = BooleanKey.AlertRapidFall, + unitType = UnitType.MGDL + ), + AlertRapidFallWindow( + key = "alert_rapid_fall_window", + defaultValue = 15, + min = 5, + max = 30, + title = KeysStrings.pref_title_alert_rapid_fall_window, + dependency = BooleanKey.AlertRapidFall, + unitType = UnitType.MIN + ), + /** Rise rate alarm: how much glucose must rise within [AlertRapidRiseWindow]. A difference, so mg/dL always, like [AlertRapidFallDrop]. */ + AlertRapidRiseAmount( + key = "alert_rapid_rise_mgdl", + defaultValue = 30, + min = 15, + max = 60, + title = KeysStrings.pref_title_alert_rapid_rise_amount, + summary = KeysStrings.pref_summary_alert_rapid_rise_amount, + dependency = BooleanKey.AlertRapidRise, + unitType = UnitType.MGDL + ), + AlertRapidRiseWindow( + key = "alert_rapid_rise_window", + defaultValue = 15, + min = 5, + max = 30, + title = KeysStrings.pref_title_alert_rapid_rise_window, + dependency = BooleanKey.AlertRapidRise, + unitType = UnitType.MIN + ), + /** High alarm: how long glucose must stay high before the first alarm. 0 = at once. */ + AlertHyperDelay( + key = "alert_cgm_high_delay_minutes", + defaultValue = 0, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_delay_first, + summary = KeysStrings.pref_summary_alert_delay_first, + dependency = BooleanKey.AlertHyper, + unitType = UnitType.MIN + ), + AlertCgmExpiringLeadHours( + key = "alert_cgm_expiring_lead_hours", + defaultValue = 12, + min = 1, + max = 48, + title = KeysStrings.pref_title_alert_cgm_expiring_lead, + dependency = BooleanKey.AlertCgmSensorExpiring, + unitType = UnitType.HOURS + ), + AlertCgmSignalLostMinutes( + key = "alert_cgm_signal_lost_minutes", + defaultValue = 10, + min = 5, + max = 60, + title = KeysStrings.pref_title_alert_cgm_signal_lost_delay, + dependency = BooleanKey.AlertCgmSignalLost, + unitType = UnitType.MIN + ), + AlertCgmSensorIssueMinutes( + key = "alert_cgm_sensor_issue_minutes", + defaultValue = 20, + min = 0, + max = 60, + title = KeysStrings.pref_title_alert_cgm_sensor_issue_delay, + dependency = BooleanKey.AlertCgmSensorIssue, + unitType = UnitType.MIN + ), + // Repeat after "Acknowledge": the alarm stays quiet this long, then goes off again if its cause is + // still there. 0 = not again until the cause has gone. Urgent low always comes back, within 30 min. + AlertUrgentLowRepeat( + key = "alert_cgm_urgent_low_repeat_minutes", + defaultValue = 30, + min = 5, + max = 30, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat_urgent_low, + dependency = BooleanKey.AlertUrgentLow, + unitType = UnitType.MIN + ), + AlertUrgentLowSoonRepeat( + key = "alert_cgm_urgent_low_soon_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertUrgentLowSoon, + unitType = UnitType.MIN + ), + AlertHypoRepeat( + key = "alert_cgm_low_repeat_minutes", + defaultValue = 15, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertHypo, + unitType = UnitType.MIN + ), + AlertRapidFallRepeat( + key = "alert_cgm_fall_rate_repeat_minutes", + defaultValue = 15, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertRapidFall, + unitType = UnitType.MIN + ), + AlertHyperRepeat( + key = "alert_cgm_high_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertHyper, + unitType = UnitType.MIN + ), + AlertRapidRiseRepeat( + key = "alert_cgm_rise_rate_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertRapidRise, + unitType = UnitType.MIN + ), + AlertCgmSensorFailedRepeat( + key = "alert_cgm_sensor_failed_repeat_minutes", + defaultValue = 0, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSensorFailed, + unitType = UnitType.MIN + ), + AlertCgmSensorExpiredRepeat( + key = "alert_cgm_sensor_expired_repeat_minutes", + defaultValue = 0, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSensorExpired, + unitType = UnitType.MIN + ), + AlertCgmSignalLostRepeat( + key = "alert_cgm_signal_lost_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSignalLost, + unitType = UnitType.MIN + ), + AlertCgmSensorIssueRepeat( + key = "alert_cgm_sensor_issue_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSensorIssue, + unitType = UnitType.MIN + ), AutotuneDefaultTuneDays(key = "autotune_default_tune_days", defaultValue = 5, min = 1, max = 30, title = KeysStrings.pref_title_autotune_days, summary = KeysStrings.autotune_default_tune_days_summary, unitType = UnitType.DAYS), diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt index fe63d715743f..b4c84e7edb64 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt @@ -230,8 +230,126 @@ enum class StringKey( validator = StringValidator.minLength(17) ), + // Sound of each CGM alarm: "default" (the standard AAPS alarm sound), "none" (notification only), + // or a Trio sound (see core/ui/SOUNDS.md). The value of a Trio sound is its file name. Urgent low + // has no "none". + AlertUrgentLowSound( + key = "alert_cgm_urgent_low_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("ulg", allowNone = false), + dependency = BooleanKey.AlertUrgentLow, + ), + AlertUrgentLowSoonSound( + key = "alert_cgm_urgent_low_soon_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("lgs", allowNone = true), + dependency = BooleanKey.AlertUrgentLowSoon, + ), + AlertHypoSound( + key = "alert_cgm_low_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("lg", allowNone = true), + dependency = BooleanKey.AlertHypo, + ), + AlertRapidFallSound( + key = "alert_cgm_fall_rate_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("lgs", allowNone = true), + dependency = BooleanKey.AlertRapidFall, + ), + AlertHyperSound( + key = "alert_cgm_high_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("hg", allowNone = true), + dependency = BooleanKey.AlertHyper, + ), + AlertRapidRiseSound( + key = "alert_cgm_rise_rate_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("hg", allowNone = true), + dependency = BooleanKey.AlertRapidRise, + ), + AlertCgmSensorFailedSound( + key = "alert_cgm_sensor_failed_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dcr", allowNone = true), + dependency = BooleanKey.AlertCgmSensorFailed, + ), + AlertCgmSensorExpiredSound( + key = "alert_cgm_sensor_ended_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dts", allowNone = true), + dependency = BooleanKey.AlertCgmSensorExpired, + ), + AlertCgmSignalLostSound( + key = "alert_cgm_signal_loss_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dts", allowNone = true), + dependency = BooleanKey.AlertCgmSignalLost, + ), + AlertCgmSensorIssueSound( + key = "alert_cgm_sensor_issue_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dts", allowNone = true), + dependency = BooleanKey.AlertCgmSensorIssue, + ), + ; override val entries: Map = entriesRefs + entriesLiterals.mapValues { TextRef.Literal(it.value) } } + +/** + * The sound choices of one CGM alarm: the AAPS sound, no sound (unless [allowNone] is false), the six + * Trio sounds made for [trioSet] (acoustic and electronic, mild to harsh), then the eight Trio tones. + * The value of a Trio sound is its file name in `core/ui/res/raw`, which `AlarmSound.fileName` holds. + */ +private fun cgmAlarmSoundEntries(trioSet: String, allowNone: Boolean): Map = buildMap { + put("default", KeysStrings.alert_sound_default) + if (allowNone) put("none", KeysStrings.alert_sound_none) + put("trio_acoustic_${trioSet}_mild", KeysStrings.alert_sound_trio_acoustic_mild) + put("trio_acoustic_${trioSet}_medium", KeysStrings.alert_sound_trio_acoustic_medium) + put("trio_acoustic_${trioSet}_harsh", KeysStrings.alert_sound_trio_acoustic_harsh) + put("trio_electronic_${trioSet}_mild", KeysStrings.alert_sound_trio_electronic_mild) + put("trio_electronic_${trioSet}_medium", KeysStrings.alert_sound_trio_electronic_medium) + put("trio_electronic_${trioSet}_harsh", KeysStrings.alert_sound_trio_electronic_harsh) + put("trio_tone_glass_bell", KeysStrings.alert_sound_trio_glass_bell) + put("trio_tone_harp", KeysStrings.alert_sound_trio_harp) + put("trio_tone_meow", KeysStrings.alert_sound_trio_meow) + put("trio_tone_saw_wave", KeysStrings.alert_sound_trio_saw_wave) + put("trio_tone_hard_saw_wave", KeysStrings.alert_sound_trio_hard_saw_wave) + put("trio_tone_sine_wave", KeysStrings.alert_sound_trio_sine_wave) + put("trio_tone_open_can", KeysStrings.alert_sound_trio_open_can) + put("trio_tone_open_wrapper", KeysStrings.alert_sound_trio_open_wrapper) +} diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt index f6777ce1b9da..5ba65c162f59 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt @@ -32,7 +32,25 @@ enum class UnitDoubleKey( defaultedBySM = true, dependency = BooleanKey.ApsUseDynamicSensitivity, sync = SyncSpec(SyncChannel.Cold, SyncDirection.Bidirectional) + ), + AlertHypoThreshold( + key = "alert_hypo_threshold", + defaultValue = 70.0, + minMgdl = 50, + maxMgdl = 100, + title = KeysStrings.pref_title_alert_hypo_threshold, + dependency = BooleanKey.AlertHypo + ), + AlertHyperThreshold( + key = "alert_hyper_threshold", + defaultValue = 250.0, + minMgdl = 140, + maxMgdl = 400, + title = KeysStrings.pref_title_alert_hyper_threshold, + dependency = BooleanKey.AlertHyper ) + // The rapid-fall drop size is a glucose difference, so it is the IntKey `AlertRapidFallDrop` in + // mg/dL: this type guesses the unit from the number and gets small differences wrong. ; } diff --git a/core/ui/SOUNDS.md b/core/ui/SOUNDS.md new file mode 100644 index 000000000000..f1f2242acc24 --- /dev/null +++ b/core/ui/SOUNDS.md @@ -0,0 +1,73 @@ +# Alarm sounds + +## The Trio sounds (`src/androidMain/res/raw/trio_*.m4a`) + +The CGM alarm sounds in `src/androidMain/res/raw/trio_*.m4a` come from Trio, the open source app +for people with diabetes on iOS. The CGM alarms (Preferences > Alerts > CGM alarms) can use them, +on Android and on iOS. The iOS app copies the same files into its bundle when it is built, so +there is only one set. + +- Source: [nightscout/Trio pull request 1645](https://github.com/nightscout/Trio/pull/1645), + "Rework Trio Alarm Sounds: Add Urgency Levels and Voice Alarms", merged on 2026-10-19 + (commit `cd6ad0706db1e7a546360d4631f75b24a402ba58`). +- Brought into Trio by Deniz Cengiz ([dnzxy](https://github.com/dnzxy)). +- The sounds were designed for Trio by a sound designer who is a diabetes dad and Trio user, and + who wants to stay anonymous. +- We took the files, already converted, from nightscout/AndroidAPS pull request 5397 (Dexcom G7 + direct, by t1dude), path `cgm/dexcomg7/src/main/res/raw/g7_*.m4a` at commit `bec1b16ba20`. + +Thank you to all of them. + +### What we took + +- The Acoustic and Electronic sets, each at three urgency levels (mild, medium, harsh), for these + Trio alarms: urgent low (`ulg`), low (`lg`), low soon (`lgs`), high (`hg`), device critical (`dcr`) + and device time-sensitive (`dts`). +- Eight extra tones from the same pull request: glass bell, harp, meow, saw wave, hard saw wave, + sine wave, open can and open wrapper. + +Not taken: the carbs required set, the spoken alarms, and the older Trio tones. + +### What was changed + +- In pull request 5397: converted from CAF (16-bit PCM) to AAC at 96 kbit/s in an `.m4a` file, + because Android does not play CAF (`afconvert -f m4af -d aac -b 96000` on macOS). +- Here: renamed from `g7_