diff --git a/.gitignore b/.gitignore index 3691a3d95ee3..9873c61bd15c 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,5 @@ ios/app/Version.xcconfig # Office owner/lock files (~$foo.xlsx). They are transient, machine-local and must never # reach history - one was staged for commit alongside _docs/import.xlsx. ~$* +*.pyc +/.codex-attachments diff --git a/README.md b/README.md index cdecad9cfd04..2e86e7be5be6 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,9 @@ * Want to contribute? Please read [CONTRIBUTING.md](CONTRIBUTING.md) first — note that AI-generated pull requests are not welcome. * Everyone who’s been looping with AAPS needs to fill out the form after 3 days of looping https://docs.google.com/forms/d/14KcMjlINPMJHVt28MDRupa4sz4DDIooI4SrW0P3HSN8/viewform?c=0&w=1 +## Compare with base +https://github.com/BernhardRo/AndroidAPS/compare/master...nightscout:AndroidAPS:master + [![Support Server](https://img.shields.io/discord/629952586895851530.svg?label=Discord&logo=Discord&colorB=7289da&style=for-the-badge)](https://discord.gg/4fQUWHZ4Mw) [![CircleCI](https://circleci.com/gh/nightscout/AndroidAPS/tree/master.svg?style=svg)](https://circleci.com/gh/nightscout/AndroidAPS/tree/master) diff --git a/app/src/test/kotlin/app/aaps/di/metro/SourceGraphTest.kt b/app/src/test/kotlin/app/aaps/di/metro/SourceGraphTest.kt index c0c31b7d0e46..5f351abfadb8 100644 --- a/app/src/test/kotlin/app/aaps/di/metro/SourceGraphTest.kt +++ b/app/src/test/kotlin/app/aaps/di/metro/SourceGraphTest.kt @@ -1,5 +1,8 @@ package app.aaps.di.metro +import app.aaps.plugins.source.activities.EversenseCalibrationActivity +import app.aaps.plugins.source.activities.EversensePlacementActivity +import app.aaps.plugins.source.activities.EversenseStatusActivity import app.aaps.plugins.source.AidexPlugin import app.aaps.plugins.source.DexcomPlugin import app.aaps.plugins.source.GlimpPlugin @@ -47,7 +50,7 @@ class SourceGraphTest { } @Test - fun `the notification reader service is the only member injection here`() { - assertThat(graph().memberInjectors.keys).containsExactly(NotificationCollectorService::class) + fun `source member injectors include the service and Eversense screens`() { + assertThat(graph().memberInjectors.keys).containsExactly(NotificationCollectorService::class, EversenseCalibrationActivity::class, EversensePlacementActivity::class, EversenseStatusActivity::class) } } diff --git a/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt b/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt index 7cccc8c7b676..3bcfc1bf8ac9 100644 --- a/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt +++ b/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt @@ -53,6 +53,9 @@ class RawPreferenceStoreScanTest { "implementation/src/commonMain/kotlin/app/aaps/implementation/sharedPreferences/PreferencesImpl.kt" to "Preferences itself, which is what everything else is supposed to use", "shared/tests/src/androidMain/kotlin/app/aaps/shared/tests/SharedPreferencesMock.kt" to "the test double for the store; it lives in a main source set so tests in other modules can use it", + "plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStateStore.kt" to + "imports the whole legacy Eversense device store once; new state is a registered, non-exported preference", + // --- Moves the whole store, not a setting --- // These are the import, the export and the cloud copies of them. They are SUPPOSED to see every // key, including ones they have never heard of, so going through `Preferences` would defeat @@ -145,6 +148,8 @@ class RawPreferenceStoreScanTest { val skip = listOf("/build/", "/src/test", "/src/androidTest", "/src/androidHostTest", "/src/commonTest", "/src/iosTest", "/wear/") val root = repoRoot() val files = root.walkTopDown() + // Apply the same exclusions before entering directories, so build output is not walked. + .onEnter { dir -> skip.none { (dir.invariantSeparatorsPath + "/").contains(it) } } .filter { it.isFile && it.extension == "kt" } .map { it to it.invariantSeparatorsPath } .filterNot { (_, path) -> skip.any { path.contains(it) } } diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index b62d8f38f60b..76aa7090ba00 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -190,6 +190,24 @@ eopatch_patch_buzzer_reminders|EopatchBooleanKey|true eopatch_patch_config|EopatchStringNonKey|true eopatch_patch_state|EopatchStringNonKey|true eopatch_temp_basal|EopatchStringNonKey|true +eversense_alert_high|EversenseStringKey|true +eversense_alert_low|EversenseStringKey|true +eversense_calibration_launch|EversenseIntentKey|false +eversense_cloud_queue_json|EversenseRuntimeKey|false +eversense_cloud_upload_enabled|EversenseBooleanKey|true +eversense_credentials_password|EversenseStringKey|true +eversense_credentials_username|EversenseStringKey|true +eversense_device_state_json|EversenseRuntimeKey|false +eversense_diagnostic_logging|EversenseBooleanKey|false +eversense_documentation|EversenseIntentKey|false +eversense_european_region|EversenseBooleanKey|true +eversense_last_calibration_submitted_at|LongNonKey|false +eversense_notif_cloud_upload_toast|EversenseBooleanKey|true +eversense_placement_launch|EversenseIntentKey|false +eversense_sign_out|EversenseIntentKey|false +eversense_status|EversenseIntentKey|false +eversense_target_high|EversenseStringKey|true +eversense_target_low|EversenseStringKey|true export_all_cloud_enabled|BooleanNonKey|true export_csv_cloud_enabled|BooleanNonKey|true export_csv_local_enabled|BooleanNonKey|true diff --git a/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppNavGraph.kt b/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppNavGraph.kt index 03638b25995b..b47fff37bd3e 100644 --- a/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppNavGraph.kt +++ b/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppNavGraph.kt @@ -74,6 +74,7 @@ import app.aaps.plugins.main.MainStrings import app.aaps.plugins.sync.nsclientV3.clientcontrol.compose.AuthorizedClientsScreen import app.aaps.plugins.sync.nsclientV3.clientcontrol.compose.PairWithMasterScreen import app.aaps.plugins.sync.nsclientV3.clientcontrol.compose.ScanMasterQrScreen +import app.aaps.ui.compose.eversenseCalibrationDialog.EversenseCalibrationDialogScreen import app.aaps.ui.compose.calibrationDialog.CalibrationDialogScreen import app.aaps.ui.compose.carbsDialog.CarbsDialogScreen import app.aaps.ui.compose.careDialog.CareDialogScreen @@ -355,6 +356,10 @@ fun NavGraphBuilder.appNavGraph( ) } + composable(route = AppRoute.EversenseCalibrationDialog.route) { + EversenseCalibrationDialogScreen(onNavigateBack = { navController.safePopBackStack() }) + } + composable(route = AppRoute.CalibrationDialog.route) { CalibrationDialogScreen( onNavigateBack = { navController.safePopBackStack() } diff --git a/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppRoute.kt b/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppRoute.kt index 69a2fc67027f..bfe3099068b0 100644 --- a/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppRoute.kt +++ b/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/AppRoute.kt @@ -73,6 +73,7 @@ sealed class AppRoute(val route: String) { fun createRoute(preselect: Int) = "fill_dialog/$preselect" } + data object EversenseCalibrationDialog : AppRoute("eversense_calibration_dialog") data object CalibrationDialog : AppRoute("calibration_dialog") data object CarbsDialog : AppRoute("carbs_dialog") data object InsulinDialog : AppRoute("insulin_dialog") diff --git a/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/ElementNavigation.kt b/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/ElementNavigation.kt index 1f0e18587ade..a0ac1ad79d68 100644 --- a/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/ElementNavigation.kt +++ b/appshell/src/commonMain/kotlin/app/aaps/appshell/navigation/ElementNavigation.kt @@ -150,6 +150,7 @@ class ElementNavigator( ElementType.CGM_XDRIP -> onOpenCgmApp("com.eveningoutpost.dexdrip") ElementType.CGM_DEX -> dexcomBoyda.dexcomPackages().forEach { onOpenCgmApp(it) } + ElementType.EVERSENSE_CALIBRATION -> navController.navigate(AppRoute.EversenseCalibrationDialog.route) ElementType.CALIBRATION -> navController.navigate(AppRoute.CalibrationDialog.route) // Careportal 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..4d25fb19ebb4 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 @@ -50,6 +50,8 @@ enum class SourceSensor(val text: String, val aliases: Set = emptySet()) GLUTEC("Glutec", setOf("MQ")), GLUPRO("GluPro"), EVERSENSE("Eversense"), + EVERSENSE_E3("Eversense E3"), + EVERSENSE_365("Eversense 365"), // One sensor sold under two brands. AAPS already treats them as one: the broadcasts from both // apps go to the same worker, which has always stored this entry, and the plugin calls itself // "Syai/Ottai App". `Ottai` is only ever read, and is what Juggluco sends. 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..e1c0b6f5b7e3 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 @@ -24,6 +24,8 @@ private val ADVANCED_FILTERING_SENSORS = setOf( SourceSensor.LIBRE_3, SourceSensor.SYAI_TAG, SourceSensor.RANDOM, + SourceSensor.EVERSENSE_E3, + SourceSensor.EVERSENSE_365, ) private val FLAT_BG_CHECK_SENSORS = setOf( 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..9ed48283d1cd 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 @@ -39,6 +39,14 @@ class SourceSensorExtensionsTest { assertFalse(SourceSensor.MM_SIMPLERA.advancedFilteringSupported()) } + @Test + fun `identified eversense sensors support advanced filtering without flat bg checks`() { + assertTrue(SourceSensor.EVERSENSE_E3.advancedFilteringSupported()) + assertTrue(SourceSensor.EVERSENSE_365.advancedFilteringSupported()) + assertFalse(SourceSensor.EVERSENSE_E3.needsFlatBgCheck()) + assertFalse(SourceSensor.EVERSENSE_365.needsFlatBgCheck()) + } + @Test fun `eversense does not support advanced filtering`() { assertFalse(SourceSensor.EVERSENSE.advancedFilteringSupported()) diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/navigation/ElementType.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/navigation/ElementType.kt index 53600499a44d..757c21a6ee72 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/navigation/ElementType.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/navigation/ElementType.kt @@ -42,6 +42,9 @@ enum class ElementType( // On a client a calibration goes to the master as BatchAction.Calibration, which hands it to its CGM plugin. CALIBRATION(category = ElementCategory.CGM, searchable = true, role = ClientRole.Caregiver), + // Sends calibration to the local Eversense transmitter. + EVERSENSE_CALIBRATION(category = ElementCategory.CGM, searchable = true, role = ClientRole.Caregiver), + // Profile & Targets — minimum level is BOLUS; screen mode (PLAY/EDIT) determined by granted auth level. // Mutating editors whose writes ride Client-Control → CLIENT_PAIRED (hidden on an unpaired client). // PROFILE_MANAGEMENT is the exception and stays visible: profiles are state an unpaired client still 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 cb44b3bf647f..e01c8414fd39 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 @@ -261,7 +261,14 @@ 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), + + // Appended to keep the stored ordinals of existing notifications stable. + EVERSENSE_RELEASE(NORMAL, CGM), + EVERSENSE_PLACEMENT(NORMAL, CGM), + EVERSENSE_CREDENTIALS(NORMAL, CGM), + EVERSENSE_FIRMWARE(INFO, CGM), + EVERSENSE_ALARM(NORMAL, CGM); companion object { diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/EversenseCalibrationSource.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/EversenseCalibrationSource.kt new file mode 100644 index 000000000000..a993077f8a85 --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/EversenseCalibrationSource.kt @@ -0,0 +1,21 @@ +package app.aaps.core.interfaces.source + +/** + * Abstraction over Eversense's BLE calibration flow, exposed to modules (e.g. `ui`) that must not + * take a direct dependency on the `plugins:eversense`/`plugins:source` modules — same pattern as + * [XDripSource]/[DexcomBoyda]. + */ +interface EversenseCalibrationSource { + + /** True when Eversense is the currently active/enabled BG source. */ + fun isEnabled(): Boolean + + /** True when currently connected to the transmitter over BLE. */ + fun isConnected(): Boolean + + /** + * Sends a fingerstick calibration value (mg/dL) to the transmitter, connecting first (with a + * timeout) if not already connected. Returns true on success. + */ + suspend fun calibrate(bgMgDl: Int): Boolean +} diff --git a/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/navigation/ElementTypeRoleTest.kt b/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/navigation/ElementTypeRoleTest.kt index b5c8a060e2cf..fb7df203af2d 100644 --- a/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/navigation/ElementTypeRoleTest.kt +++ b/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/navigation/ElementTypeRoleTest.kt @@ -20,7 +20,7 @@ class ElementTypeRoleTest { ) private val caregiver = setOf( - ElementType.CALIBRATION, + ElementType.CALIBRATION, ElementType.EVERSENSE_CALIBRATION, ElementType.TEMP_TARGET_MANAGEMENT, ElementType.INSULIN_MANAGEMENT, ElementType.QUICK_WIZARD_MANAGEMENT, ElementType.FOOD_MANAGEMENT, ElementType.BG_CHECK, ElementType.NOTE, ElementType.EXERCISE, ElementType.QUESTION, ElementType.ANNOUNCEMENT, ElementType.SENSOR_INSERT, ElementType.BATTERY_CHANGE, ElementType.CANNULA_CHANGE, ElementType.FILL, ElementType.SITE_ROTATION, diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/LongNonKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/LongNonKey.kt index 52b9e9d68789..749dfa668300 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/LongNonKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/LongNonKey.kt @@ -8,6 +8,8 @@ enum class LongNonKey( override val exportable: Boolean = true ) : LongNonPreferenceKey { + EversenseLastCalibrationSubmittedAt("eversense_last_calibration_submitted_at", 0L, exportable = false), + LocalProfileLastChange("local_profile_last_change", 0L), BtWatchdogLastBark("bt_watchdog_last", 0L), diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt index a93e546ee95a..97b2ef2b2bfb 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/interfaces/StringPreferenceKey.kt @@ -9,6 +9,10 @@ interface StringPreferenceKey : PreferenceKey, StringNonPreferenceKey { val isPassword: Boolean val isPin: Boolean + /** Whether the password dialog asks for the value a second time. */ + val requiresPasswordConfirmation: Boolean + get() = true + /** * Whether the value should be hashed before storing. * When true, [hashPassword] is applied before persisting. @@ -80,4 +84,4 @@ fun StringPreferenceKey.withEntriesProvider( provider: () -> Map, emptyEntriesMessage: TextRef? = null ): StringKeyWithEntriesProvider = - StringKeyWithEntriesProvider(this, provider, emptyEntriesMessage) \ No newline at end of file + StringKeyWithEntriesProvider(this, provider, emptyEntriesMessage) diff --git a/core/ui/src/androidHostTest/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialogTest.kt b/core/ui/src/androidHostTest/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialogTest.kt index fcb7da066ccb..e5231197d498 100644 --- a/core/ui/src/androidHostTest/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialogTest.kt +++ b/core/ui/src/androidHostTest/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialogTest.kt @@ -3,10 +3,12 @@ package app.aaps.core.ui.compose.dialogs import android.content.Context import androidx.compose.material3.MaterialTheme import androidx.compose.ui.test.hasSetTextAction +import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.junit4.v2.createComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput +import androidx.compose.ui.test.performImeAction import app.aaps.core.ui.R import com.google.common.truth.Truth.assertThat import org.junit.Before @@ -36,14 +38,15 @@ class SetPasswordDialogTest { cancelLabel = context.getString(R.string.cancel) } - private fun show(onConfirm: (String, String) -> Unit = { _, _ -> }, onCancel: () -> Unit = {}) { + private fun show(onConfirm: (String, String) -> Unit = { _, _ -> }, onCancel: () -> Unit = {}, requireConfirmation: Boolean = true) { compose.setContent { MaterialTheme { SetPasswordDialog( title = "Set New Password", pinInput = false, onConfirm = onConfirm, - onCancel = onCancel + onCancel = onCancel, + requireConfirmation = requireConfirmation ) } } @@ -64,6 +67,19 @@ class SetPasswordDialogTest { assertThat(second).isEqualTo("beta") } + @Test + fun singleEntry_submitsFromKeyboardWithoutConfirmationField() { + var submitted: Pair? = null + show(onConfirm = { a, b -> submitted = a to b }, requireConfirmation = false) + + val fields = compose.onAllNodes(hasSetTextAction()) + fields.assertCountEquals(1) + fields[0].performTextInput("dms-password") + fields[0].performImeAction() + + assertThat(submitted).isEqualTo("dms-password" to "dms-password") + } + @Test fun cancel_firesOnCancel() { var cancels = 0 diff --git a/core/ui/src/androidMain/res/values/strings.xml b/core/ui/src/androidMain/res/values/strings.xml index 6314ac72ce62..956d4163501a 100644 --- a/core/ui/src/androidMain/res/values/strings.xml +++ b/core/ui/src/androidMain/res/values/strings.xml @@ -1276,4 +1276,8 @@ y Range for visualization No system key store was found on this computer. The keys that protect your settings and the pairing with the master are kept in files next to the data, so anyone who gets a copy of your files gets them too. On Linux, install and start a keyring (for example GNOME Keyring or KWallet), then start AAPS again. +Eversense Calibration + +Send a fingerstick value directly to the Eversense transmitter + diff --git a/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialog.kt b/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialog.kt index 495cd842af5e..61994ee1dd86 100644 --- a/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialog.kt +++ b/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/dialogs/SetPasswordDialog.kt @@ -32,12 +32,13 @@ import app.aaps.core.ui.compose.stringResource /** * Dialog for setting a new password or PIN. - * Requires entering the password twice for confirmation. + * Asks for confirmation unless the preference opts out. * * @param title Dialog title * @param pinInput If true, shows numeric keyboard for PIN input * @param onConfirm Called with (password1, password2) when OK is clicked * @param onCancel Called when Cancel is clicked or dialog is dismissed + * @param requireConfirmation Whether to show a second field. When false, both callback values match. * * @see SetPasswordDialogPreview */ @@ -46,10 +47,12 @@ fun SetPasswordDialog( title: String, pinInput: Boolean, onConfirm: (String, String) -> Unit, - onCancel: () -> Unit + onCancel: () -> Unit, + requireConfirmation: Boolean = true ) { var password1 by remember { mutableStateOf("") } var password2 by remember { mutableStateOf("") } + val confirm = { onConfirm(password1, if (requireConfirmation) password2 else password1) } val focusRequester = remember { FocusRequester() } LaunchedEffect(Unit) { @@ -85,15 +88,16 @@ fun SetPasswordDialog( visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions( keyboardType = if (pinInput) KeyboardType.NumberPassword else KeyboardType.Password, - imeAction = ImeAction.Next + imeAction = if (requireConfirmation) ImeAction.Next else ImeAction.Done ), + keyboardActions = KeyboardActions(onDone = { if (!requireConfirmation) confirm() }), singleLine = true, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) ) - OutlinedTextField( + if (requireConfirmation) OutlinedTextField( value = password2, onValueChange = { password2 = it }, label = { @@ -105,7 +109,7 @@ fun SetPasswordDialog( imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( - onDone = { onConfirm(password1, password2) } + onDone = { confirm() } ), singleLine = true, modifier = Modifier.fillMaxWidth() @@ -113,7 +117,7 @@ fun SetPasswordDialog( } }, confirmButton = { - TextButton(onClick = { onConfirm(password1, password2) }) { + TextButton(onClick = confirm) { Text(stringResource(CoreUiStrings.ok)) } }, diff --git a/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/navigation/ElementTypeStyle.kt b/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/navigation/ElementTypeStyle.kt index c64db1e65888..ffe90b09e602 100644 --- a/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/navigation/ElementTypeStyle.kt +++ b/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/navigation/ElementTypeStyle.kt @@ -73,6 +73,7 @@ fun ElementType.color(): Color = when (this) { ElementType.CGM_XDRIP -> AapsTheme.elementColors.cgmXdrip ElementType.CGM_DEX -> AapsTheme.elementColors.cgmDex ElementType.CALIBRATION -> AapsTheme.elementColors.calibration + ElementType.EVERSENSE_CALIBRATION -> AapsTheme.elementColors.calibration ElementType.INSULIN_MANAGEMENT -> AapsTheme.elementColors.insulin ElementType.PROFILE_MANAGEMENT -> AapsTheme.elementColors.profileSwitch @@ -139,6 +140,7 @@ fun ElementType.icon(): ImageVector = when (this) { ElementType.CGM_XDRIP -> IcXDrip ElementType.CGM_DEX -> IcByoda ElementType.CALIBRATION -> IcCalibration + ElementType.EVERSENSE_CALIBRATION -> IcCalibration ElementType.INSULIN_MANAGEMENT -> IcPluginInsulin ElementType.PROFILE_MANAGEMENT -> IcProfile @@ -210,6 +212,7 @@ fun ElementType.label(): TextRef? = when (this) { ElementType.CGM_XDRIP -> CoreUiStrings.cgm ElementType.CGM_DEX -> CoreUiStrings.cgm ElementType.CALIBRATION -> CoreUiStrings.calibration + ElementType.EVERSENSE_CALIBRATION -> CoreUiStrings.eversense_calibration_label ElementType.INSULIN_MANAGEMENT -> CoreUiStrings.insulin_management ElementType.PROFILE_MANAGEMENT -> CoreUiStrings.profile_management ElementType.TEMP_TARGET_MANAGEMENT -> CoreUiStrings.temp_target_management @@ -272,6 +275,7 @@ fun ElementType.description(): TextRef? = when (this) { ElementType.CGM_DEX -> CoreUiStrings.treatment_cgm_desc ElementType.CALIBRATION -> CoreUiStrings.treatment_calibration_desc + ElementType.EVERSENSE_CALIBRATION -> CoreUiStrings.treatment_eversense_calibration_desc ElementType.BG_CHECK -> CoreUiStrings.treatment_bg_check_desc ElementType.EXERCISE -> CoreUiStrings.treatment_exercise_desc ElementType.ANNOUNCEMENT -> CoreUiStrings.treatment_announcement_desc diff --git a/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/preference/AdaptivePasswordPreference.kt b/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/preference/AdaptivePasswordPreference.kt index 37564802404f..85548eab8160 100644 --- a/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/preference/AdaptivePasswordPreference.kt +++ b/core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/preference/AdaptivePasswordPreference.kt @@ -91,6 +91,7 @@ fun AdaptivePasswordPreferenceItem( SetPasswordDialog( title = stringResource(effectiveTitle), pinInput = isPin, + requireConfirmation = stringKey.requiresPasswordConfirmation, onConfirm = { password1, password2 -> when { password1 != password2 -> { diff --git a/database/impl/src/commonMain/kotlin/app/aaps/database/entities/GlucoseValue.kt b/database/impl/src/commonMain/kotlin/app/aaps/database/entities/GlucoseValue.kt index e0a28f276b65..0465fe030cb6 100644 --- a/database/impl/src/commonMain/kotlin/app/aaps/database/entities/GlucoseValue.kt +++ b/database/impl/src/commonMain/kotlin/app/aaps/database/entities/GlucoseValue.kt @@ -95,6 +95,8 @@ data class GlucoseValue( GLUTEC, GLUPRO, EVERSENSE, + EVERSENSE_E3, + EVERSENSE_365, SYAI_TAG, INSTARA, RANDOM, diff --git a/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourceSensorExtension.kt b/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourceSensorExtension.kt index b58e2371a7bc..fdf6aaea1c93 100644 --- a/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourceSensorExtension.kt +++ b/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourceSensorExtension.kt @@ -30,6 +30,8 @@ fun GlucoseValue.SourceSensor.fromDb(): SourceSensor = GlucoseValue.SourceSensor.ANYTIME -> SourceSensor.ANYTIME GlucoseValue.SourceSensor.GLUTEC -> SourceSensor.GLUTEC GlucoseValue.SourceSensor.GLUPRO -> SourceSensor.GLUPRO + GlucoseValue.SourceSensor.EVERSENSE_E3 -> SourceSensor.EVERSENSE_E3 + GlucoseValue.SourceSensor.EVERSENSE_365 -> SourceSensor.EVERSENSE_365 GlucoseValue.SourceSensor.EVERSENSE -> SourceSensor.EVERSENSE GlucoseValue.SourceSensor.SYAI_TAG -> SourceSensor.SYAI_TAG GlucoseValue.SourceSensor.INSTARA -> SourceSensor.INSTARA @@ -70,6 +72,8 @@ fun SourceSensor.toDb(): GlucoseValue.SourceSensor = SourceSensor.ANYTIME -> GlucoseValue.SourceSensor.ANYTIME SourceSensor.GLUTEC -> GlucoseValue.SourceSensor.GLUTEC SourceSensor.GLUPRO -> GlucoseValue.SourceSensor.GLUPRO + SourceSensor.EVERSENSE_E3 -> GlucoseValue.SourceSensor.EVERSENSE_E3 + SourceSensor.EVERSENSE_365 -> GlucoseValue.SourceSensor.EVERSENSE_365 SourceSensor.EVERSENSE -> GlucoseValue.SourceSensor.EVERSENSE SourceSensor.SYAI_TAG -> GlucoseValue.SourceSensor.SYAI_TAG SourceSensor.INSTARA -> GlucoseValue.SourceSensor.INSTARA diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c98639018f2f..2eaf23a94ca4 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,6 +1,6 @@ # libs.versions.toml [versions] -gradlePlugin = "9.5.0" +gradlePlugin = "9.5.1" kotlin = "2.4.21" room = "2.8.5" metro = "1.5.0" diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 91c4fc64aa0c..6c73eb262e98 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,9 +1,6 @@ +#Sun Nov 15 17:57:35 CET 2026 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip -networkTimeout=10000 -retries=0 -retryBackOffMs=500 -validateDistributionUrl=true +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/plugins/configuration/src/androidMain/assets/AAPS Material.zip b/plugins/configuration/src/androidMain/assets/AAPS Material.zip new file mode 100644 index 000000000000..2146b4d52129 Binary files /dev/null and b/plugins/configuration/src/androidMain/assets/AAPS Material.zip differ diff --git a/plugins/configuration/src/androidMain/assets/AAPS Sport.zip b/plugins/configuration/src/androidMain/assets/AAPS Sport.zip new file mode 100644 index 000000000000..89211dcbcf42 Binary files /dev/null and b/plugins/configuration/src/androidMain/assets/AAPS Sport.zip differ diff --git a/plugins/eversense/.gitignore b/plugins/eversense/.gitignore new file mode 100644 index 000000000000..796b96d1c402 --- /dev/null +++ b/plugins/eversense/.gitignore @@ -0,0 +1 @@ +/build diff --git a/plugins/eversense/README.md b/plugins/eversense/README.md new file mode 100644 index 000000000000..97059bf253bd --- /dev/null +++ b/plugins/eversense/README.md @@ -0,0 +1,166 @@ +# Eversense in AndroidAPS 4 + +The Eversense E3/365 plugin receives glucose readings over Bluetooth. It provides transmitter status, calibration submission, a placement guide and optional uploads to Eversense DMS. + +Project: [BernhardRo/AndroidAPS](https://github.com/BernhardRo/AndroidAPS/tree/master). For architecture and implementation details, see [TECHNICAL.md](TECHNICAL.md). + +The screenshots below show AAPS 4.0.0 (`5d85b5094e`) in English with the dark theme on an Android emulator. No transmitter or DMS account was connected: `0%`, `Never`, `UNKNOWN` and empty signal bars are initial placeholders, not measurements from a transmitter. + +## Setup + +Complete sensor setup and alarm configuration in the official Eversense app first. Keep that app installed for functions not provided by AAPS. + +1. Enable Bluetooth and select **Eversense** as the active blood glucose source in AAPS. Allow the requested Bluetooth/Nearby devices permissions. +2. Open the Eversense settings and expand **Eversense DMS credentials**. +3. Enter your DMS username and password. Both fields are required for E3 and ES365, even with cloud upload disabled. +4. Enable **European transmitter (365)** for a European/OUS DMS account; leave it off for a US account. The default is off. +5. Choose whether to enable cloud upload. It is on by default. +6. Open **Status & Connection**, press **Connect**, wait for the ten-second scan and select your transmitter. If one is already saved, Connect uses it. +7. Wait for connection setup, then check for a current glucose timestamp in the AAPS overview. + +ES365 needs internet for initial registration. It can also need registration again after account or transmitter changes. Verify reception with your actual phone and transmitter before relying on the setup. + +### Select the glucose source + +Open **Configuration > BG Source**, select **Eversense** and confirm the switch. The highlighted card and selected radio button identify the active source. Tap **Open plugin**, then the settings icon in the top right to reach the Eversense settings. + +BG Source configuration with Eversense selected and the Open plugin button visible + +### Two ways to open the settings + +From the overview, use either the **Settings** gear at the top right or the navigation menu at the top left. The screenshot also shows the optional **Eversense Calibration** shortcut in the QuickLaunch toolbar near the bottom, beside its configuration gear. + +Dark overview with the navigation menu at top left, Settings gear at top right and Eversense Calibration plus Configure QuickLaunch icons near the bottom + +| Route | Steps | +| --- | --- | +| **Settings gear, top right** | Open Settings, then expand **Eversense**. Eversense must be the active BG source. If its section is hidden in Simple mode, turn off **General > Simple mode**, return to the overview and reopen Settings, or use the Configuration route below. | +| **Navigation menu, top left** | Choose **Configuration > BG Source > Eversense > Open plugin**, then tap the gear at the top right of the Eversense page. This opens the plugin's own settings. | + +| Settings list reached from the overview gear | Left navigation menu | +| --- | --- | +| Settings list showing the Eversense section with Simple mode off | Left navigation menu with the Configuration entry | + +On the Eversense plugin page, use the gear in the top right (**Plugin preferences**). **No records available** in this example means that no transmitter readings have been received yet. + +Eversense plugin page with the Plugin preferences gear in the top right and no records available + +### Enter the DMS credentials + +Expand **Eversense DMS credentials**. Tap **Username** and **Password** to enter your account details. **Not set** and **Password not set** mean that credentials are still missing. The **European transmitter (365)** switch selects the European servers; the screenshot shows its default off position. **Sign out** clears the saved credentials after confirmation. + +Expanded DMS credentials showing Username, Password, European transmitter (365) and Sign out + +## Settings + +The settings page groups connection controls, cloud upload, diagnostics, credentials and the two transmitter tools. Tap a row to open its page; the switches change cloud upload and diagnostic logging directly. **Documentation & Setup Guide** opens this guide. + +Eversense settings with connection, upload, diagnostics, credentials, documentation, calibration and placement controls + +| Setting | Use | +| --- | --- | +| **Status & Connection** | View battery, sensor and calibration information; connect, disconnect, change transmitter or request a sync. | +| **Enable cloud upload** | Upload data to Eversense DMS at most once per hour. | +| **Diagnostic logging** | Collect extra detail for troubleshooting. Leave off during normal use. | +| **Eversense DMS credentials** | Edit username, password and region, or sign out. | +| **Calibrate transmitter** | Submit a calibration value. | +| **Transmitter Placement** | Check signal feedback while adjusting placement. | + +**START SYNC** refreshes transmitter information; it does not force a DMS upload. **Default Sync Days** does not currently control how much glucose history is recovered. + +## Daily use + +### Connection and transmitter replacement + +Unexpected connection loss triggers automatic retries. A manual **Disconnect** pauses them until you press **Connect** again. + +To use a replacement transmitter, choose **Change Transmitter**, confirm and select it from the scan results. This does not delete glucose history in AAPS. Sensor linking still belongs in the official app. + +Disconnected Status & Connection page with status fields, Connect, Change Transmitter, Default Sync Days and disabled START SYNC + +| UI element | Meaning | +| --- | --- | +| **Connected** | A check mark means the connection is ready after authentication. A Bluetooth link alone is not enough. | +| **Battery**, **Insertion date**, **Last sync** | Transmitter battery and stored sensor/sync timestamps. The initial values shown above have not been read from a transmitter. | +| **Placement signal** | Strength of the transmitter-to-sensor signal. | +| **Calibration phase**, **Last calibration**, **Next calibration** | Calibration state and timestamps reported by the driver. | +| **Connect / Disconnect** | Connect uses the saved transmitter, or opens a scan if none is saved. Once ready, the button becomes Disconnect. | +| **Change Transmitter** | Opens the replacement workflow instead of reconnecting to the saved device. | +| **Default Sync Days** | A selectable value; it does not currently determine recovered glucose history. | +| **START SYNC** | Refreshes transmitter information when connected. It is disabled in this disconnected screenshot. | + +### Calibration + +Calibration is available from the bottom QuickLaunch toolbar and from the plugin settings. Both send a fingerstick value to the Eversense transmitter, with different entry screens. Eversense must be the active BG source for its QuickLaunch action to be available. + +#### From the bottom QuickLaunch toolbar + +1. On the overview, tap the small **Configure QuickLaunch** gear near the bottom, just above the bottom navigation bar. It is separate from the Settings gear at the top right. +2. Under **Treatment**, tap **+** beside **Eversense Calibration**. The action moves into the selected actions list. +3. Return to the overview. Tap the new **Eversense Calibration** shortcut beside the QuickLaunch configuration gear, as shown in the [overview screenshot](#two-ways-to-open-the-settings). +4. Enter the fingerstick value in **BG**, check the unit and adjust with **− / +** if needed. The bottom confirmation button shows the entered value once it is valid. Tap it once to submit. Use **Close** at the top left to leave without submitting. + +| Add the shortcut | Calibration opened from QuickLaunch | +| --- | --- | +| Configure QuickLaunch with the plus button beside Eversense Calibration | Eversense Calibration screen with BG input, mg/dL unit, minus and plus controls and a disabled OK button for the empty field | + +The example shows an empty value and a disconnected transmitter, so the confirmation button is disabled. If necessary, AAPS tries to reconnect when a calibration is submitted. + +#### From the plugin settings + +Open **Calibrate transmitter** in the [Eversense settings](#settings). Check the displayed unit, enter the blood glucose value and tap **Submit calibration** once. If necessary, AAPS first tries to reconnect. + +Calibration page with an empty focused Blood glucose value field, mg/dL unit and Submit calibration button + +Tap **Blood glucose value** to enter the value. The focused field shows the unit on its right; this screenshot uses **mg/dL**. **Submit calibration** sends the entered value. The screenshot shows an empty field; no calibration was submitted for these illustrations. + +A warning appears for current vertical or double up/down trend arrows, including stronger trends. A 45-degree arrow does not trigger it. The warning does not block submission. Follow the manufacturer's [calibration guidance](https://www.eversensecgm.com/siteassets/eversense-pwd-resources/eversense-365_fingcalibration_101124_v2-006.pdf); no warning does not prove that glucose is stable. + +A successful submission starts a 15-minute countdown in the overview. This is not confirmation that the transmitter has finished processing. If submission fails, check connection and transmitter readiness before trying again. + +### Placement + +Open **Transmitter Placement**, adjust the transmitter using the signal feedback, then leave the page when finished. Placement signal describes the transmitter-to-sensor connection, not the phone's Bluetooth connection. + +Transmitter Placement Guide with five inactive signal bars and the Not connected message + +The five bars visualize placement signal strength. When readings are available, the page also shows a signal label, value and update time. Here, **Not connected** and inactive bars mean that no live placement signal is available; connect the transmitter before using the guide. + +### Credentials and sign out + +Account or region changes can interrupt reception and require ES365 registration again, so keep internet available. + +**Sign out** is inside the expanded credentials group. After confirmation, it deletes the saved username/password and pending cloud uploads and pauses the connection. AAPS glucose history is retained. To resume, enter the credentials again and connect. Use Disconnect, rather than Sign out, for a temporary pause. + +## Using the original Eversense app + +**The original app can stay installed; uninstalling it is not required.** Keep it for sensor setup, transmitter settings and switching back to the manufacturer workflow. + +- **E3:** parallel reception can work. Keep using both only if both receive current readings reliably. +- **ES365:** reliable parallel reception has not been established. Start with one active receiver. + +If the apps compete, use Android **Settings > Apps > Eversense / Eversense 365 > Force stop** for the original app, then connect in AAPS. Swiping its window away may not stop its Bluetooth service. A force-stopped app does not provide its normal phone notifications until restarted. + +To switch back, disconnect in AAPS first, then open the original app and check reception. Returning to AAPS may require ES365 online registration again. Do not clear app storage, remove Bluetooth pairing or relink the sensor simply to switch receivers. + +## Offline use and cloud upload + +After initial setup, readings can be received without internet, including in airplane mode with Bluetooth enabled. ES365 needs internet if registration is required again. + +DMS upload is optional and does not affect local glucose reception. Uploads are attempted at most once per hour; readings are kept for up to seven days while waiting for connectivity. + +## Troubleshooting and limits + +| Problem | Check or limitation | +| --- | --- | +| No scan result | Bluetooth, Nearby devices permissions, range and transmitter state. Allow ten seconds for the scan. | +| Connect uses the old transmitter | Use Change Transmitter. | +| ES365 cannot finish registration | Internet, DMS credentials and European region. | +| No readings after Disconnect | Press Connect to resume automatic connection attempts. | +| Connected but no fresh glucose | Check the glucose timestamp, transmitter state, battery and placement. A status sync is not a new reading. | +| Gaps remain in history | E3 has no glucose backfill. ES365 recovery is limited, not a complete archive download. | +| Readings appear in AAPS but not DMS | Check upload, account/region and internet; allow for the hourly limit. Some recovered ES365 history cannot be uploaded. | + +A settings export does not replace transmitter setup on a new phone. ES365 registration may be required again. + +For a problem report, include the AAPS build, transmitter model, phone/Android version, problem time and whether the original app was running. Enable Diagnostic logging briefly to reproduce the issue, then turn it off. Review logs for private health/device data before sharing. diff --git a/plugins/eversense/TECHNICAL.md b/plugins/eversense/TECHNICAL.md new file mode 100644 index 000000000000..5c082cdd2f75 --- /dev/null +++ b/plugins/eversense/TECHNICAL.md @@ -0,0 +1,282 @@ +# Eversense plugin: architecture and behavior + +This document describes the Eversense E3/365 implementation in this AAPS 4 checkout. It explains ownership, data flow, failure handling and current limits. It is not a claim of complete transmitter compatibility. + +For setup and practical instructions, read the [user guide](README.md). Project: [BernhardRo/AndroidAPS, master](https://github.com/BernhardRo/AndroidAPS/tree/master). + +## Module boundaries + +| Area | Responsibility | Entry points | +| --- | --- | --- | +| This module | Android BLE, connection lifecycle, commands, codecs, authentication and DMS clients | EversenseCGMPlugin, EversenseGattCallback | +| [Source adapter](../source/src/androidMain/kotlin/app/aaps/plugins/source/EversensePlugin.kt) | AAPS source registration, preferences, persistence, cloud queue and notifications | EversensePlugin | +| [Source integration helpers](../source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/) | Driver storage adapter, cloud delivery, placement lifecycle | EversenseStateStore, EversenseCloudUploader, PositioningSession | +| [Android activities](../source/src/androidMain/kotlin/app/aaps/plugins/source/activities/) | Status, calibration and placement screens | EversenseStatusActivity, EversenseCalibrationActivity, EversensePlacementActivity | +| [Shared calibration UI](../../ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/) | Overview calibration form and view model | EversenseCalibrationDialogViewModel | +| core/interfaces | Shared calibration contract | EversenseCalibrationSource | +| core/keys and core/ui | Typed preference keys, password dialog and theme selection | StringPreferenceKey, SetPasswordDialog, UiMode | + +The driver uses EversenseStore rather than directly reading AAPS preferences. The source module supplies the store adapter. Bluetooth and DMS delivery are Android-only; shared UI checks the active source's calibration contract. + +Metro registers the source, driver and activity member injectors. The three device activities extend MetroAppCompatActivity. The application must provide their dependencies before layout inflation. + +## Reading flow + +```mermaid +flowchart TD + T[Transmitter] --> G[Gatt callback and packet engine] + G --> C[Model communicator] + C --> W[Watcher callbacks] + W --> S[Eversense source adapter] + S --> P[AAPS glucose persistence] + P --> L[Normal local AAPS processing] + P --> Q[Optional persistent cloud queue] + Q --> H[DMS clients] + H --> D[Eversense DMS] +``` + +Communicators decode readings and update driver state. The source maps readings to GV, preserving timestamp, glucose, trend and E3/365 source identity. It calls insertCgmSourceData before enqueueing optional cloud work. Upload failure cannot roll back a stored reading. + +Watchers receive connection, readiness, state, glucose, alarm and placement events. A BLE link is not yet a ready transmitter: isConnected requires both a connected link and transmitterReady. ES365 attempts a glucose read after authentication instead of waiting for the next keep-alive. + +## Connection control + +EversenseConnectionController owns connection intent and timing. EversenseGattCallback owns the Android transport. The manager connects them through a small Transport interface. + +| State | Meaning | +| --- | --- | +| STOPPED | Source stopped; no connection wanted. | +| PAUSED | Source running, but connection intent paused. | +| DISCONNECTED | Connection wanted; a retry can be pending. | +| CONNECTING | Opening or authenticating the connection. | +| READY | Session usable; data watchdog active. | + +Source start requests automatic connection when credentials are present. Ordinary Connect calls do not start a second attempt while already connecting. The status page's explicit Connect uses the force path to restart an in-progress attempt. Manual Disconnect clears intent, invalidates work and cancels retries. Bluetooth becoming available only restarts work if the running source still wants a connection. + +Unexpected failures back off through 5, 10, 20, 40 and 60 seconds. Failure to open a transport uses a 60-second retry. E3 status 19 waits 30 seconds. A normal ES365 status-19 reconnect can reuse the GATT handle. + +```mermaid +stateDiagram-v2 + [*] --> STOPPED + STOPPED --> CONNECTING: Start with credentials + STOPPED --> PAUSED: Start without credentials + PAUSED --> CONNECTING: Explicit Connect + CONNECTING --> READY: Session ready + CONNECTING --> DISCONNECTED: Failure or deadline + READY --> DISCONNECTED: Unexpected disconnect + DISCONNECTED --> CONNECTING: Retry timer + READY --> CONNECTING: Data watchdog + CONNECTING --> PAUSED: Manual Disconnect + READY --> PAUSED: Manual Disconnect + DISCONNECTED --> PAUSED: Manual Disconnect +``` + +Stop can move any running state to STOPPED and releases its resources. The diagram shows normal transitions; a forced Connect can also restart an existing attempt. PAUSED has no automatic retry. + +### Stale callbacks and results + +Each fresh GATT client gets a session token. Callback delivery and store access check ownership. Invalidation changes the token before closing the old client, so queued old work cannot publish new state. + +Reused ES365 GATT handles also have a link generation. Authentication and network work capture this generation and use a restricted SessionStore. Results from a prior handshake cannot be accepted on a later link that reuses the callback. + +Cloud work has a separate generation. Ordinary BLE reconnects do not cancel a valid upload. Explicit invalidation, such as stop, manual disconnect or account changes, ends that generation. SessionStore checks reads and final editor commits; stale access raises cancellation. + +### Timing and cleanup + +| Operation | Bound or behavior | +| --- | --- | +| Device scan | Ten-second deadline, with owner-specific cancellation handle | +| Connection/authentication | Three-minute attempt deadline | +| Data watchdog | Checked every minute; restarts after more than seven minutes without data | +| Ordinary packet response | Five-second default timeout | +| E3 calibration packet | Fifteen-second response timeout | +| Manager calibration operation | Twenty-second outer wait | +| UI calibration reconnect | Thirty-second wait | +| Full sync | Normally skipped if another completed within four minutes; force bypasses this | +| Placement | Initial 500 ms delay, then 500 ms between completed reads | + +A write lock serializes packet exchanges. PacketExchange is registered before sending, so an early response cannot miss its waiter. Packet timeout closes the link before another command can consume a late response. + +The callback has dedicated BLE and network executors. Registration HTTP runs on the network executor; the authentication sequence can wait for it without putting HTTP inside the Android BLE callbacks. Closing a callback releases GATT and executor resources. Source stop cancels its scope, removes watchers, stops scanning and closes the driver. + +## Discovery, identity and authentication + +The status UI presents scan results with names beginning with T followed by digits and removes duplicate names. The chosen Bluetooth address is saved. Service/characteristic discovery selects E3 or SecureV2; the credentials screen title does not select the model. + +E3 has no ES365 online identity-registration exchange. The manager still requires non-empty username/password fields before opening either model's connection. + +For ES365, EversenseCrypto365Util holds long-lived client identity material and a registration-shortcut flag. Without a usable shortcut, validated internet is required: the flow identifies the transmitter, logs in to DMS and obtains a certificate to register the identity. It then performs the local ephemeral/session handshake. + +With an accepted saved identity, a new session can be established locally without refreshing the DMS upload token. Cloud tokens and BLE session keys serve different purposes. Upload-token expiry alone does not invalidate the BLE identity. + +```mermaid +flowchart TD + Start[ES365 connection] --> Shortcut{Registration shortcut available?} + Shortcut -->|Yes| Local[Local session handshake] + Shortcut -->|No| Internet{Validated internet?} + Internet -->|No| Wait[Keep stored identity and retry later] + Internet -->|Yes| Register[DMS login and identity registration] + Register --> Local + Local --> Success{Handshake succeeds?} + Success -->|Yes| Sync[Initial sync and glucose read attempt] + Sync --> Ready[Announce transmitter ready] + Success -->|No| Retry[Failure handling and reconnect] +``` + +The offline path depends on a usable identity already being accepted by the transmitter. Failure handling can change which path the next attempt takes; the shortcut flag is not proof that a handshake will succeed. + +Offline failures retain identity material for later attempts. Online authentication or decryption failures can invalidate the shortcut and trigger full registration. Stored identity is not guaranteed to remain accepted after transmitter changes or use by another client. + +SecureV2Cipher owns stateless AES-CCM, sequence prefix and nonce construction. EversenseCrypto365Util retains identity, ephemeral material and sequence-counter ownership. Signing, ECDH, HKDF and AES use the existing cryptographic libraries. + +### Original Eversense app + +The plugin neither requires uninstalling the original app nor coordinates its Bluetooth use. It does not stop the original app, share its active connection or import its authenticated session. + +Parallel E3 use is a reported setup behavior, not an enforced invariant. Reliable ES365 concurrent reception has not been established. Switching clients can exercise shortcut invalidation and online registration. The user guide therefore distinguishes keeping the app installed from allowing it to compete as an active receiver. + +## Packet and binary layers + +EversenseBasePacket takes an immutable PacketSpec with request ID, response ID, type ID and security mode. Metadata is explicit rather than discovered through runtime annotations. Public command names and nested response models remain available to callers. + +The 109 command classes are grouped into eight files: E3 session, register queries, history queries, settings and calibration; ES365 session, data queries and settings. E3RegisterPacket shares register-address request encoding. + +| Component in protocol/ | Responsibility | +| --- | --- | +| PacketSpec | Explicit command contract and response offset | +| WireEncoding | E3 command/payload/CRC16 frames and SecureV2 MTU framing | +| BinaryFields | Little-endian fields, packed dates/times, timezone offsets and sensor epoch | +| CalibrationPayload | Shared primitives with separate E3/ES365 layouts | +| GlucoseDecoders | Model offsets, validity bounds and trend mapping | +| NotificationAssembler | SecureV2 fragment order, duplicate suppression and assembly | +| SecureV2Cipher | Stateless authenticated encryption | +| PacketTime | System time in production; scoped clock input in tests | + +The response buffer and notification assembler use growing byte streams instead of copying the full accumulated response at each append. The assembler ignores an identical fragment repeated inside one second. A new first fragment restarts partial assembly; an out-of-order fragment discards it. Reassembly does not own reconnect policy. + +Some legacy rules remain intentionally unchanged: E3 accepts 20 through 450 mg/dL; ES365 rejects 450 and above and does not apply the same lower bound. Unknown live trends map to NONE; history mapping can use FLAT. Some malformed frames still throw. Compatibility tests preserve outcome categories, not general malformed-input hardening. + +## Synchronization and history + +E3 reads current glucose, status and calibration/log information. It does not backfill glucose history into AAPS. + +ES365 reads current glucose and attempts calibration/history requests. RangeCalculator uses the prior glucose timestamp and caps a history request at 20 log indices. Returned history must lie between the previous and new live reading, with a 90-second margin at both ends. A history failure does not make recovery mandatory before publishing an otherwise usable current reading. + +The status UI saves eversense_sync_days, default 14. Neither communicator uses it to calculate history requests. It is not a multi-day archive-download control. Recovered entries can lack sensor ID or raw data needed for full cloud representation. + +A forced full sync bypasses the recent-sync check and requests transmitter data. It does not flush cloud work or bypass the hourly upload limit. + +## Calibration and placement + +The source implements EversenseCalibrationSource. If needed, it requests a connection and waits for readiness; cancellation removes the temporary watcher. The settings activity has a separate calibration form and reconnect path. + +The shared calibration dialog limits input to 40–400 mg/dL or 2.2–22.2 mmol/L. The Android settings form checks a positive number and converts the displayed unit. These validation paths are not identical. Model-specific command adapters encode and send calibration values. + +After successful send, the manager updates local calibration timestamps and provisional waiting state, then asynchronously re-reads E3 readiness. Callers request a forced sync and record EversenseLastCalibrationSubmittedAt. That timestamp drives the 15-minute overview countdown; it is presentation state, not proof of clinical readiness or an enforced interval. + +EversenseCalibrationDynamics reads LastBgData and DateUtil. It warns only for fresh SINGLE, DOUBLE or TRIPLE up/down arrows. FORTY_FIVE_UP, FORTY_FIVE_DOWN, FLAT and NONE do not warn; a computed delta does not override that rule. Data older than Constants.OLD_BG_MINUTES or dated in the future is ignored. Missing data is not evidence of stability. The warning component is shared by both calibration entry points and uses the standard AAPS WarningBanner. It refreshes on resume and every five seconds while resumed, reading off the UI thread. Pause/disposal cancels that job; it does not poll Bluetooth or DMS. Warning state does not participate in canSubmit and does not block the driver call. + +PositioningSession polls while the placement activity is resumed. Its mutex makes a new session wait for the old session's exit. Pause cancels polling, and a non-cancellable cleanup block attempts to leave transmitter diagnostic/placement mode. Diagnostic logging is a separate feature. + +## Cloud delivery and offline behavior + +EversenseCloudUploader owns an optional persistent queue, independent of BLE connection control. Enqueue follows successful local persistence. + +- Batches group readings by transmitter type and serial number. Readings deduplicate by timestamp and sensor ID, preferring more raw data. +- ES365 entries without raw response data are excluded from the cloud queue, but can remain in AAPS. +- Retention is seven days with a total cap of 2016 readings; it does not prune AAPS history. +- A mutex protects updates and an atomic busy flag prevents concurrent flushes. +- Upload requires validated internet and the enabled setting. An attempt is reserved before HTTP, so failures also consume the hourly slot. +- The wall-clock attempt timestamp survives restart. A monotonic timestamp also prevents repeat attempts within an hour in the same process. A backward wall-clock jump resets the stored reference and defers that cycle. +- A later enqueue can trigger a due flush. There is no independent hourly wake-up timer. +- Successful batches are removed. Failure retains the batch and stops that cycle. Earlier successful requests can be repeated on retry; multiple endpoints are not one transaction. + +ES365 delivery sends raw glucose, current portal values and device events. E3 sends current values and device events. One hourly cycle can make several requests. Upload failure does not request BLE reconnection. + +DmsHttpClient shares HTTP transport, form/JSON content types, headers, UTF-8 handling and connection cleanup. DmsAccessTokens refreshes cached tokens with a five-minute expiry margin. Model clients retain their payloads and endpoint routing. E3 uses OUS endpoints; the region setting selects the ES365 US/EU group. + +POST requests have 30-second connect/read timeouts. Certificate GET retains legacy zero/default transport timeouts. Registration has 65-second future waits and the outer connection deadline; those bounds do not guarantee immediate interruption of every underlying HTTP call. + +Local Bluetooth reception does not wait for upload. ES365 initial registration still needs internet with optional upload off. Connectivity checks require Android internet capability and validated connectivity. + +```mermaid +sequenceDiagram + participant Driver as BLE driver + participant Source as AAPS source + participant DB as AAPS persistence + participant Queue as Cloud queue + participant DMS as Eversense DMS + Driver->>Source: Glucose readings + Source->>DB: Store readings + DB-->>Source: Persistence completes + opt Cloud upload enabled + Source->>Queue: Enqueue eligible readings + alt Offline or hourly slot not due + Queue->>Queue: Retain pending readings + else Online and hourly slot due + Queue->>Queue: Reserve attempt before HTTP + Queue->>DMS: Upload batch through model endpoints + alt Batch succeeds + DMS-->>Queue: Success + Queue->>Queue: Remove successful batch + else Request fails + DMS-->>Queue: Error + Queue->>Queue: Keep batch for a later cycle + end + end + end +``` + +The stored readings remain available to normal AAPS processing regardless of the optional cloud branch. A cloud cycle is not scheduled at an exact clock time and can contain multiple HTTP requests. + +## Storage and account changes + +| Data | Storage/export behavior | +| --- | --- | +| Username, password, region and upload preference | Registered AAPS settings; username/password are exportable | +| Device/secure state, saved address, token metadata | EversenseRuntimeKey.DeviceState, eversense_device_state_json; not exported | +| Pending batches | EversenseRuntimeKey.CloudQueue, eversense_cloud_queue_json; not exported | +| Diagnostic switch | Registered, off by default, not exported | +| Glucose history | AAPS persistence, separate from driver state and queue | + +EversenseStateStore imports legacy EversenseCGMManager SharedPreferences once if no registered device-state value exists. The old file remains. New writes use typed AAPS storage. The separate queue value avoids copying all queued readings on normal state updates. Settings import does not rewind live driver state. + +The password is hidden in the UI but retrievable for login, not one-way hashed. The implementation does not establish that all account/identity storage is encrypted. Treat device storage, exports and logs as potentially sensitive. + +Account/region changes invalidate current work, update state, disable the registration shortcut and clear tokens and queued uploads before reconnecting. Sign out also clears typed username/password and pauses connection intent. It does not wipe every identity field or delete AAPS history. Change Transmitter removes the saved Bluetooth address. These operations have different effects. + +## Settings, theme and logging + +DMS username, password, region and Sign out share one collapsible group. Sign out supplies an IntentPreferenceKey confirmation message. The normal renderer executes the clearing callback only after confirmation. + +StringPreferenceKey.requiresPasswordConfirmation defaults to true. Only the Eversense password opts out. SetPasswordDialog then shows one masked field with a Done action and passes the entered value to both existing callback arguments. Other password/PIN preferences retain confirmation and their storage rules. + +The three device activities use Compose with the central AapsTheme, LocalPreferences and AapsTopAppBar, as the other settings pages do. MaterialTheme supplies backgrounds, text, cards, buttons, menus and connection/scan dialogs. There is no private Eversense light/dark palette or XML theme selector. Theme changes update while a page is open, and standard Scaffold/app-bar insets protect navigation from system bars. The placement guide uses the same theme colors for active and inactive bars. + +The source observes the diagnostic switch and resets active diagnostic logging on stop. Detailed messages use lazy formatting where supported. Dumps, state detail and stack traces are gated; normal action/status/error logs can still contain health/device information. Symmetric session keys are not logged. Disabling logging does not erase existing logs. + +## Automated tests + +From the repository root, use the supported JDK and ./gradlew.bat on Windows or ./gradlew on other hosts: + +```text +./gradlew.bat :plugins:eversense:testAndroidHostTest +./gradlew.bat :plugins:source:testAndroidHostTest --tests "*Eversense*Test" --tests "*PositioningSessionTest" +./gradlew.bat :core:ui:testAndroidHostTest --tests "*SetPasswordDialogTest" +./gradlew.bat :ui:testAndroidHostTest --tests "*EversenseCalibration*Test" +./gradlew.bat :app:testFullDebugUnitTest --tests "*SourceGraphTest" --tests "*PreferenceKeySnapshotTest" --tests "*RawPreferenceStoreScanTest" +``` + +Coverage includes controller timing, pause/reuse, stale writes, early packet responses, queue retention and hourly limits, persistence during cloud failure, calibration, navigation, password entry and theme selection. Application graph tests cover integration. Run broader project checks when changing shared APIs and follow repository instructions before publishing. + +### Frozen reference + +src/androidHostTest/resources/protocol-reference.zip freezes the driver from commit bb0b0373cd6ccf6b935a63783cb5fcf29468e317. The archive and 156 source files have pinned SHA-256 checks. The command list records all 109 commands. Do not regenerate the reference from changed production code to make comparisons pass. + +Gradle compiles reference sources only for host tests in an isolated package. Preparation changes package names, clock inputs, logger routing and endpoint mutability to supply equal inputs and local HTTP servers. Reference protocol algorithms stay unchanged. These classes are not APK production code. + +Comparisons cover metadata, payloads, MTU frames, decoding and failure categories; dates, times and timezones; calibration and DMS binary records; notification traces; ciphertext, counters and tampering; and HTTP paths, headers, bodies, outcomes and caching. Independent CRC vectors and binary golden records supplement the reference. This protects exercised behavior, including legacy quirks; it is not formal proof of every device state. + +## Real-device checks + +Initial registration, reconnect, Bluetooth-off recovery, manual pause/resume, calibration results, placement cleanup and airplane mode with Bluetooth re-enabled still need device validation. Check local reception and DMS separately. Test original-app coexistence and measure battery use when relevant. Automated tests alone do not establish these outcomes. diff --git a/plugins/eversense/build.gradle.kts b/plugins/eversense/build.gradle.kts new file mode 100644 index 000000000000..8a294b7a5a10 --- /dev/null +++ b/plugins/eversense/build.gradle.kts @@ -0,0 +1,62 @@ +import java.util.zip.ZipFile + +plugins { + id("kmp-android-library") + id("kotlinx-serialization") +} + +kotlin { + android { + namespace = "app.aaps.plugins.eversense" + withHostTest { isIncludeAndroidResources = true; isReturnDefaultValues = true } + } + sourceSets { + androidMain.dependencies { + api(libs.androidx.core) + api(project.dependencies.platform(libs.kotlinx.serialization.bom)) + api(libs.kotlinx.serialization.json) + api(libs.org.slf4j.api) + api(libs.com.github.tony19.logback.android) + implementation("org.bouncycastle:bcpkix-jdk18on:1.81") + implementation("org.bouncycastle:bcprov-jdk18on:1.81") + } + getByName("androidHostTest").dependencies { + implementation(libs.org.junit.jupiter) + implementation(libs.org.junit.jupiter.api) + runtimeOnly(libs.org.junit.platform.launcher) + implementation(libs.org.mockito.kotlin) + implementation(libs.org.mockito.junit.jupiter) + implementation("com.squareup.okhttp3:mockwebserver:4.12.0") + } + } +} + +// Compile the frozen implementation in an isolated package for byte/result comparison tests. +val generateProtocolReference by tasks.registering { + val archive = layout.projectDirectory.file("src/androidHostTest/resources/protocol-reference.zip") + val destination = layout.buildDirectory.dir("generated/protocolReference") + inputs.file(archive) + outputs.dir(destination) + doLast { + val output = destination.get().asFile + ZipFile(archive.asFile).use { zip -> + zip.entries().asSequence().filter { it.name.endsWith(".kt") && !it.name.endsWith("EversenseLogger.kt") }.forEach { entry -> + val target = output.resolve(entry.name) + check(target.toPath().normalize().startsWith(output.toPath().normalize())) + target.parentFile.mkdirs() + val source = zip.getInputStream(entry).bufferedReader(Charsets.UTF_8).use { it.readText() } + .replace("app.aaps.plugins.eversense", "app.aaps.plugins.eversense.reference") + .replace("app.aaps.plugins.eversense.reference.util.EversenseLogger", "app.aaps.plugins.eversense.util.EversenseLogger") + .replace(Regex("private const val (eu(?:Token|Upload|Care|Vault)BaseUrl)"), "internal var $1") + .replace("System.currentTimeMillis()", "app.aaps.plugins.eversense.protocol.PacketTime.nowMillis()") + .replace("SystemClock.elapsedRealtime()", "app.aaps.plugins.eversense.protocol.PacketTime.nowMillis()") + val prepared = if ("EversenseLogger" in source && "import app.aaps.plugins.eversense.util.EversenseLogger" !in source) { + val end = source.indexOf('\n') + 1 + source.substring(0, end) + "\nimport app.aaps.plugins.eversense.util.EversenseLogger\n" + source.substring(end) + } else source + target.writeText(prepared, Charsets.UTF_8) + } + } + } +} +kotlin.sourceSets.getByName("androidHostTest").kotlin.srcDir(generateProtocolReference) diff --git a/plugins/eversense/docs/screenshots/README.md b/plugins/eversense/docs/screenshots/README.md new file mode 100644 index 000000000000..e1965c1f228b --- /dev/null +++ b/plugins/eversense/docs/screenshots/README.md @@ -0,0 +1,29 @@ +# Eversense README screenshots + +These PNGs are unmodified Android screenshots from AAPS 4.0.0, commit `5d85b5094e`, captured on a Pixel 6a emulator running Android 16 (API 36.1), at 1080 × 2400 pixels. The app uses English, dark theme and the default color scheme. No DMS credentials, transmitter identifiers or patient readings were entered. + +| File | Page/state | +| --- | --- | +| `bg-source.png` | Configuration > BG Source, Eversense selected | +| `settings.png` | Eversense settings, credentials collapsed | +| `credentials.png` | Eversense settings, credentials expanded and empty | +| `status-connection.png` | Status & Connection, disconnected and never synchronized | +| `calibration.png` | Calibrate transmitter, empty field focused, keyboard dismissed | +| `placement.png` | Transmitter Placement, disconnected | +| `overview-navigation.png` | Overview with navigation menu, Settings gear and configured Eversense Calibration QuickLaunch action | +| `settings-list.png` | Settings opened from the overview gear, Simple mode off, Eversense section visible | +| `navigation-menu.png` | Left navigation menu with Configuration | +| `plugin-navigation.png` | Eversense plugin page with its own preferences gear, no readings | +| `quicklaunch-configuration.png` | Configure QuickLaunch before adding Eversense Calibration using its plus button | +| `quicklaunch-calibration.png` | Eversense Calibration opened from QuickLaunch, empty BG field, no submission | + +The overview uses the default virtual pump with no profile or glucose readings. Its pump indicators are emulator defaults. For the Settings list capture, Simple mode was turned off and the settings page was reopened. Eversense Calibration was added to QuickLaunch through its configuration screen; no transmitter connection or calibration submission was performed. + +To update an image, install the matching build on an emulator, navigate to the corresponding page, wait for transitions to finish and capture the screen: + +```sh +adb -s shell screencap -p /sdcard/eversense-screen.png +adb -s pull /sdcard/eversense-screen.png .png +``` + +Check the image against the current UI before replacing it. Keep credentials empty and use a disconnected emulator to avoid publishing private device or health data. The parent README displays images at 320 pixels wide and explains controls using their visible labels. diff --git a/plugins/eversense/docs/screenshots/bg-source.png b/plugins/eversense/docs/screenshots/bg-source.png new file mode 100644 index 000000000000..e570250e6702 Binary files /dev/null and b/plugins/eversense/docs/screenshots/bg-source.png differ diff --git a/plugins/eversense/docs/screenshots/calibration.png b/plugins/eversense/docs/screenshots/calibration.png new file mode 100644 index 000000000000..e180769cbf0c Binary files /dev/null and b/plugins/eversense/docs/screenshots/calibration.png differ diff --git a/plugins/eversense/docs/screenshots/credentials.png b/plugins/eversense/docs/screenshots/credentials.png new file mode 100644 index 000000000000..d7fe1eea29e8 Binary files /dev/null and b/plugins/eversense/docs/screenshots/credentials.png differ diff --git a/plugins/eversense/docs/screenshots/navigation-menu.png b/plugins/eversense/docs/screenshots/navigation-menu.png new file mode 100644 index 000000000000..1ad1a4929a31 Binary files /dev/null and b/plugins/eversense/docs/screenshots/navigation-menu.png differ diff --git a/plugins/eversense/docs/screenshots/overview-navigation.png b/plugins/eversense/docs/screenshots/overview-navigation.png new file mode 100644 index 000000000000..fc897026924a Binary files /dev/null and b/plugins/eversense/docs/screenshots/overview-navigation.png differ diff --git a/plugins/eversense/docs/screenshots/placement.png b/plugins/eversense/docs/screenshots/placement.png new file mode 100644 index 000000000000..318cdaf4a041 Binary files /dev/null and b/plugins/eversense/docs/screenshots/placement.png differ diff --git a/plugins/eversense/docs/screenshots/plugin-navigation.png b/plugins/eversense/docs/screenshots/plugin-navigation.png new file mode 100644 index 000000000000..176a03ae7b38 Binary files /dev/null and b/plugins/eversense/docs/screenshots/plugin-navigation.png differ diff --git a/plugins/eversense/docs/screenshots/quicklaunch-calibration.png b/plugins/eversense/docs/screenshots/quicklaunch-calibration.png new file mode 100644 index 000000000000..4c9f10750388 Binary files /dev/null and b/plugins/eversense/docs/screenshots/quicklaunch-calibration.png differ diff --git a/plugins/eversense/docs/screenshots/quicklaunch-configuration.png b/plugins/eversense/docs/screenshots/quicklaunch-configuration.png new file mode 100644 index 000000000000..2bd0d01ce566 Binary files /dev/null and b/plugins/eversense/docs/screenshots/quicklaunch-configuration.png differ diff --git a/plugins/eversense/docs/screenshots/settings-list.png b/plugins/eversense/docs/screenshots/settings-list.png new file mode 100644 index 000000000000..0db2ddceb8b3 Binary files /dev/null and b/plugins/eversense/docs/screenshots/settings-list.png differ diff --git a/plugins/eversense/docs/screenshots/settings.png b/plugins/eversense/docs/screenshots/settings.png new file mode 100644 index 000000000000..fdacb9954ebc Binary files /dev/null and b/plugins/eversense/docs/screenshots/settings.png differ diff --git a/plugins/eversense/docs/screenshots/status-connection.png b/plugins/eversense/docs/screenshots/status-connection.png new file mode 100644 index 000000000000..7ca8316e90b1 Binary files /dev/null and b/plugins/eversense/docs/screenshots/status-connection.png differ diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/EversenseCredentialsTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/EversenseCredentialsTest.kt new file mode 100644 index 000000000000..3093340a6cac --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/EversenseCredentialsTest.kt @@ -0,0 +1,75 @@ +package app.aaps.plugins.eversense + +import android.bluetooth.BluetoothManager +import android.content.Context +import app.aaps.plugins.eversense.models.EversenseSecureState +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.util.StorageKeys +import kotlinx.serialization.json.Json +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.mockito.kotlin.* + +class EversenseCredentialsTest { + private val store: EversenseStore = mock() + private val editor: EversenseStore.Editor = mock() + private val context: Context = mock() + private val bluetooth: BluetoothManager = mock() + private val json = Json { ignoreUnknownKeys = true } + private fun backend(): EversenseCGMPlugin { + whenever(store.edit()).thenReturn(editor) + whenever(editor.commit()).thenReturn(true) + whenever(store.getString(StorageKeys.SECURE_STATE, null)).thenReturn( + json.encodeToString(EversenseSecureState().apply { username = "user"; password = "secret"; canUseShortcut = true })) + return EversenseCGMPlugin(context, bluetooth, store) + } + @Test fun clearCredentialsRemovesCachedLoginAndDisablesShortcut() { + val backend = backend() + backend.clearCredentials() + val state = argumentCaptor() + verify(editor).putString(eq(StorageKeys.SECURE_STATE), state.capture()) + val saved = json.decodeFromString(state.firstValue) + assertEquals("", saved.username) + assertEquals("", saved.password) + assertFalse(saved.canUseShortcut) + assertEquals("", backend.username) + assertEquals("", backend.password) + verify(editor).remove(StorageKeys.ACCESS_TOKEN) + verify(editor).remove(StorageKeys.ACCESS_TOKEN_EXPIRY) + verify(editor).commit() + verifyNoInteractions(bluetooth) + } + @Test fun regionChangeInvalidatesTokenAndShortcutBeforeDriverIsStarted() { + val backend = backend() + backend.setCredentials("user", "secret", europeanRegion = true) + val state = argumentCaptor() + verify(editor).putString(eq(StorageKeys.SECURE_STATE), state.capture()) + val saved = json.decodeFromString(state.firstValue) + assertTrue(saved.isEuropeanRegion) + assertFalse(saved.canUseShortcut) + verify(editor).remove(StorageKeys.ACCESS_TOKEN) + verify(editor).remove(StorageKeys.ACCESS_TOKEN_EXPIRY) + verifyNoInteractions(bluetooth) + } + @Test fun repeatedOfflineShortcutFailuresRetainRegisteredIdentity() { + val backend = backend() + val adapter: android.bluetooth.BluetoothAdapter = mock() + val device: android.bluetooth.BluetoothDevice = mock() + val gatt: android.bluetooth.BluetoothGatt = mock() + whenever(bluetooth.adapter).thenReturn(adapter) + whenever(adapter.isEnabled).thenReturn(true) + whenever(store.getString(StorageKeys.REMOTE_DEVICE_KEY, null)).thenReturn("00:11:22:33:44:55") + whenever(adapter.getRemoteDevice(any())).thenReturn(device) + whenever(device.connectGatt(eq(context), eq(false), any(), eq(android.bluetooth.BluetoothDevice.TRANSPORT_LE))).thenReturn(gatt) + backend.setCredentials("user", "secret", false) + backend.start() + try { + val callback = argumentCaptor() + verify(device).connectGatt(eq(context), eq(false), callback.capture(), eq(android.bluetooth.BluetoothDevice.TRANSPORT_LE)) + val session = (callback.firstValue as EversenseGattCallback).session + repeat(10) { backend.authenticationFailed(session, shortcut = true) } + verify(editor, never()).putString(eq(StorageKeys.SECURE_STATE), anyOrNull()) + } finally { backend.stop() } + } + +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/EversenseGattCallbackTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/EversenseGattCallbackTest.kt new file mode 100644 index 000000000000..16ae767b8897 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/EversenseGattCallbackTest.kt @@ -0,0 +1,217 @@ +package app.aaps.plugins.eversense + +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic +import app.aaps.plugins.eversense.connection.EversenseConnectionController +import app.aaps.plugins.eversense.connection.SessionStore +import app.aaps.plugins.eversense.exceptions.EversenseWriteException +import app.aaps.plugins.eversense.packets.e3.GetSignalStrengthRawPacket +import app.aaps.plugins.eversense.storage.EversenseStore +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.* + +class EversenseGattCallbackTest { + private val plugin: EversenseCGMPlugin = mock() + private val gatt: BluetoothGatt = mock() + private val characteristic: BluetoothGattCharacteristic = mock() + private val delegate: EversenseStore = mock() + private val controller = EversenseConnectionController( + object : EversenseConnectionController.Scheduler { + override fun after(delayMs: Long, action: () -> Unit) = EversenseConnectionController.Task { } + }, { 0L }, object : EversenseConnectionController.Transport { + override fun open(session: Long) = true + override fun reuse(session: Long) = true + override fun close() {} + } + ) + private val callback: EversenseGattCallback + init { + controller.start() + whenever(plugin.sessionActive(1L)).thenReturn(true) + whenever(plugin.deliver(eq(1L), any())).thenAnswer { it.getArgument<() -> Unit>(1).invoke() } + callback = EversenseGattCallback(plugin, SessionStore(controller, 1, delegate), 1) + callback.attachGatt(gatt) + EversenseGattCallback::class.java.getDeclaredField("requestCharacteristic").apply { + isAccessible = true + set(callback, characteristic) + } + } + @AfterEach fun close() { callback.closeSession() } + + @Test fun synchronousBleResponseBeforeWriteReturnsIsRetained() { + val packet = GetSignalStrengthRawPacket() + whenever(gatt.writeCharacteristic(characteristic)).thenAnswer { + callback.onCharacteristicChanged(gatt, characteristic, + byteArrayOf(packet.spec.responseId, 0, 0, 0, 0x87.toByte(), 3)) + true + } + val response = callback.writePacket(packet, 100) + assertEquals(903, response.rawValue) + assertEquals(80, response.signalStrength) + } + @Test fun timeoutInvalidatesLinkRatherThanAllowingResponseToReachNextCommand() { + whenever(gatt.writeCharacteristic(characteristic)).thenReturn(true) + assertThrows(EversenseWriteException::class.java) { + callback.writePacket(GetSignalStrengthRawPacket(), 1) + } + verify(plugin).sessionDisconnected(1, -1, false) + } + @Test fun rejected365CommandDoesNotInvalidateAuthenticatedLink() { + val crypto: app.aaps.plugins.eversense.util.EversenseCrypto365Util = mock() + whenever(crypto.encrypt(any())).thenReturn(byteArrayOf(3, 14)) + whenever(crypto.decrypt(any())).thenReturn(byteArrayOf(0xff.toByte(), 0x0e, 5)) + EversenseGattCallback::class.java.getDeclaredField("cryptoUtil").apply { isAccessible = true; set(callback, crypto) } + EversenseGattCallback::class.java.getDeclaredField("security").apply { + isAccessible = true + set(callback, app.aaps.plugins.eversense.enums.EversenseSecurityType.SecureV2) + } + whenever(gatt.writeCharacteristic(characteristic)).thenAnswer { + callback.onCharacteristicChanged(gatt, characteristic, byteArrayOf(1, 1, 1, 0x42, 1)) + true + } + val error = assertThrows(EversenseWriteException::class.java) { + callback.writePacket( + app.aaps.plugins.eversense.packets.e365.SetAppVersion365Packet(), 100) + } + assertEquals("Transmitter rejected the packet", error.message) + verify(plugin, never()).sessionDisconnected(any(), any(), any()) + } + + @Test fun closedSessionCannotSendAnotherPacket() { + callback.closeSession() + assertThrows(EversenseWriteException::class.java) { + callback.writePacket(GetSignalStrengthRawPacket(), 1) + } + verify(gatt, never()).writeCharacteristic(any()) + } + @Test fun rejectedBleWriteDoesNotWaitForResponse() { + whenever(gatt.writeCharacteristic(characteristic)).thenReturn(false) + assertThrows(EversenseWriteException::class.java) { + callback.writePacket(GetSignalStrengthRawPacket(), 100) + } + verify(plugin, never()).sessionDisconnected(any(), any(), any()) + } + @Test fun queuedWorkFromInterrupted365LinkIsRejectedAfterGattReuse() { + val device: android.bluetooth.BluetoothDevice = mock() + whenever(gatt.device).thenReturn(device) + whenever(device.name).thenReturn("T123") + whenever(gatt.connect()).thenReturn(true) + EversenseGattCallback::class.java.getDeclaredField("security").apply { + isAccessible = true + set(callback, app.aaps.plugins.eversense.enums.EversenseSecurityType.SecureV2) + } + val entered = java.util.concurrent.CountDownLatch(1) + val release = java.util.concurrent.CountDownLatch(1) + val first = callback.submitToExecutor { + entered.countDown() + release.await(5, java.util.concurrent.TimeUnit.SECONDS) + } + try { + assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS)) + val old = callback.submitToExecutor { fail("Stale work must not run") } + callback.onConnectionStateChange(gatt, 19, android.bluetooth.BluetoothProfile.STATE_DISCONNECTED) + assertTrue(callback.reuse()) + release.countDown() + first.get(5, java.util.concurrent.TimeUnit.SECONDS) + assertThrows(java.util.concurrent.ExecutionException::class.java) { + old.get(5, java.util.concurrent.TimeUnit.SECONDS) + } + assertEquals(42, callback.submitToExecutor { 42 }.get(5, java.util.concurrent.TimeUnit.SECONDS)) + } finally { release.countDown() } + } + + @Test fun commandsRequiringReadyTransmitterCannotRunDuringAuthentication() { + val future = callback.submitToExecutor(readyOnly = true) { fail("Not authenticated") } + assertThrows(java.util.concurrent.ExecutionException::class.java) { + future.get(5, java.util.concurrent.TimeUnit.SECONDS) + } + } + @Test fun stoppingCancelsQueuedFuturesAndRejectsNewWorkWithoutThrowingOnCaller() { + val entered = java.util.concurrent.CountDownLatch(1) + val release = java.util.concurrent.CountDownLatch(1) + callback.submitToExecutor { + entered.countDown() + release.await(5, java.util.concurrent.TimeUnit.SECONDS) + } + try { + assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS)) + val queued = callback.submitToExecutor { fail("Stopped work must not run") } + callback.closeSession() + assertTrue(queued.isCancelled) + val rejected = callback.submitToExecutor { 42 } + assertThrows(java.util.concurrent.ExecutionException::class.java) { + rejected.get(5, java.util.concurrent.TimeUnit.SECONDS) + } + } finally { release.countDown() } + } + + @Test fun closingSessionReleasesAnInFlightPacketWaitImmediately() { + val sent = java.util.concurrent.CountDownLatch(1) + whenever(gatt.writeCharacteristic(characteristic)).thenAnswer { sent.countDown(); true } + val worker = java.util.concurrent.Executors.newSingleThreadExecutor() + try { + val result = worker.submit { + callback.writePacket(GetSignalStrengthRawPacket(), 60_000) + } + assertTrue(sent.await(5, java.util.concurrent.TimeUnit.SECONDS)) + callback.closeSession() + val error = assertThrows(java.util.concurrent.ExecutionException::class.java) { + result.get(5, java.util.concurrent.TimeUnit.SECONDS) + } + assertTrue(error.cause is EversenseWriteException) + } finally { worker.shutdownNow() } + } + + @Test fun registered365IdentityUsesBluetoothAuthStartWithoutInternet() { + val crypto: app.aaps.plugins.eversense.util.EversenseCrypto365Util = mock() + whenever(crypto.canUseShortcut()).thenReturn(true) + whenever(crypto.generateKeyPairIfNotExists()).thenReturn(true) + whenever(crypto.generateEphem()).thenReturn(byteArrayOf(1)) + whenever(crypto.getStartSecret(any())).thenReturn(byteArrayOf(1)) + doThrow(IllegalStateException("Authentication reached session-key derivation")) + .whenever(crypto).generateSessionKey(any()) + EversenseGattCallback::class.java.getDeclaredField("cryptoUtil").apply { isAccessible = true; set(callback, crypto) } + EversenseGattCallback::class.java.getDeclaredField("security").apply { + isAccessible = true + set(callback, app.aaps.plugins.eversense.enums.EversenseSecurityType.SecureV2) + } + whenever(gatt.writeCharacteristic(characteristic)).thenAnswer { + val packets = app.aaps.plugins.eversense.packets.e365.Eversense365Packets + callback.onCharacteristicChanged(gatt, characteristic, + byteArrayOf(1, 1, 1, packets.AuthenticateResponseId, packets.AuthenticateStart) + ByteArray(64)) + true + } + EversenseGattCallback::class.java.getDeclaredMethod("authV2flow").apply { isAccessible = true }.invoke(callback) + verify(crypto).generateSessionKey(any()) + verify(plugin, never()).hasInternet() + verify(gatt).writeCharacteristic(characteristic) + } + @Test fun missing365RegistrationOfflineDoesNotAttemptHttpOrBluetoothWhoAmI() { + val crypto: app.aaps.plugins.eversense.util.EversenseCrypto365Util = mock() + whenever(crypto.canUseShortcut()).thenReturn(false) + whenever(crypto.generateKeyPairIfNotExists()).thenReturn(true) + whenever(plugin.hasInternet()).thenReturn(false) + EversenseGattCallback::class.java.getDeclaredField("cryptoUtil").apply { isAccessible = true; set(callback, crypto) } + EversenseGattCallback::class.java.getDeclaredMethod("authV2flow").apply { isAccessible = true }.invoke(callback) + verify(plugin).sessionDisconnected(1, BluetoothGatt.GATT_SUCCESS, false) + verify(gatt, never()).writeCharacteristic(any()) + } + + @Test fun offlineDecryptFailureRetainsRegisteredIdentityForLocalReconnect() { + val crypto: app.aaps.plugins.eversense.util.EversenseCrypto365Util = mock() + whenever(crypto.decrypt(any())).thenReturn(byteArrayOf()) + whenever(plugin.hasInternet()).thenReturn(false) + EversenseGattCallback::class.java.getDeclaredField("cryptoUtil").apply { isAccessible = true; set(callback, crypto) } + EversenseGattCallback::class.java.getDeclaredField("security").apply { + isAccessible = true + set(callback, app.aaps.plugins.eversense.enums.EversenseSecurityType.SecureV2) + } + callback.onCharacteristicChanged(gatt, characteristic, byteArrayOf(1, 1, 1, 0x42, 1)) + verify(crypto).decrypt(any()) + verify(crypto, never()).disallowUseShortcut() + verify(plugin).sessionDisconnected(1, BluetoothGatt.GATT_SUCCESS, false) + } + +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/EversenseConnectionControllerTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/EversenseConnectionControllerTest.kt new file mode 100644 index 000000000000..6b8e30d165bf --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/EversenseConnectionControllerTest.kt @@ -0,0 +1,154 @@ +package app.aaps.plugins.eversense.connection + +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test + +class EversenseConnectionControllerTest { + private class Clock : EversenseConnectionController.Scheduler { + data class Entry(val at: Long, val action: () -> Unit, var cancelled: Boolean = false) + var now = 0L + val queue = mutableListOf() + override fun after(delayMs: Long, action: () -> Unit): EversenseConnectionController.Task { + val entry = Entry(now + delayMs, action) + queue.add(entry) + return EversenseConnectionController.Task { entry.cancelled = true } + } + fun advance(ms: Long) { + val end = now + ms + while (true) { + val next = queue.filter { !it.cancelled && it.at <= end }.minByOrNull { it.at } ?: break + queue.remove(next) + now = next.at + next.action() + } + now = end + } + fun pending() = queue.count { !it.cancelled } + } + private class Link : EversenseConnectionController.Transport { + val opened = mutableListOf() + var reused = 0 + var closed = 0 + var accepted = true + override fun open(session: Long): Boolean { opened.add(session); return accepted } + override fun reuse(session: Long): Boolean { reused++; return accepted } + override fun close() { closed++ } + } + private val clock = Clock() + private val link = Link() + private val controller = EversenseConnectionController(clock, { clock.now }, link) + private fun token() = link.opened.last() + + @Test fun stopCancelsAllTimersAndIgnoresLateCallbacksAndBluetooth() { + controller.start() + val old = token() + val lateDeadline = clock.queue.last().action + controller.stop() + controller.ready(old) + controller.disconnected(old, 19, true) + controller.bluetoothAvailable() + lateDeadline() + clock.advance(1_000_000) + assertEquals(EversenseConnectionController.State.STOPPED, controller.state) + assertEquals(1, link.opened.size) + assertEquals(0, clock.pending()) + assertFalse(controller.connect()) + } + @Test fun manualDisconnectRemainsPausedUntilExplicitConnect() { + controller.start() + controller.disconnect() + controller.bluetoothAvailable() + clock.advance(1_000_000) + assertEquals(1, link.opened.size) + assertEquals(EversenseConnectionController.State.PAUSED, controller.state) + assertTrue(controller.connect()) + assertEquals(2, link.opened.size) + } + @Test fun duplicateDisconnectsCreateOneRetryAndOldSessionCannotAffectNewOne() { + controller.start() + val old = token() + controller.disconnected(old, 133) + controller.disconnected(old, 133) + assertEquals(1, clock.pending()) + clock.advance(4_999) + assertEquals(1, link.opened.size) + clock.advance(1) + assertEquals(2, link.opened.size) + controller.ready(old) + controller.disconnected(old, 133) + assertEquals(EversenseConnectionController.State.CONNECTING, controller.state) + assertEquals(1, clock.pending()) + } + @Test fun repeatedFailuresBackOffAndSuccessfulAuthenticationResetsBackoff() { + controller.start() + for (delay in listOf(5_000L, 10_000L, 20_000L, 40_000L, 60_000L, 60_000L)) { + controller.disconnected(token(), 133) + val before = link.opened.size + clock.advance(delay - 1) + assertEquals(before, link.opened.size) + clock.advance(1) + assertEquals(before + 1, link.opened.size) + } + controller.ready(token()) + controller.disconnected(token(), 133) + val before = link.opened.size + clock.advance(5_000) + assertEquals(before + 1, link.opened.size) + } + @Test fun normal365DisconnectionReusesGattInsteadOfOpeningAnotherClient() { + controller.start() + controller.ready(token()) + val closed = link.closed + controller.disconnected(token(), 19, reuse = true) + clock.advance(5_000) + assertEquals(1, link.reused) + assertEquals(1, link.opened.size) + assertEquals(closed, link.closed) + controller.ready(token()) + assertEquals(EversenseConnectionController.State.READY, controller.state) + } + @Test fun e3Status19WaitsThirtySeconds() { + controller.start() + controller.disconnected(token(), 19) + clock.advance(29_999) + assertEquals(1, link.opened.size) + clock.advance(1) + assertEquals(2, link.opened.size) + } + @Test fun stalledAttemptTimesOutAndDoesNotRemainConnectingForever() { + controller.start() + controller.connect() + assertEquals(1, link.opened.size) + clock.advance(180_000) + assertEquals(EversenseConnectionController.State.DISCONNECTED, controller.state) + clock.advance(5_000) + assertEquals(2, link.opened.size) + } + @Test fun watchdogReplacesOnlyReadyConnectionsWithoutRecentData() { + controller.start() + controller.ready(token()) + clock.advance(6 * 60_000) + controller.dataReceived(token()) + clock.advance(7 * 60_000) + assertEquals(1, link.opened.size) + clock.advance(60_000) + assertEquals(2, link.opened.size) + } + @Test fun rejectedConnectHasOneBoundedRetry() { + link.accepted = false + controller.start() + assertEquals(1, clock.pending()) + clock.advance(59_999) + assertEquals(1, link.opened.size) + clock.advance(1) + assertEquals(2, link.opened.size) + assertEquals(1, clock.pending()) + } + @Test fun startWithoutCredentialsDoesNotOpenBluetooth() { + controller.start(autoConnect = false) + controller.bluetoothAvailable() + clock.advance(1_000_000) + assertEquals(0, link.opened.size) + assertTrue(controller.connect()) + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/PacketExchangeTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/PacketExchangeTest.kt new file mode 100644 index 000000000000..ec7d267d2303 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/PacketExchangeTest.kt @@ -0,0 +1,33 @@ +package app.aaps.plugins.eversense.connection + +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import java.util.concurrent.ExecutionException +import java.util.concurrent.TimeoutException + +class PacketExchangeTest { + @Test fun responseBeforeWaitingIsNotLost() { + val packet = Any() + val exchange = PacketExchange(packet) + exchange.complete() + assertSame(packet, exchange.await(1)) + } + @Test fun missingResponseHasBoundedTimeout() { + assertThrows(TimeoutException::class.java) { PacketExchange(Any()).await(1) } + } + @Test fun teardownFailureUnblocksWaitAndLateResponseCannotOverwriteIt() { + val exchange = PacketExchange(Any()) + val cause = IllegalStateException("session closed") + exchange.fail(cause) + assertFalse(exchange.complete()) + val error = assertThrows(ExecutionException::class.java) { exchange.await(1) } + assertSame(cause, error.cause) + } + @Test fun oldResponseCannotCompleteAnotherExchange() { + val old = PacketExchange(Any()) + assertThrows(TimeoutException::class.java) { old.await(1) } + val next = PacketExchange(Any()) + old.complete() + assertThrows(TimeoutException::class.java) { next.await(1) } + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/SessionStoreTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/SessionStoreTest.kt new file mode 100644 index 000000000000..52c4656687ab --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/connection/SessionStoreTest.kt @@ -0,0 +1,81 @@ +package app.aaps.plugins.eversense.connection + +import app.aaps.plugins.eversense.storage.EversenseStore +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.mockito.kotlin.* +import java.util.concurrent.CancellationException + +class SessionStoreTest { + private val scheduled = mutableListOf<() -> Unit>() + private var token = 0L + private val transport = object : EversenseConnectionController.Transport { + override fun open(session: Long): Boolean { token = session; return true } + override fun reuse(session: Long) = true + override fun close() {} + } + private val controller = EversenseConnectionController( + object : EversenseConnectionController.Scheduler { + override fun after(delayMs: Long, action: () -> Unit): EversenseConnectionController.Task { + scheduled.add(action) + return EversenseConnectionController.Task { } + } + }, { 0L }, transport + ) + private val delegate: EversenseStore = mock() + private val editor: EversenseStore.Editor = mock() + private fun store(): SessionStore { + whenever(delegate.edit()).thenReturn(editor) + controller.start() + return SessionStore(controller, token, delegate) + } + @Test fun queuedEditorCannotRestoreCredentialsAfterStopEvenWithChainedCalls() { + val store = store() + val pending = store.edit().putString("username", "old").putString("access_token", "stale") + controller.stop() + assertThrows(CancellationException::class.java) { pending.apply() } + assertThrows(CancellationException::class.java) { pending.commit() } + verify(editor, never()).apply() + verify(editor, never()).commit() + } + @Test fun oldStoreCannotReadOrWriteAfterReconnect() { + val old = store() + controller.connect(force = true) + assertThrows(CancellationException::class.java) { old.getString("token", null) } + assertThrows(CancellationException::class.java) { old.edit() } + } + @Test fun currentSessionCanCommit() { + val current = store() + whenever(editor.commit()).thenReturn(true) + assertTrue(current.edit().putLong("counter", 2).commit()) + verify(editor).putLong("counter", 2) + verify(editor).commit() + } + @Test fun interrupted365LinkCannotPublishAfterSameGattIsReused() { + val current = store() + var generation = 1 + val httpStore = current.restrict { generation == 1 } + val pending = httpStore.edit().putString("access_token", "old") + controller.disconnected(token, 19, true) + generation++ + scheduled.last().invoke() + assertTrue(controller.active(token)) + assertThrows(CancellationException::class.java) { pending.apply() } + verify(editor, never()).apply() + } + @Test fun cloudStoreSurvivesBleDisconnectAndFreshGattButNotSignOutOrStop() { + store() + val cloud = controller.cloudStore(delegate)!! + controller.disconnected(token, 133) + cloud.edit().putString("token", "valid").apply() + controller.connect(force = true) + cloud.edit().putString("token", "still valid").apply() + controller.disconnect() + assertThrows(CancellationException::class.java) { cloud.edit() } + controller.connect() + val next = controller.cloudStore(delegate)!! + controller.stop() + assertThrows(CancellationException::class.java) { next.edit() } + } + +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e3/CalibrationPacketTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e3/CalibrationPacketTest.kt new file mode 100644 index 000000000000..86e2e1a5bd22 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e3/CalibrationPacketTest.kt @@ -0,0 +1,181 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.enums.CalibrationPhase +import app.aaps.plugins.eversense.enums.CalibrationReadiness +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test + +class GetCalibrationPhasePacketTest { + + private fun makePacket(vararg bytes: Int): GetCalibrationPhasePacket { + val packet = GetCalibrationPhasePacket() + packet.appendData(bytes.map { it.toUByte() }.toUByteArray()) + return packet + } + + @Test + fun `empty receivedData returns null`() { + val packet = GetCalibrationPhasePacket() + assertNull(packet.parseResponse()) + } + + @Test + fun `value 1 parses to WARMING_UP`() { + val packet = makePacket(0, 0, 0, 0, 1) + assertEquals(CalibrationPhase.WARMING_UP, packet.parseResponse()?.phase) + } + + @Test + fun `value 2 parses to INITIALIZATION`() { + val packet = makePacket(0, 0, 0, 0, 2) + assertEquals(CalibrationPhase.INITIALIZATION, packet.parseResponse()?.phase) + } + + @Test + fun `value 3 parses to DAILY_CALIBRATION`() { + val packet = makePacket(0, 0, 0, 0, 3) + assertEquals(CalibrationPhase.DAILY_CALIBRATION, packet.parseResponse()?.phase) + } + + @Test + fun `value 4 parses to SUSPICIOUS`() { + val packet = makePacket(0, 0, 0, 0, 4) + assertEquals(CalibrationPhase.SUSPICIOUS, packet.parseResponse()?.phase) + } + + @Test + fun `value 5 parses to DROPOUT`() { + val packet = makePacket(0, 0, 0, 0, 5) + assertEquals(CalibrationPhase.DROPOUT, packet.parseResponse()?.phase) + } + + @Test + fun `value 6 parses to DEBUG`() { + val packet = makePacket(0, 0, 0, 0, 6) + assertEquals(CalibrationPhase.DEBUG, packet.parseResponse()?.phase) + } + + @Test + fun `value 7 parses to UNKNOWN`() { + val packet = makePacket(0, 0, 0, 0, 7) + assertEquals(CalibrationPhase.UNKNOWN, packet.parseResponse()?.phase) + } + + @Test + fun `unknown value falls back to UNKNOWN`() { + val packet = makePacket(0, 0, 0, 0, 99) + assertEquals(CalibrationPhase.UNKNOWN, packet.parseResponse()?.phase) + } + + @Test + fun `annotation uses SingleByte command id`() { + val annotation = GetCalibrationPhasePacket().spec + assertEquals(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, annotation.requestId) + } + + @Test + fun `annotation uses SingleByte response id`() { + val annotation = GetCalibrationPhasePacket().spec + assertEquals(EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId, annotation.responseId) + } +} + +class GetCalibrationReadinessPacketTest { + + private fun makePacket(vararg bytes: Int): GetCalibrationReadinessPacket { + val packet = GetCalibrationReadinessPacket() + packet.appendData(bytes.map { it.toUByte() }.toUByteArray()) + return packet + } + + @Test + fun `empty receivedData returns null`() { + val packet = GetCalibrationReadinessPacket() + assertNull(packet.parseResponse()) + } + + @Test + fun `value 0 parses to READY`() { + val packet = makePacket(0, 0, 0, 0, 0) + assertEquals(CalibrationReadiness.READY, packet.parseResponse()?.readiness) + } + + @Test + fun `value 1 parses to NOT_ENOUGH_DATA`() { + val packet = makePacket(0, 0, 0, 0, 1) + assertEquals(CalibrationReadiness.NOT_ENOUGH_DATA, packet.parseResponse()?.readiness) + } + + @Test + fun `value 2 parses to GLUCOSE_RATE_TOO_HIGH`() { + val packet = makePacket(0, 0, 0, 0, 2) + assertEquals(CalibrationReadiness.GLUCOSE_RATE_TOO_HIGH, packet.parseResponse()?.readiness) + } + + @Test + fun `value 3 parses to TOO_SOON`() { + val packet = makePacket(0, 0, 0, 0, 3) + assertEquals(CalibrationReadiness.TOO_SOON, packet.parseResponse()?.readiness) + } + + @Test + fun `value 4 parses to DROPOUT_PHASE`() { + val packet = makePacket(0, 0, 0, 0, 4) + assertEquals(CalibrationReadiness.DROPOUT_PHASE, packet.parseResponse()?.readiness) + } + + @Test + fun `value 5 parses to SENSOR_EOL`() { + val packet = makePacket(0, 0, 0, 0, 5) + assertEquals(CalibrationReadiness.SENSOR_EOL, packet.parseResponse()?.readiness) + } + + @Test + fun `value 6 parses to NO_SENSOR_LINKED`() { + val packet = makePacket(0, 0, 0, 0, 6) + assertEquals(CalibrationReadiness.NO_SENSOR_LINKED, packet.parseResponse()?.readiness) + } + + @Test + fun `value 7 parses to UNSUPPORTED_MODE`() { + val packet = makePacket(0, 0, 0, 0, 7) + assertEquals(CalibrationReadiness.UNSUPPORTED_MODE, packet.parseResponse()?.readiness) + } + + @Test + fun `value 8 parses to WAITING_POST_CALIBRATION`() { + val packet = makePacket(0, 0, 0, 0, 8) + assertEquals(CalibrationReadiness.WAITING_POST_CALIBRATION, packet.parseResponse()?.readiness) + } + + @Test + fun `value 9 parses to LED_DISCONNECT_DETECTED`() { + val packet = makePacket(0, 0, 0, 0, 9) + assertEquals(CalibrationReadiness.LED_DISCONNECT_DETECTED, packet.parseResponse()?.readiness) + } + + @Test + fun `value 10 parses to TRANSMITTER_EOL`() { + val packet = makePacket(0, 0, 0, 0, 10) + assertEquals(CalibrationReadiness.TRANSMITTER_EOL, packet.parseResponse()?.readiness) + } + + @Test + fun `unknown value falls back to REASON_UNKNOWN`() { + val packet = makePacket(0, 0, 0, 0, 99) + assertEquals(CalibrationReadiness.REASON_UNKNOWN, packet.parseResponse()?.readiness) + } + + @Test + fun `annotation uses SingleByte command id`() { + val annotation = GetCalibrationReadinessPacket().spec + assertEquals(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, annotation.requestId) + } + + @Test + fun `annotation uses SingleByte response id`() { + val annotation = GetCalibrationReadinessPacket().spec + assertEquals(EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId, annotation.responseId) + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e3/SetBloodGlucosePointPacketTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e3/SetBloodGlucosePointPacketTest.kt new file mode 100644 index 000000000000..c4d748b4c2f2 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e3/SetBloodGlucosePointPacketTest.kt @@ -0,0 +1,46 @@ +package app.aaps.plugins.eversense.packets.e3 + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Assertions.assertEquals +import java.util.Calendar +import java.util.TimeZone + +/** + * Byte-parity test for the E3 two-timestamp calibration packet against the iOS reference + * (loopandlearn/EversenseKit commit b79d858). + * + * Lets an E3 user confirm the encoding matches iOS BEFORE connecting to a transmitter. + * It does NOT prove the calibration works on hardware - only that the bytes match the + * reference implementation. On-device validation is still required. + */ +class SetBloodGlucosePointPacketTest { + + private fun gmtMillis(y: Int, mo: Int, d: Int, h: Int, mi: Int, s: Int): Long { + val cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")) + cal.clear() + cal.set(y, mo - 1, d, h, mi, s) + return cal.timeInMillis + } + + private fun ByteArray.hex(): String = joinToString("") { "%02x".format(it) } + + @Test + fun `getRequestData encodes two-timestamp calibration body matching iOS reference`() { + val sample = gmtMillis(2026, 6, 25, 14, 30, 0) + val packet = SetBloodGlucosePointPacket(glucoseInMgDl = 120, sampleTimestamp = sample) + val body = packet.getRequestData() + + assertEquals(14, body.size, "body must be 14 bytes") + assertEquals("d934c073", body.copyOfRange(0, 4).hex(), "sample date+time bytes") + assertEquals("7800", body.copyOfRange(8, 10).hex(), "glucose 120 little-endian") + assertEquals("00000055", body.copyOfRange(10, 14).hex(), "padding + 0x55 trailer") + } + + @Test + fun `glucose is encoded little-endian for values over 255`() { + val sample = gmtMillis(2026, 6, 25, 14, 30, 0) + val packet = SetBloodGlucosePointPacket(glucoseInMgDl = 300, sampleTimestamp = sample) + val body = packet.getRequestData() + assertEquals("2c01", body.copyOfRange(8, 10).hex(), "glucose 300 little-endian") + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e365/PushAlarmWithDataPacketTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e365/PushAlarmWithDataPacketTest.kt new file mode 100644 index 000000000000..1f14ab714eef --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/packets/e365/PushAlarmWithDataPacketTest.kt @@ -0,0 +1,39 @@ +package app.aaps.plugins.eversense.packets.e365 + +import app.aaps.plugins.eversense.enums.EversenseAlarm +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Test + +class PushAlarmWithDataPacketTest { + + private fun makePacket(vararg bytes: Int): PushAlarmWithDataPacket { + val packet = PushAlarmWithDataPacket() + packet.appendData(bytes.map { it.toUByte() }.toUByteArray()) + return packet + } + + @Test + fun `data shorter than 12 bytes returns null`() { + val packet = makePacket(0x44, 0x03, 14, 0x00) + assertNull(packet.parseResponse()) + } + + @Test + fun `alarm code comes from byte index 2, not the reserved byte at index 3`() { + // [0]=0x44 header, [1]=0x03 type, [2]=14 (LOW_GLUCOSE, the real alarm code), + // [3]=reserved (nonzero on purpose - must NOT be read as the code; empirically confirmed + // constant/0 on real devices, but a nonzero value here proves this test doesn't pass by + // coincidence), [4..11]=datetime. This is the exact byte position mistake that briefly + // broke real alarm decoding (High Glucose etc. all showing as CRITICAL_FAULT) after an + // earlier fix swapped these two indices based on a doc comment that turned out to be wrong. + val packet = makePacket(0x44, 0x03, 14, 0x7F, 0, 0, 0, 0, 0, 0, 0, 0) + assertEquals(EversenseAlarm.LOW_GLUCOSE, packet.parseResponse()?.alarm?.code) + } + + @Test + fun `unrecognized alarm code falls back to UNKNOWN`() { + val packet = makePacket(0x44, 0x03, 254, 0x00, 0, 0, 0, 0, 0, 0, 0, 0) + assertEquals(EversenseAlarm.UNKNOWN, packet.parseResponse()?.alarm?.code) + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/BinaryCompatibilityTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/BinaryCompatibilityTest.kt new file mode 100644 index 000000000000..93655fd286f0 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/BinaryCompatibilityTest.kt @@ -0,0 +1,115 @@ +package app.aaps.plugins.eversense.protocol + +import app.aaps.plugins.eversense.enums.CalibrationFlag +import app.aaps.plugins.eversense.enums.EversenseAlarm +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Parser +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Writer +import app.aaps.plugins.eversense.packets.e365.CalibrationHistoryItem +import app.aaps.plugins.eversense.packets.e365.utils.toUnix +import app.aaps.plugins.eversense.packets.e365.utils.toUnixArray +import app.aaps.plugins.eversense.util.EversenseDmsBinaryCodec +import java.lang.reflect.Method +import java.time.Instant +import java.util.Random +import java.util.TimeZone +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class BinaryCompatibilityTest { + private val methods = mutableMapOf>() + private fun old(type: String, name: String, vararg args: Any): Any? { + val (target, method) = methods.getOrPut("$type/$name") { + val klass = Class.forName("app.aaps.plugins.eversense.reference.$type") + val target = klass.fields.firstOrNull { it.name == "Companion" || it.name == "INSTANCE" }?.get(null) + val owner = target?.javaClass ?: klass + target to owner.methods.single { it.name.substringBefore('-') == name && '$' !in it.name && it.parameterCount == args.size } + } + return method.invoke(target, *args) + } + private val parser = "packets.e3.util.EversenseE3Parser" + private val writer = "packets.e3.util.EversenseE3Writer" + private val dms = "util.EversenseDmsBinaryCodec" + private val extensions = "packets.e365.utils.ByteArrayUtilKt" + + @Test fun crcMatchesFrozenBitwiseEncoderAndIndependentCheckVector() { + assertArrayEquals(byteArrayOf(0xb1.toByte(), 0x29), WireEncoding.crc16("123456789".toByteArray())) + val random = Random(365) + val fixtures = (0..255).map { byteArrayOf(it.toByte()) } + + (0..512).map { ByteArray(it * 3).also(random::nextBytes) } + for (bytes in fixtures) assertArrayEquals(old(writer, "generateChecksumCRC16", bytes) as ByteArray, WireEncoding.crc16(bytes)) + } + + @Test fun everyPackedDateTimeAndTimezoneValueMatchesOriginalIncludingLenientOverflow() { + for (bits in 0..65535) { + val bytes = byteArrayOf(bits.toByte(), (bits ushr 8).toByte()) + assertEquals(old(parser, "readDate", bytes, 0), EversenseE3Parser.readDate(bytes.toUByteArray(), 0), "date $bits") + assertEquals(old(parser, "readTime", bytes, 0), EversenseE3Parser.readTime(bytes.toUByteArray(), 0), "time $bits") + for (sign in listOf(0, 1, 255)) { + val offset = bytes + byteArrayOf(sign.toByte()) + assertEquals(old(parser, "readTimezone", offset, 0), EversenseE3Parser.readTimezone(offset.toUByteArray(), 0), "offset $bits/$sign") + } + } + } + + @Test fun dateTimeAndSignedIntegerEncodingMatchAcrossLeapDaysAndTimezoneRules() { + val previous = TimeZone.getDefault() + try { + val timestamps = listOf("1900-01-01T00:00:00Z", "2000-02-29T23:59:59Z", "2024-02-29T01:02:03Z", "2025-01-01T00:00:00Z", "2025-07-01T23:59:59Z", "2127-12-31T23:59:59Z").map { Instant.parse(it).toEpochMilli() } + for (zone in TimeZone.getAvailableIDs()) { + TimeZone.setDefault(TimeZone.getTimeZone(zone)) + for (timestamp in timestamps) { + assertArrayEquals(old(writer, "writeDate", timestamp) as ByteArray, EversenseE3Writer.writeDate(timestamp)) + assertArrayEquals(old(writer, "writeTime", timestamp) as ByteArray, EversenseE3Writer.writeTime(timestamp)) + assertArrayEquals(old(writer, "writeTimezone", timestamp) as ByteArray, EversenseE3Writer.writeTimezone(timestamp), "$zone at $timestamp") + } + } + } finally { TimeZone.setDefault(previous) } + for (value in listOf(Int.MIN_VALUE, -65536, -1, 0, 1, 255, 256, 65535, Int.MAX_VALUE)) { + assertArrayEquals(old(writer, "writeInt16", value) as ByteArray, EversenseE3Writer.writeInt16(value)) + for (width in listOf(2, 3, 4)) { + val name = "int${width * 8}LE" + assertArrayEquals(old(dms, name, value) as ByteArray, BinaryFields.littleEndian(value.toLong(), width)) + } + } + for (value in listOf(Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, -3.14159, 0.0, 1.5)) { + assertArrayEquals(old(writer, "writeDouble", value) as ByteArray, EversenseE3Writer.writeDouble(value)) + } + } + + @Test fun sensorClockUsesIdenticalTruncationOverflowAndEpoch() { + for (value in listOf(Long.MIN_VALUE, -1L, 0L, 946_684_799_999L, 946_684_800_000L, 1_735_689_610_999L, Long.MAX_VALUE)) { + assertArrayEquals(old(extensions, "toUnixArray", value) as ByteArray, value.toUnixArray()) + } + val random = Random(191) + for (size in 0..16) repeat(100) { + val bytes = ByteArray(size).also(random::nextBytes) + assertEquals(old(extensions, "toUnix", bytes), bytes.toUByteArray().toUnix()) + } + } + + private fun legacyEnum(type: String, name: String): Any = Class.forName("app.aaps.plugins.eversense.reference.enums.$type").enumConstants!!.single { (it as Enum<*>).name == name } + private fun legacyReading(value: EversenseCGMResult): Any = Class.forName("app.aaps.plugins.eversense.reference.models.EversenseCGMResult") + .constructors.single { !it.isSynthetic && it.parameterCount == 5 }.newInstance(value.glucoseInMgDl, value.datetime, legacyEnum("EversenseTrendArrow", value.trend.name), value.sensorId, value.rawResponseHex) + + @Test fun dmsRecordsMatchByteForByteForSensorIdsReadingsCalibrationsAndEveryAlarm() { + val timestamp = 1_735_689_610_000L + for (sensor in listOf("", "0", "00112233445566778899", "abcdef")) { + val readings = listOf(0, 19, 20, 100, 449, 450, 65535).mapIndexed { index, glucose -> EversenseCGMResult(glucose, timestamp + index * 61_000L, EversenseTrendArrow.entries[index % EversenseTrendArrow.entries.size], sensor) } + assertEquals(old(dms, "buildSgBytes", readings.map(::legacyReading)), EversenseDmsBinaryCodec.buildSgBytes(readings)) + val alarms = EversenseAlarm.entries.map { ActiveAlarm(it, 0, 0, 0) } + val legacyAlarms = alarms.map { Class.forName("app.aaps.plugins.eversense.reference.models.ActiveAlarm").constructors.single { !it.isSynthetic && it.parameterCount == 4 }.newInstance(legacyEnum("EversenseAlarm", it.code.name), 0, 0, 0) } + assertEquals(old(dms, "buildAlertBytes", sensor, legacyAlarms, timestamp, 123), EversenseDmsBinaryCodec.buildAlertBytes(sensor, alarms, timestamp, 123)) + } + val calibrations = CalibrationFlag.entries.map { CalibrationHistoryItem(timestamp + it.ordinal * 60_000L, 80 + it.ordinal, it) } + val legacyCalibrations = calibrations.map { Class.forName("app.aaps.plugins.eversense.reference.packets.e365.CalibrationHistoryItem").constructors.single { !it.isSynthetic && it.parameterCount == 3 }.newInstance(it.datetime, it.glucoseInMgDl, legacyEnum("CalibrationFlag", it.flag.name)) } + assertEquals(old(dms, "buildMgBytes", legacyCalibrations), EversenseDmsBinaryCodec.buildMgBytes(calibrations)) + assertEquals(old(dms, "buildEmptyMgBytes"), EversenseDmsBinaryCodec.buildEmptyMgBytes()) + assertEquals(old(dms, "buildEmptyPatientBytes"), EversenseDmsBinaryCodec.buildEmptyPatientBytes()) + for (signal in -10..110) assertEquals(old(dms, "signalStrengthOrdinal", signal), EversenseDmsBinaryCodec.signalStrengthOrdinal(signal)) + for (trend in EversenseTrendArrow.entries) assertEquals(old(dms, "trendOrdinal", legacyEnum("EversenseTrendArrow", trend.name)), EversenseDmsBinaryCodec.trendOrdinal(trend)) + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/DmsHttpCompatibilityTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/DmsHttpCompatibilityTest.kt new file mode 100644 index 000000000000..a3ee4092eada --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/DmsHttpCompatibilityTest.kt @@ -0,0 +1,164 @@ +package app.aaps.plugins.eversense.protocol + +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import java.util.TimeZone +import java.util.concurrent.TimeUnit +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.DynamicTest +import org.junit.jupiter.api.TestFactory +import org.junit.jupiter.api.Test +import org.mockito.Answers +import org.mockito.Mockito + +/** Observe actual HTTP paths/headers/bodies, not just model-level mocks. No manufacturer endpoint is contacted. */ +class DmsHttpCompatibilityTest { + private val fixedTime = 1_735_689_610_000L + private val tokenJson = """{"access_token":"fresh-token","expires_in":3600,"token_type":"Bearer","expires":"2099-01-01T00:00:00Z","lastLogin":"2025-01-01T00:00:00Z"}""" + private val certificateJson = """{"Status":"Success","StatusCode":200,"Result":{"Certificate":"0102","IsKeyAvailable":true}}""" + + private class Gateway(val prefix: String, generation: String, val region: Boolean) { + val owner: Any = Class.forName("$prefix.util.EversenseHttp${generation}Util").getField("Companion").get(null) + val values = mutableMapOf( + "eversense_state_secure" to """{"username":"test+ä@example.test","password":"test&=password","isEuropeanRegion":$region}""", + "eversense_access_token" to "cached-token", "eversense_access_token_expiry" to Long.MAX_VALUE + ) + val store: Any + private val restore = mutableListOf<() -> Unit>() + init { + val editorType = Class.forName(prefix + ".storage.EversenseStore\$Editor") + val pending = mutableMapOf() + val editor = Mockito.mock(editorType) { call -> + when { + call.method.name.startsWith("put") -> { pending[call.getArgument(0)] = call.getArgument(1); call.mock } + call.method.name == "commit" -> { values.putAll(pending); true } + call.method.name == "apply" -> { values.putAll(pending); null } + else -> Answers.RETURNS_DEFAULTS.answer(call) + } + } + store = Mockito.mock(Class.forName("$prefix.storage.EversenseStore")) { call -> + when (call.method.name) { + "getString", "getLong", "getInt", "getBoolean" -> values[call.getArgument(0)] ?: call.getArgument(1) + "contains" -> values.containsKey(call.getArgument(0)) + "edit" -> editor + else -> Answers.RETURNS_DEFAULTS.answer(call) + } + } + } + fun route(server: MockWebServer, generation: String) { + val properties = if (generation == "E3") listOf("tokenBaseUrl", "careBaseUrl") else + listOf("tokenBaseUrl", "uploadBaseUrl", "careBaseUrl", "vaultBaseUrl", "euTokenBaseUrl", "euUploadBaseUrl", "euCareBaseUrl", "euVaultBaseUrl") + for (property in properties) { + val suffix = property.replaceFirstChar(Char::uppercase) + val getter = owner.javaClass.methods.single { it.name.startsWith("get$suffix") && it.parameterCount == 0 } + val setter = owner.javaClass.methods.single { it.name.startsWith("set$suffix") && it.parameterCount == 1 } + val previous = getter.invoke(owner) + restore.add { setter.invoke(owner, previous) } + val segment = if (generation == "E3") "ous" else if (property.startsWith("eu")) "eu" else "us" + setter.invoke(owner, server.url("/$segment/").toString()) + } + } + fun close() { restore.asReversed().forEach { it() } } + private fun trend(): Any = Class.forName("$prefix.enums.EversenseTrendArrow").enumConstants!!.single { (it as Enum<*>).name == "FLAT" } + private fun readings(): List = listOf(Class.forName("$prefix.models.EversenseCGMResult").constructors.single { !it.isSynthetic && it.parameterCount == 5 } + .newInstance(123, 1_735_689_610_000L, trend(), "00112233445566778899", "01020304")) + fun invoke(operation: String): Any? { + val args: Array = when (operation) { + "login", "getOrRefreshToken" -> arrayOf(store) + "putCurrentValues" -> arrayOf(store, 123, 1_735_689_610_000L, trend(), 55, 80) + "putDeviceEvents" -> arrayOf(store, readings(), "T123", emptyList(), emptyList()) + "uploadGlucoseReadings" -> arrayOf(store, readings(), "T123", "1.2.3") + "getFleetSecretV2" -> arrayOf(store, "test-token", byteArrayOf(1,2,3), byteArrayOf(4,5,6), true, ByteArray(91) { it.toByte() }) + else -> error(operation) + } + return owner.javaClass.methods.single { it.name == operation && it.parameterCount == args.size }.invoke(owner, *args) + } + } + + @TestFactory fun modelSpecificRequestsAndOutcomes(): List { + val tests = mutableListOf() + for (generation in listOf("E3", "365")) for (eu in listOf(false, true)) { + val operations = listOf("login", "putCurrentValues", "putDeviceEvents") + + if (generation == "365") listOf("uploadGlucoseReadings", "getFleetSecretV2") else emptyList() + for (operation in operations) for (status in listOf(200, 401, 500)) { + tests.add(DynamicTest.dynamicTest("$generation region=$eu $operation HTTP$status") { compare(generation, eu, operation, status) }) + } + tests.add(DynamicTest.dynamicTest("$generation region=$eu malformed login") { compare(generation, eu, "login", 200, malformed = true) }) + tests.add(DynamicTest.dynamicTest("$generation region=$eu token refresh") { compare(generation, eu, "getOrRefreshToken", 200, expired = true) }) + } + return tests + } + + @Test fun validCachedTokensNeedNoNetworkIncludingEmptyLegacyToken() { + MockWebServer().use { server -> + server.start() + for (generation in listOf("E3", "365")) for (eu in listOf(false, true)) { + val original = Gateway("app.aaps.plugins.eversense.reference", generation, eu) + val rewritten = Gateway("app.aaps.plugins.eversense", generation, eu) + try { + original.route(server, generation) + rewritten.route(server, generation) + repeat(2) { server.enqueue(MockResponse().setResponseCode(503)) } + for (token in listOf("offline-token", "")) { + for (gateway in listOf(original, rewritten)) { + gateway.values["eversense_access_token"] = token + gateway.values["eversense_access_token_expiry"] = fixedTime + 300_001L + } + PacketTime.withClock(Clock.fixed(Instant.ofEpochMilli(fixedTime), ZoneOffset.UTC)) { + assertEquals(token, original.invoke("getOrRefreshToken")) + assertEquals(token, rewritten.invoke("getOrRefreshToken")) + assertEquals(original.values, rewritten.values) + } + } + assertEquals(0, server.requestCount, "Cached tokens must not access the network") + } finally { + original.close() + rewritten.close() + } + } + } + } + + private fun compare(generation: String, eu: Boolean, operation: String, status: Int, malformed: Boolean = false, expired: Boolean = false) { + val server = MockWebServer() + server.start() + val original = Gateway("app.aaps.plugins.eversense.reference", generation, eu) + val rewritten = Gateway("app.aaps.plugins.eversense", generation, eu) + val oldZone = TimeZone.getDefault() + try { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")) + original.route(server, generation); rewritten.route(server, generation) + if (expired) { original.values.remove("eversense_access_token"); rewritten.values.remove("eversense_access_token") } + val body = when { + malformed -> "not-json" + status >= 400 -> "{\"error\":\"denied\"}" + operation in listOf("login", "getOrRefreshToken") -> tokenJson + operation == "getFleetSecretV2" -> certificateJson + else -> "{\"ok\":true}" + } + repeat(2) { server.enqueue(MockResponse().setResponseCode(status).setBody(body).addHeader("Content-Type", "application/json; charset=utf-8")) } + PacketTime.withClock(Clock.fixed(Instant.ofEpochMilli(fixedTime), ZoneOffset.UTC)) { + val expected = original.invoke(operation) + val actual = rewritten.invoke(operation) + assertEquals(expected?.toString(), actual?.toString(), "result") + assertEquals(original.values, rewritten.values, "credential/token store") + } + val expectedRequest = server.takeRequest(5, TimeUnit.SECONDS) + val actualRequest = server.takeRequest(5, TimeUnit.SECONDS) + assertNotNull(expectedRequest); assertNotNull(actualRequest) + assertEquals(expectedRequest!!.method, actualRequest!!.method) + assertEquals(expectedRequest.path, actualRequest.path) + assertEquals(expectedRequest.getHeader("Content-Type"), actualRequest.getHeader("Content-Type")) + assertEquals(expectedRequest.getHeader("Authorization"), actualRequest.getHeader("Authorization")) + assertEquals(expectedRequest.body.readUtf8(), actualRequest.body.readUtf8(), "HTTP payload") + } finally { + original.close(); rewritten.close() + TimeZone.setDefault(oldZone) + server.shutdown() + } + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/NotificationCompatibilityTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/NotificationCompatibilityTest.kt new file mode 100644 index 000000000000..0152ad9d600b --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/NotificationCompatibilityTest.kt @@ -0,0 +1,71 @@ +package app.aaps.plugins.eversense.protocol + +import java.lang.reflect.InvocationTargetException +import java.time.Clock +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset +import java.util.Random +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.DynamicTest +import org.junit.jupiter.api.TestFactory +import org.mockito.Mockito + +class NotificationCompatibilityTest { + private data class Event(val delay: Long, val bytes: ByteArray) + private class Timeline(var value: Long = 100) : Clock() { + override fun getZone(): ZoneId = ZoneOffset.UTC + override fun withZone(zone: ZoneId): Clock = this + override fun instant(): Instant = Instant.ofEpochMilli(value) + override fun millis(): Long = value + } + private fun event(vararg bytes: Int, delay: Long = 10) = Event(delay, bytes.map(Int::toByte).toByteArray()) + + @TestFactory fun notificationTraces(): List { + val traces = mutableListOf( + listOf(event(1, 1, 1, 10), event(1, 1, 1, 10, delay = 200), event(1, 1, 1, 10, delay = 1000)), + listOf(event(1, 3, 1, 10), event(2, 3, 20), event(2, 3, 20), event(3, 3, 30)), + listOf(event(1, 3, 1, 10), event(3, 3, 30), event(2, 3, 20), event(1, 1, 1, 40)), + listOf(event(1, 3, 1, 10), event(2, 4, 20), event(1, 1, 1, 40)), + listOf(event(1, 2, 1), event(), event(1), event(2, 2)), + listOf(event(1, 2), event(1, 1, 1), event(1, 0, 1, 42)), + listOf(event(1, 4, 1, 10), event(1, 2, 1, 20), event(2, 2, 30)) + ) + val random = Random(191365) + repeat(100) { + traces.add((0 until 40).map { + val bytes = ByteArray(random.nextInt(24)).also(random::nextBytes) + if (bytes.isNotEmpty()) bytes[0] = random.nextInt(8).toByte() + if (bytes.size > 1) bytes[1] = random.nextInt(7).toByte() + Event(listOf(0L, 10L, 999L, 1000L, 1001L)[random.nextInt(5)], bytes) + }) + } + return traces.mapIndexed { index, trace -> DynamicTest.dynamicTest("trace $index") { + val type = Class.forName("app.aaps.plugins.eversense.reference.EversenseGattCallback") + val constructor = type.constructors.single() + val store = Mockito.mock(constructor.parameterTypes[1]) { invocation -> + if (invocation.method.name == "restrict") invocation.mock else org.mockito.Answers.RETURNS_DEFAULTS.answer(invocation) + } + val reference = constructor.newInstance(Mockito.mock(constructor.parameterTypes[0]), store, 1L) + val append = type.getDeclaredMethod("accumulateChunk", ByteArray::class.java).apply { isAccessible = true } + val clock = Timeline() + val rewritten = NotificationAssembler(clock::millis) + try { + PacketTime.withClock(clock) { + trace.forEachIndexed { eventIndex, event -> + clock.value += event.delay + val expected = outcome { append.invoke(reference, event.bytes) as? ByteArray } + val actual = outcome { rewritten.accept(event.bytes) } + assertEquals(expected, actual, "trace $index event $eventIndex") + } + } + } finally { type.getMethod("closeSession").invoke(reference) } + } } + } + private fun outcome(action: () -> ByteArray?): String = try { + action()?.joinToString(",") ?: "incomplete" + } catch (e: Exception) { + val cause = if (e is InvocationTargetException) e.targetException else e + "exception:${cause.javaClass.simpleName}" + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/ProtocolCompatibilityTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/ProtocolCompatibilityTest.kt new file mode 100644 index 000000000000..3f54df5331a1 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/ProtocolCompatibilityTest.kt @@ -0,0 +1,162 @@ +package app.aaps.plugins.eversense.protocol + +import java.lang.reflect.InvocationTargetException +import java.lang.reflect.Modifier +import java.time.Clock +import java.time.Instant +import java.time.ZoneOffset +import java.util.Random +import java.util.TimeZone +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.DynamicTest +import org.junit.jupiter.api.TestFactory +import org.mockito.Mockito +import org.mockito.Answers + +/** The oracle is compiled from an immutable source snapshot, never from rewritten packet code. */ +class ProtocolCompatibilityTest { + private val instant = 1_735_689_610_000L + private val clock = Clock.fixed(Instant.ofEpochMilli(instant), ZoneOffset.UTC) + private val names = javaClass.getResourceAsStream("/protocol-command-classes.txt")!!.bufferedReader().readLines() + + @TestFactory fun allCommandContracts(): List = names.map { name -> + DynamicTest.dynamicTest(name.substringAfter(".packets.")) { + val previous = TimeZone.getDefault() + try { + for (zone in listOf("UTC", "Europe/Berlin", "America/New_York", "Asia/Kolkata")) { + TimeZone.setDefault(TimeZone.getTimeZone(zone)) + PacketTime.withClock(clock) { compare(name) } + } + } finally { TimeZone.setDefault(previous) } + } + } + + private fun compare(name: String) { + val oldName = name.replace("app.aaps.plugins.eversense", "app.aaps.plugins.eversense.reference") + val current = Class.forName(name) + val reference = Class.forName(oldName) + for (variant in 0..2) { + val original = create(reference, variant) + val rewritten = create(current, variant) + assertEquals(metadata(original), metadata(rewritten), "$name descriptor") + assertEquals(result { invoke(original, "getRequestData") }, result { invoke(rewritten, "getRequestData") }, "$name payload variant=$variant") + for (mtu in listOf(5, 20, 185, 512)) { + for (emptyCiphertext in listOf(false, true)) { + assertEquals(request(original, mtu, emptyCiphertext), request(rewritten, mtu, emptyCiphertext), "$name framed request variant=$variant mtu=$mtu emptyCiphertext=$emptyCiphertext") + } + } + for ((index, response) in responses(original).withIndex()) { + val old = create(reference, variant) + val new = create(current, variant) + assertEquals(decode(old, response, index % 3), decode(new, response, index % 3), "$name response case=$index variant=$variant size=${response.size}") + } + } + } + + private fun create(type: Class<*>, variant: Int): Any { + val ctor = type.constructors.filterNot { it.isSynthetic }.maxBy { it.parameterCount } + val args = ctor.parameterTypes.mapIndexed { index, param -> + when { + param == Int::class.javaPrimitiveType -> listOf(10 + index, 0, 255)[variant] + param == Long::class.javaPrimitiveType -> instant - 120_000 + param == Boolean::class.javaPrimitiveType -> variant != 1 + param == Double::class.javaPrimitiveType -> listOf(1.5, 0.0, -1.5)[variant] + param == Float::class.javaPrimitiveType -> listOf(1.5f, 0f, -1.5f)[variant] + param == Byte::class.javaPrimitiveType -> listOf(1, 0, 255)[variant].toByte() + param == String::class.java -> listOf("8.0.4", "", "ABC123")[variant] + param == ByteArray::class.java -> ByteArray(listOf(32, 0, 80)[variant]) { it.toByte() } + param.isEnum -> param.enumConstants[variant % param.enumConstants.size] + else -> error("No constructor fixture for ${type.name}: ${param.name}") + } + }.toTypedArray() + return ctor.newInstance(*args) + } + + private fun metadata(packet: Any): List { + val value = packet.javaClass.methods.firstOrNull { it.name == "getSpec" }?.invoke(packet) + ?: invoke(packet, "getAnnotation")!! + return listOf("requestId", "responseId", "typeId", "securityType").map { key -> + val getter = value.javaClass.methods.first { it.name == key || it.name == "get" + key.replaceFirstChar(Char::uppercase) } + normalize(getter.invoke(value)) + } + } + + private fun request(packet: Any, mtu: Int, emptyCiphertext: Boolean): Any? = result { + val method = packet.javaClass.methods.single { it.name == "buildRequest" } + val crypto = Mockito.mock(method.parameterTypes[0]) { invocation -> + if (invocation.method.name == "encrypt") { + if (emptyCiphertext) byteArrayOf() else byteArrayOf(0x7e) + invocation.getArgument(0).map { (it.toInt() xor 0x55).toByte() }.toByteArray() + } else Answers.RETURNS_DEFAULTS.answer(invocation) + } + method.invoke(packet, crypto, mtu) + } + + private fun responses(packet: Any): List { + val random = Random(191) + val all = mutableListOf() + for (size in listOf(0, 1, 2, 3, 4, 7, 11, 14, 20, 32, 64, 128, 192, 256, 512)) { + all.add(ByteArray(size)) + all.add(ByteArray(size) { 0x55 }) + all.add(ByteArray(size).also(random::nextBytes)) + } + // Populate the body independently of parser implementations, including history-log headers. + for (kind in listOf(0, 6, 13)) { + all.add(ByteArray(512).also { it[6] = kind.toByte() }) + } + if (packet.javaClass.simpleName in setOf("GetCurrentGlucosePacket", "GetGlucoseDataPacket")) { + for (glucose in listOf(0, 19, 20, 100, 449, 450, 451, 65535)) { + for (trend in listOf(0, 1, 2, 4, 8, 16, 32, 64, 255)) { + val frame = ByteArray(192) + if (packet.javaClass.simpleName == "GetCurrentGlucosePacket") { + frame[0] = 0x88.toByte() + frame[4] = 0x21; frame[5] = 0x32 // 2025-01-01 UTC + frame[6] = 5 // 00:00:10 UTC + frame[9] = glucose.toByte(); frame[10] = (glucose ushr 8).toByte() + frame[13] = trend.toByte() + } else { + frame[0] = 0x42; frame[1] = 0x1f; frame[11] = 10 + java.nio.ByteBuffer.wrap(frame, 22, 8).order(java.nio.ByteOrder.LITTLE_ENDIAN) + .putLong((instant - 946_684_800_000L) / 1000 * 1024) + frame[30] = glucose.toByte(); frame[31] = (glucose ushr 8).toByte() + frame[32] = 55; frame[174] = trend.toByte() + } + all.add(frame) + } + } + } + return all + } + + private fun decode(packet: Any, bytes: ByteArray, split: Int): Any? = result { + val append = packet.javaClass.methods.single { it.name.startsWith("appendData") } + if (split == 0) append.invoke(packet, bytes) + else { + val boundary = bytes.size / (split + 1) + append.invoke(packet, bytes.copyOfRange(0, boundary)) + append.invoke(packet, bytes.copyOfRange(boundary, bytes.size)) + } + invoke(packet, "parseResponse") + } + + private fun invoke(target: Any, method: String): Any? = target.javaClass.methods.single { it.name == method && it.parameterCount == 0 }.invoke(target) + private fun result(action: () -> Any?): Any? = try { listOf("value", normalize(action())) } catch (e: Exception) { + var cause: Throwable = e + while (cause is InvocationTargetException) cause = cause.targetException + // Preserve malformed-input outcome categories without coupling to implementation-specific messages. + listOf("exception", when (cause) { + is IndexOutOfBoundsException -> "bounds" + else -> cause.javaClass.simpleName + }) + } + private fun normalize(value: Any?): Any? = when (value) { + null, is String, is Boolean -> value + is Number -> value.toString() + is Enum<*> -> value.name + is ByteArray -> value.joinToString("") { "%02x".format(it) } + is Collection<*> -> value.map(::normalize) + is Map<*, *> -> value.entries.associate { normalize(it.key).toString() to normalize(it.value) } + else -> value.javaClass.declaredFields.filterNot { Modifier.isStatic(it.modifiers) || it.isSynthetic } + .sortedBy { it.name }.associate { it.name to normalize(it.apply { isAccessible = true }.get(value)) } + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/ReferenceIntegrityTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/ReferenceIntegrityTest.kt new file mode 100644 index 000000000000..d27439f4e19d --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/ReferenceIntegrityTest.kt @@ -0,0 +1,44 @@ +package app.aaps.plugins.eversense.protocol + +import java.io.ByteArrayInputStream +import java.security.MessageDigest +import java.util.zip.ZipInputStream +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +/** The oracle must stay independent from later changes to production code. */ +class ReferenceIntegrityTest { + private fun sha256(bytes: ByteArray): String = MessageDigest.getInstance("SHA-256") + .digest(bytes).joinToString("") { "%02x".format(it.toInt() and 255) } + + @Test fun frozenSourcesHaveTheRecordedHashes() { + val archive = checkNotNull(javaClass.getResourceAsStream("/protocol-reference.zip")).use { it.readBytes() } + assertEquals("148f63d0a9375f01b9e0c0b67c75148a1bfe46d931842da462298d3023444f93", sha256(archive)) + val entries = mutableMapOf() + ZipInputStream(ByteArrayInputStream(archive)).use { zip -> + while (true) { + val entry = zip.nextEntry ?: break + if (!entry.isDirectory) entries[entry.name] = zip.readBytes() + } + } + val manifest = Json.parseToJsonElement(checkNotNull(entries["baseline.json"]).decodeToString()).jsonObject + assertEquals("bb0b0373cd6ccf6b935a63783cb5fcf29468e317", manifest.getValue("baseline_commit").jsonPrimitive.content) + val commands = checkNotNull(javaClass.getResourceAsStream("/protocol-command-classes.txt")) + .bufferedReader().use { it.readLines() } + assertEquals(109, commands.size) + assertEquals(109, commands.toSet().size) + assertEquals(manifest.getValue("commands").jsonArray.map { it.jsonPrimitive.content }.sorted(), commands.sorted()) + val files = manifest.getValue("files").jsonArray + assertEquals(156, files.size) + for (file in files) { + val item = file.jsonObject + val path = item.getValue("path").jsonPrimitive.content + assertEquals(item.getValue("sha256").jsonPrimitive.content, sha256(checkNotNull(entries[path])), path) + } + assertEquals(files.size, entries.keys.count { it.endsWith(".kt") }) + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/SecureChannelCompatibilityTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/SecureChannelCompatibilityTest.kt new file mode 100644 index 000000000000..7d039ea1e6a5 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/protocol/SecureChannelCompatibilityTest.kt @@ -0,0 +1,63 @@ +package app.aaps.plugins.eversense.protocol + +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.util.EversenseCrypto365Util +import java.lang.reflect.InvocationTargetException +import java.util.Random +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.mockito.Mockito +import org.mockito.kotlin.mock + +class SecureChannelCompatibilityTest { + private val referenceType = Class.forName("app.aaps.plugins.eversense.reference.util.EversenseCrypto365Util") + private fun reference(): Any = referenceType.constructors.single().let { it.newInstance(Mockito.mock(it.parameterTypes[0])) } + private fun material(target: Any, salt: ByteArray?, key: ByteArray?, sequence: Int) { + for ((name, value) in listOf("ephemSalt" to salt, "sessionKey" to key, "messageSequenceNumber" to sequence)) { + target.javaClass.getDeclaredField(name).apply { isAccessible = true; set(target, value) } + } + } + private fun call(target: Any, name: String, input: ByteArray): ByteArray = target.javaClass.getMethod(name, ByteArray::class.java).invoke(target, input) as ByteArray + private fun sequence(target: Any): Int = target.javaClass.getDeclaredField("messageSequenceNumber").apply { isAccessible = true }.getInt(target) + + @Test fun authenticatedCiphertextAndCounterRolloverMatchFrozenSession() { + val random = Random(365191) + for (start in listOf(0, 1, 16382, 16383, 16384, 65535, Int.MAX_VALUE, Int.MIN_VALUE)) { + for (size in listOf(0, 1, 2, 15, 16, 17, 64, 185, 512)) { + val old = reference() + val current = EversenseCrypto365Util(mock()) + val key = ByteArray(16).also(random::nextBytes) + val salt = ByteArray(8).also(random::nextBytes) + material(old, salt, key, start); material(current, salt, key, start) + repeat(4) { + val plaintext = ByteArray(size).also(random::nextBytes) + val expected = call(old, "encrypt", plaintext) + val actual = current.encrypt(plaintext) + assertArrayEquals(expected, actual, "start=$start size=$size") + assertEquals(sequence(old), sequence(current)) + assertArrayEquals(plaintext, call(old, "decrypt", actual)) + assertArrayEquals(plaintext, current.decrypt(expected)) + val damaged = actual.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() } + assertArrayEquals(call(old, "decrypt", damaged), current.decrypt(damaged)) + } + } + } + } + @Test fun missingMaterialTruncatedMessagesAndInvalidKeySizesRetainFailureOutcomes() { + for (salt in listOf(null, ByteArray(8))) for (key in listOf(null, ByteArray(0), ByteArray(15), ByteArray(16))) { + val old = reference(); val current = EversenseCrypto365Util(mock()) + material(old, salt, key, 1); material(current, salt, key, 1) + for (bytes in listOf(byteArrayOf(), byteArrayOf(1), byteArrayOf(1,2), ByteArray(10))) { + for (method in listOf("encrypt", "decrypt")) { + assertEquals(outcome { call(old, method, bytes) }, outcome { call(current, method, bytes) }, "$method with ${bytes.size} bytes") + assertEquals(sequence(old), sequence(current)) + } + } + } + } + private fun outcome(operation: () -> ByteArray): String = try { operation().joinToString(",") } catch (error: Exception) { + val cause = if (error is InvocationTargetException) error.targetException else error + cause.javaClass.simpleName + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseDmsBinaryCodecTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseDmsBinaryCodecTest.kt new file mode 100644 index 000000000000..59069a11595a --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseDmsBinaryCodecTest.kt @@ -0,0 +1,131 @@ +package app.aaps.plugins.eversense.util + +import app.aaps.plugins.eversense.enums.CalibrationFlag +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.packets.e365.CalibrationHistoryItem +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.util.Base64 + +/** + * Golden tests for [EversenseDmsBinaryCodec]. + * + * These pin the exact bytes/base64 that get uploaded to the Eversense DMS portal. They were + * computed independently (not from the Kotlin code) and verified to match the two original + * per-file copies that this codec replaced, so they guarantee the de-duplication did not + * change any uploaded value and guard against future drift. + * + * Reference timestamp: 1700000000000 ms == 2023-11-14T22:13:20 UTC. + */ +class EversenseDmsBinaryCodecTest { + + private val ts = 1700000000000L + private fun b64(bytes: ByteArray) = Base64.getEncoder().encodeToString(bytes) + private fun reading(glucose: Int, datetime: Long, sensorId: String) = + EversenseCGMResult(glucose, datetime, EversenseTrendArrow.FLAT, sensorId, "") + + // ─── little-endian integers ─────────────────────────────────────────────── + + @Test + fun `int16LE writes two little-endian bytes`() { + assertArrayEquals(byteArrayOf(0x34, 0x12), EversenseDmsBinaryCodec.int16LE(0x1234)) + } + + @Test + fun `int24LE writes three little-endian bytes`() { + assertArrayEquals(byteArrayOf(0x56, 0x34, 0x12), EversenseDmsBinaryCodec.int24LE(0x123456)) + } + + @Test + fun `int32LE writes four little-endian bytes including negative offsets`() { + assertArrayEquals(byteArrayOf(0x78, 0x56, 0x34, 0x12), EversenseDmsBinaryCodec.int32LE(0x12345678)) + // Negative timezone offset (e.g. -18000 s == UTC-5) must two's-complement correctly + assertEquals("sLn//w==", b64(EversenseDmsBinaryCodec.int32LE(-18000))) + } + + // ─── timestamp packing ───────────────────────────────────────────────────── + + @Test + fun `calcDateBytes packs the date the way the transmitter protocol expects`() { + assertArrayEquals(byteArrayOf(0x6E, 0x2F), EversenseDmsBinaryCodec.calcDateBytes(ts)) + } + + @Test + fun `calcTimeBytes packs the time the way the transmitter protocol expects`() { + assertArrayEquals(byteArrayOf(0xAA.toByte(), 0xB1.toByte()), EversenseDmsBinaryCodec.calcTimeBytes(ts)) + } + + // ─── fixed-header blobs ───────────────────────────────────────────────────── + + @Test + fun `buildEmptyMgBytes is the fixed zero-record header`() { + assertEquals("mAEAAAAA", EversenseDmsBinaryCodec.buildEmptyMgBytes()) + } + + @Test + fun `buildEmptyPatientBytes is the fixed zero-event header`() { + assertEquals("ngEAAAA=", EversenseDmsBinaryCodec.buildEmptyPatientBytes()) + } + + @Test + fun `buildAlertBytes embeds the sensor id and a zero count`() { + assertEquals("kwEAAAAjwasA", EversenseDmsBinaryCodec.buildAlertBytes("23C1AB")) + assertEquals("kwEAAAAA", EversenseDmsBinaryCodec.buildAlertBytes("")) + } + + // ─── glucose / calibration record blobs ───────────────────────────────────── + + @Test + fun `buildSgBytes with no readings is just the header and a zero count`() { + assertEquals("jAABAAAAAAA=", EversenseDmsBinaryCodec.buildSgBytes(emptyList())) + } + + @Test + fun `buildSgBytes encodes a single reading exactly`() { + val expected = "jAABAAABAAABAABuL6qxeAAAI8GrAAAAAAAAAAAAAAAAAAAAAAAAAA==" + assertEquals(expected, EversenseDmsBinaryCodec.buildSgBytes(listOf(reading(120, ts, "23C1AB")))) + } + + @Test + fun `buildSgBytes encodes multiple readings with incrementing record numbers`() { + val expected = "jAABAAACAAABAABuL6qxeAAAI8GrAAAAAAAAAAAAAAAAAAAAAAAAAAIAAG4vSrJfAAAjwasAAAAAAAAAAAAAAAAAAAAAAAAA" + val readings = listOf(reading(120, ts, "23C1AB"), reading(95, ts + 300000, "23C1AB")) + assertEquals(expected, EversenseDmsBinaryCodec.buildSgBytes(readings)) + } + + @Test + fun `buildMgBytes encodes a calibration record exactly`() { + val cals = listOf(CalibrationHistoryItem(ts, 100, CalibrationFlag.ACTUALLY_USED_FOR_CALIBRATION)) + assertEquals("mAEAAQAAAQBuL6qxZAAAAAEAAAA=", EversenseDmsBinaryCodec.buildMgBytes(cals)) + } + + // ─── ordinal mappings ─────────────────────────────────────────────────────── + + @Test + fun `signalStrengthOrdinal maps percentage bands to ordinals`() { + assertEquals(5, EversenseDmsBinaryCodec.signalStrengthOrdinal(100)) + assertEquals(5, EversenseDmsBinaryCodec.signalStrengthOrdinal(75)) + assertEquals(4, EversenseDmsBinaryCodec.signalStrengthOrdinal(74)) + assertEquals(4, EversenseDmsBinaryCodec.signalStrengthOrdinal(48)) + assertEquals(3, EversenseDmsBinaryCodec.signalStrengthOrdinal(47)) + assertEquals(3, EversenseDmsBinaryCodec.signalStrengthOrdinal(30)) + assertEquals(2, EversenseDmsBinaryCodec.signalStrengthOrdinal(29)) + assertEquals(2, EversenseDmsBinaryCodec.signalStrengthOrdinal(28)) + assertEquals(1, EversenseDmsBinaryCodec.signalStrengthOrdinal(27)) + assertEquals(1, EversenseDmsBinaryCodec.signalStrengthOrdinal(25)) + assertEquals(0, EversenseDmsBinaryCodec.signalStrengthOrdinal(24)) + assertEquals(0, EversenseDmsBinaryCodec.signalStrengthOrdinal(0)) + } + + @Test + fun `trendOrdinal maps every arrow to its protocol ordinal`() { + assertEquals(0, EversenseDmsBinaryCodec.trendOrdinal(EversenseTrendArrow.NONE)) + assertEquals(1, EversenseDmsBinaryCodec.trendOrdinal(EversenseTrendArrow.SINGLE_DOWN)) + assertEquals(2, EversenseDmsBinaryCodec.trendOrdinal(EversenseTrendArrow.FORTY_FIVE_DOWN)) + assertEquals(3, EversenseDmsBinaryCodec.trendOrdinal(EversenseTrendArrow.FLAT)) + assertEquals(4, EversenseDmsBinaryCodec.trendOrdinal(EversenseTrendArrow.FORTY_FIVE_UP)) + assertEquals(5, EversenseDmsBinaryCodec.trendOrdinal(EversenseTrendArrow.SINGLE_UP)) + } +} diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseHttp365UtilTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseHttp365UtilTest.kt new file mode 100644 index 000000000000..a9fd80a46185 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseHttp365UtilTest.kt @@ -0,0 +1,396 @@ +package app.aaps.plugins.eversense.util + +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.EversenseCGMResult +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotNull +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class EversenseHttp365UtilTest { + + private lateinit var mockWebServer: MockWebServer + private lateinit var prefs: EversenseStore + private lateinit var editor: EversenseStore.Editor + + private val validTokenJson = """ + { + "access_token": "test_access_token_abc123", + "expires_in": 3600, + "token_type": "Bearer", + "expires": "2099-01-01T00:00:00Z", + "lastLogin": "2026-04-10T00:00:00Z" + } + """.trimIndent() + + @BeforeEach + fun setUp() { + mockWebServer = MockWebServer() + mockWebServer.start() + + val baseUrl = mockWebServer.url("/").toString() + EversenseHttp365Util.tokenBaseUrl = baseUrl + EversenseHttp365Util.uploadBaseUrl = baseUrl + + prefs = mock() + editor = mock() + whenever(prefs.edit()).thenReturn(editor) + whenever(editor.putString(any(), anyOrNull())).thenReturn(editor) + whenever(editor.putLong(any(), any())).thenReturn(editor) + whenever(editor.commit()).thenReturn(true) + whenever(editor.apply()).then { } + + // Default: no stored state (empty secure state) + whenever(prefs.getString(StorageKeys.SECURE_STATE, null)).thenReturn(null) + } + + @AfterEach + fun tearDown() { + mockWebServer.shutdown() + // Restore production URLs + EversenseHttp365Util.tokenBaseUrl = "https://usiamapi.eversensedms.com/" + EversenseHttp365Util.uploadBaseUrl = "https://usmobileappmsprod.eversensedms.com/" + } + + // ─── getOrRefreshToken ──────────────────────────────────────────────────── + + @Test + fun `getOrRefreshToken returns cached token when not expired`() { + val futureExpiry = System.currentTimeMillis() + 600_000L // 10 minutes from now + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("cached_token_xyz") + + val token = EversenseHttp365Util.getOrRefreshToken(prefs) + + assertEquals("cached_token_xyz", token) + // No requests should have been made to the server + assertEquals(0, mockWebServer.requestCount) + } + + @Test + fun `getOrRefreshToken fetches new token when cache is expired`() { + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(0L) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn(null) + whenever(prefs.getString(StorageKeys.SECURE_STATE, null)).thenReturn( + """{"username":"user@example.com","password":"testpass"}""" + ) + + mockWebServer.enqueue(MockResponse().setBody(validTokenJson).setResponseCode(200)) + + val token = EversenseHttp365Util.getOrRefreshToken(prefs) + + assertEquals("test_access_token_abc123", token) + assertEquals(1, mockWebServer.requestCount) + val request = mockWebServer.takeRequest() + assertEquals("/connect/token", request.path) + assertEquals("POST", request.method) + assertTrue(request.body.readUtf8().contains("grant_type=password")) + } + + @Test + fun `getOrRefreshToken returns null when login fails`() { + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(0L) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn(null) + + mockWebServer.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":"invalid_client"}""")) + + val token = EversenseHttp365Util.getOrRefreshToken(prefs) + + assertNull(token) + } + + @Test + fun `getOrRefreshToken refreshes token within 5 minutes of expiry`() { + // Token expires in 4 minutes — within the 5-minute refresh window + val nearExpiryMs = System.currentTimeMillis() + 240_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(nearExpiryMs) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("old_token") + whenever(prefs.getString(StorageKeys.SECURE_STATE, null)).thenReturn( + """{"username":"user@example.com","password":"testpass"}""" + ) + + mockWebServer.enqueue(MockResponse().setBody(validTokenJson).setResponseCode(200)) + + val token = EversenseHttp365Util.getOrRefreshToken(prefs) + + assertEquals("test_access_token_abc123", token) + assertEquals(1, mockWebServer.requestCount) + } + + // ─── uploadGlucoseReadings ──────────────────────────────────────────────── + + @Test + fun `uploadGlucoseReadings posts to correct endpoint with bearer token`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("my_bearer_token") + + mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody("[]")) + + val readings = listOf( + EversenseCGMResult( + glucoseInMgDl = 120, + datetime = 1700000000000L, + trend = EversenseTrendArrow.FLAT, + sensorId = "sensor_001", + rawResponseHex = "deadbeef" + ) + ) + + val result = EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX-12345", "1.2.3") + + assertTrue(result.success, "Expected upload to succeed on HTTP 200") + assertEquals(1, result.sentCount, "Expected the reading to be counted as actually sent") + assertEquals(200, result.httpStatus) + assertEquals(1, mockWebServer.requestCount) + val request = mockWebServer.takeRequest() + assertEquals("/api/v1.0/DiagnosticLog/PostEssentialLogs", request.path) + assertEquals("POST", request.method) + assertEquals("Bearer my_bearer_token", request.getHeader("Authorization")) + assertEquals("application/json", request.getHeader("Content-Type")) + } + + @Test + fun `uploadGlucoseReadings sends correct JSON body fields`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("my_bearer_token") + + mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody("[]")) + + val readings = listOf( + EversenseCGMResult( + glucoseInMgDl = 95, + datetime = 1700000000000L, + trend = EversenseTrendArrow.FLAT, + sensorId = "abc123", + rawResponseHex = "cafebabe" + ) + ) + + EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TXSERIAL", "2.0.1") + + val body = mockWebServer.takeRequest().body.readUtf8() + + assertTrue(body.startsWith("[") && body.endsWith("]"), "Body must be a bare JSON array") + assertTrue(body.contains("\"SensorId\":\"23C1AB\""), "Missing SensorId") + assertTrue(body.contains("\"TransmitterId\":\"TXSERIAL\""), "Missing TransmitterId") + assertTrue(body.contains("\"CurrentGlucoseValue\":95"), "Missing CurrentGlucoseValue") + assertTrue(body.contains("\"FWVersion\":\"2.0.1\""), "Missing FWVersion") + // EssentialLog must be base64-encoded bytes, not a hex string + val expectedBase64 = java.util.Base64.getEncoder().encodeToString(byteArrayOf(0xca.toByte(), 0xfe.toByte(), 0xba.toByte(), 0xbe.toByte())) + assertTrue(body.contains("\"EssentialLog\":\"$expectedBase64\""), "EssentialLog must be base64 bytes, got: $body") + } + + @Test + fun `uploadGlucoseReadings sends multiple readings in one request`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("token") + + mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody("[]")) + + val readings = listOf( + EversenseCGMResult(100, 1700000000000L, EversenseTrendArrow.FLAT, "s1", "aa"), + EversenseCGMResult(110, 1700000300000L, EversenseTrendArrow.SINGLE_UP, "s1", "bb"), + EversenseCGMResult(105, 1700000600000L, EversenseTrendArrow.SINGLE_DOWN, "s1", "cc") + ) + + EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX99", "3.0") + + assertEquals(1, mockWebServer.requestCount) + val body = mockWebServer.takeRequest().body.readUtf8() + assertTrue(body.contains("\"CurrentGlucoseValue\":100")) + assertTrue(body.contains("\"CurrentGlucoseValue\":110")) + assertTrue(body.contains("\"CurrentGlucoseValue\":105")) + } + + @Test + fun `uploadGlucoseReadings does nothing when readings list is empty`() { + EversenseHttp365Util.uploadGlucoseReadings(prefs, emptyList(), "TX99", "1.0") + + assertEquals(0, mockWebServer.requestCount) + } + + /** + * The case that made missing DMS readings look like healthy uploads: a reading carrying no + * raw BLE data is filtered out before the POST, nothing reaches the server, and this used to + * return success — so the caller logged "1 reading(s) sent" for an upload that never left the + * phone. It must report failure and say how many were skipped. + */ + @Test + fun `uploadGlucoseReadings reports a skip, not a success, when no reading carries raw BLE data`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("token") + + val readings = listOf( + EversenseCGMResult( + glucoseInMgDl = 120, + datetime = 1700000000000L, + trend = EversenseTrendArrow.FLAT, + sensorId = "sensor_001", + rawResponseHex = "" + ) + ) + + val result = EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX1", "1.0") + + assertFalse(result.success, "Sending nothing is not a successful upload") + assertEquals(0, result.sentCount) + assertEquals(1, result.skippedNoRawData) + assertEquals(0, mockWebServer.requestCount, "Nothing should have been POSTed") + } + + @Test + fun `uploadGlucoseReadings counts only readings that carry raw BLE data as sent`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("token") + mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody("[]")) + + val readings = listOf( + EversenseCGMResult(120, 1700000000000L, EversenseTrendArrow.FLAT, "sensor_001", "deadbeef"), + EversenseCGMResult(121, 1700000300000L, EversenseTrendArrow.FLAT, "sensor_001", "") + ) + + val result = EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX1", "1.0") + + assertTrue(result.success) + assertEquals(1, result.sentCount, "Only the reading with raw data was sent") + assertEquals(1, result.skippedNoRawData, "The other must be reported as skipped, not sent") + } + + @Test + fun `uploadGlucoseReadings does not throw on 4xx server error`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("token") + + mockWebServer.enqueue(MockResponse().setResponseCode(400).setBody("""{"error":"bad request"}""")) + + val readings = listOf( + EversenseCGMResult(120, System.currentTimeMillis(), EversenseTrendArrow.FLAT, "s1", "ff") + ) + + // Should not throw — errors are logged internally, returns false + val result = EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX1", "1.0") + + assertFalse(result.success, "Expected upload to fail on HTTP 400") + assertEquals(0, result.sentCount, "A rejected request must not report readings as sent") + assertEquals(400, result.httpStatus) + assertEquals(1, mockWebServer.requestCount) + } + + @Test + fun `uploadGlucoseReadings does not throw on 5xx server error`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("token") + + mockWebServer.enqueue(MockResponse().setResponseCode(500).setBody("Internal Server Error")) + + val readings = listOf( + EversenseCGMResult(80, System.currentTimeMillis(), EversenseTrendArrow.FLAT, "s1", "01") + ) + + val result = EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX1", "1.0") + + assertFalse(result.success, "Expected upload to fail on HTTP 500") + assertEquals(0, result.sentCount, "A rejected request must not report readings as sent") + assertEquals(500, result.httpStatus) + assertEquals(1, mockWebServer.requestCount) + } + + @Test + fun `uploadGlucoseReadings skips upload when no valid token available`() { + // Token expired and login fails + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(0L) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn(null) + + mockWebServer.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":"unauthorized"}""")) + + val readings = listOf( + EversenseCGMResult(100, System.currentTimeMillis(), EversenseTrendArrow.FLAT, "s1", "ab") + ) + + EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX1", "1.0") + + // Only the login attempt should have been made, not the upload + assertEquals(1, mockWebServer.requestCount) + assertEquals("/connect/token", mockWebServer.takeRequest().path) + } + + // ─── login ─────────────────────────────────────────────────────────────── + + @Test + fun `login sends correct form-encoded body`() { + whenever(prefs.getString(StorageKeys.SECURE_STATE, null)).thenReturn( + """{"username":"testuser@test.com","password":"secret123"}""" + ) + + mockWebServer.enqueue(MockResponse().setBody(validTokenJson).setResponseCode(200)) + + val result = EversenseHttp365Util.login(prefs) + + assertNotNull(result) + assertEquals("test_access_token_abc123", result!!.access_token) + assertEquals(3600, result.expires_in) + + val request = mockWebServer.takeRequest() + val body = request.body.readUtf8() + assertTrue(body.contains("grant_type=password")) + assertTrue(body.contains("client_id=eversenseMMAAndroid")) + assertTrue(body.contains("username=testuser%40test.com") || body.contains("username=testuser@test.com")) + } + + @Test + fun `login returns null on 401 response`() { + whenever(prefs.getString(StorageKeys.SECURE_STATE, null)).thenReturn( + """{"username":"bad@user.com","password":"wrong"}""" + ) + + mockWebServer.enqueue(MockResponse().setResponseCode(401).setBody("""{"error":"invalid_grant"}""")) + + val result = EversenseHttp365Util.login(prefs) + + assertNull(result) + } + + // ─── timestamp formatting (guards the thread-safe ThreadLocal change) ────── + + @Test + fun `uploadGlucoseReadings formats timestamp as UTC in the expected pattern`() { + val futureExpiry = System.currentTimeMillis() + 600_000L + whenever(prefs.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0)).thenReturn(futureExpiry) + whenever(prefs.getString(StorageKeys.ACCESS_TOKEN, null)).thenReturn("token") + + mockWebServer.enqueue(MockResponse().setResponseCode(200).setBody("[]")) + + // 1700000000000 ms == 2023-11-14T22:13:20 UTC. The formatter must emit UTC with + // no offset, regardless of the machine's default time zone. + val readings = listOf( + EversenseCGMResult(120, 1700000000000L, EversenseTrendArrow.FLAT, "s1", "ab") + ) + + EversenseHttp365Util.uploadGlucoseReadings(prefs, readings, "TX1", "1.0") + + val body = mockWebServer.takeRequest().body.readUtf8() + assertTrue( + body.contains("\"Timestamp\":\"2023-11-14T22:13:20\""), + "Timestamp must be UTC in yyyy-MM-dd'T'HH:mm:ss; got: $body" + ) + } +} + diff --git a/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseLoggerTest.kt b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseLoggerTest.kt new file mode 100644 index 000000000000..dcafd4604ec3 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/kotlin/app/aaps/plugins/eversense/util/EversenseLoggerTest.kt @@ -0,0 +1,89 @@ +package app.aaps.plugins.eversense.util + +import app.aaps.plugins.eversense.storage.EversenseStore +import ch.qos.logback.classic.LoggerContext +import ch.qos.logback.classic.spi.ILoggingEvent +import ch.qos.logback.core.AppenderBase +import java.nio.file.Path +import java.security.KeyPairGenerator +import java.security.interfaces.ECPublicKey +import java.security.spec.ECGenParameterSpec +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.mockito.kotlin.mock + +class EversenseLoggerTest { + @TempDir lateinit var directory: Path + private val instanceField = EversenseLogger::class.java.getDeclaredField("configuredInstance").apply { isAccessible = true } + private var previous: Any? = null + private lateinit var context: LoggerContext + private class CaptureAppender : AppenderBase() { + val list = mutableListOf() + override fun append(event: ILoggingEvent) { list.add(event) } + } + private lateinit var events: CaptureAppender + + @BeforeEach fun setup() { + previous = instanceField.get(null) + EversenseLogger.setDiagnosticLogging(false) + val logger = EversenseLogger::class.java.getDeclaredConstructor(String::class.java).apply { isAccessible = true }.newInstance(directory.toString()) + context = EversenseLogger::class.java.getDeclaredField("lc").apply { isAccessible = true }.get(logger) as LoggerContext + val root = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) + root.detachAndStopAllAppenders() + events = CaptureAppender().apply { start() } + root.addAppender(events) + instanceField.set(null, logger) + } + @AfterEach fun cleanup() { + EversenseLogger.setDiagnosticLogging(false) + context.stop() + instanceField.set(null, previous) + } + @Test fun normalModeKeepsOperationalMessagesAndDoesNotFormatPacketDetails() { + var formatted = false + EversenseLogger.debug("test") { formatted = true; "raw packet data" } + EversenseLogger.info("test", "connected") + EversenseLogger.warning("test", "retrying") + EversenseLogger.error("test", "link failed") + assertFalse(formatted) + assertEquals(listOf("connected", "retrying", "link failed"), events.list.map { it.formattedMessage }) + } + @Test fun diagnosticSwitchTakesEffectImmediatelyAndStopsFormattingWhenDisabled() { + var formatted = 0 + EversenseLogger.setDiagnosticLogging(true) + EversenseLogger.debug("test") { formatted++; "packet" } + EversenseLogger.setDiagnosticLogging(false) + EversenseLogger.debug("test") { formatted++; "suppressed" } + EversenseLogger.info("test", "still connected") + assertEquals(1, formatted) + assertEquals(listOf("packet", "still connected"), events.list.map { it.formattedMessage }) + } + @Test fun aapsDiagnosticBlocksAreAlsoGated() { + var emitted = 0 + EversenseLogger.diagnostic { emitted++ } + EversenseLogger.setDiagnosticLogging(true) + EversenseLogger.diagnostic { emitted++ } + EversenseLogger.setDiagnosticLogging(false) + EversenseLogger.diagnostic { emitted++ } + assertEquals(1, emitted) + } + @Test fun derivingSessionKeyDoesNotWriteItsValueEvenInDiagnosticMode() { + EversenseLogger.setDiagnosticLogging(true) + val generator = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) } + val local = generator.generateKeyPair() + val remote = generator.generateKeyPair().public as ECPublicKey + val crypto = EversenseCrypto365Util(mock()) + EversenseCrypto365Util::class.java.getDeclaredField("ephemPrivate").apply { isAccessible = true; set(crypto, local.private) } + EversenseCrypto365Util::class.java.getDeclaredField("ephemSalt").apply { isAccessible = true; set(crypto, ByteArray(8) { 1 }) } + fun coordinate(value: java.math.BigInteger) = value.toByteArray().takeLast(32).toByteArray().let { ByteArray(32 - it.size) + it } + crypto.generateSessionKey(coordinate(remote.w.affineX) + coordinate(remote.w.affineY)) + val key = EversenseCrypto365Util::class.java.getDeclaredField("sessionKey").apply { isAccessible = true }.get(crypto) as? ByteArray + assertNotNull(key) + assertEquals(16, key!!.size) + val keyHex = key.joinToString("") { "%02x".format(it) } + assertTrue(events.list.none { it.formattedMessage.contains(keyHex, ignoreCase = true) }) + } +} diff --git a/plugins/eversense/src/androidHostTest/resources/protocol-command-classes.txt b/plugins/eversense/src/androidHostTest/resources/protocol-command-classes.txt new file mode 100644 index 000000000000..6d069473f5c9 --- /dev/null +++ b/plugins/eversense/src/androidHostTest/resources/protocol-command-classes.txt @@ -0,0 +1,109 @@ +app.aaps.plugins.eversense.packets.e3.EnterDiagnosticModePacket +app.aaps.plugins.eversense.packets.e3.ExitDiagnosticModePacket +app.aaps.plugins.eversense.packets.e3.GetAlertLogPacket +app.aaps.plugins.eversense.packets.e3.GetBatteryPercentagePacket +app.aaps.plugins.eversense.packets.e3.GetBleDisconnectPacket +app.aaps.plugins.eversense.packets.e3.GetCalibrationDailyPacket +app.aaps.plugins.eversense.packets.e3.GetCalibrationLogPacket +app.aaps.plugins.eversense.packets.e3.GetCalibrationLogRangePacket +app.aaps.plugins.eversense.packets.e3.GetCalibrationPhasePacket +app.aaps.plugins.eversense.packets.e3.GetCalibrationReadinessPacket +app.aaps.plugins.eversense.packets.e3.GetCompletedCalibrationsCountPacket +app.aaps.plugins.eversense.packets.e3.GetCurrentDatetimePacket +app.aaps.plugins.eversense.packets.e3.GetCurrentGlucosePacket +app.aaps.plugins.eversense.packets.e3.GetGlucoseAlertsAndStatusPacket +app.aaps.plugins.eversense.packets.e3.GetGlucoseLogPacket +app.aaps.plugins.eversense.packets.e3.GetGlucoseLogRangePacket +app.aaps.plugins.eversense.packets.e3.GetHighGlucoseRepeatIntervalPacket +app.aaps.plugins.eversense.packets.e3.GetInsertionDatePacket +app.aaps.plugins.eversense.packets.e3.GetInsertionTimePacket +app.aaps.plugins.eversense.packets.e3.GetIsOneCalPhasePacket +app.aaps.plugins.eversense.packets.e3.GetLastCalibrationDatePacket +app.aaps.plugins.eversense.packets.e3.GetLastCalibrationTimePacket +app.aaps.plugins.eversense.packets.e3.GetLowGlucoseRepeatIntervalPacket +app.aaps.plugins.eversense.packets.e3.GetMmaFeaturesPacket +app.aaps.plugins.eversense.packets.e3.GetSettingGlucoseHighEnabled +app.aaps.plugins.eversense.packets.e3.GetSettingGlucoseHighThresholdPacket +app.aaps.plugins.eversense.packets.e3.GetSettingGlucoseLowThresholdPacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveAlarmEnabledPacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveHighEnabledPacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveHighThresholdPacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveHighTimePacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveLowEnabledPacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveLowThresholdPacket +app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveLowTimePacket +app.aaps.plugins.eversense.packets.e3.GetSettingRateEnabledPacket +app.aaps.plugins.eversense.packets.e3.GetSettingRateFallingEnabledPacket +app.aaps.plugins.eversense.packets.e3.GetSettingRateFallingThresholdPacket +app.aaps.plugins.eversense.packets.e3.GetSettingRateRisingEnabledPacket +app.aaps.plugins.eversense.packets.e3.GetSettingRateRisingThresholdPacket +app.aaps.plugins.eversense.packets.e3.GetSettingVibratePacket +app.aaps.plugins.eversense.packets.e3.GetSignalStrengthRawPacket +app.aaps.plugins.eversense.packets.e3.GetVersionExtendedPacket +app.aaps.plugins.eversense.packets.e3.GetVersionPacket +app.aaps.plugins.eversense.packets.e3.PingPacket +app.aaps.plugins.eversense.packets.e3.SaveBondingInformationPacket +app.aaps.plugins.eversense.packets.e3.SendCalibrationPacket +app.aaps.plugins.eversense.packets.e3.SetAppVersionE3Packet +app.aaps.plugins.eversense.packets.e3.SetBleDisconnectPacket +app.aaps.plugins.eversense.packets.e3.SetBloodGlucosePointPacket +app.aaps.plugins.eversense.packets.e3.SetCurrentDatetimePacket +app.aaps.plugins.eversense.packets.e3.SetHighGlucoseRepeatIntervalDayPacket +app.aaps.plugins.eversense.packets.e3.SetHighGlucoseRepeatIntervalNightPacket +app.aaps.plugins.eversense.packets.e3.SetLowGlucoseRepeatIntervalDayPacket +app.aaps.plugins.eversense.packets.e3.SetLowGlucoseRepeatIntervalNightPacket +app.aaps.plugins.eversense.packets.e3.SetSettingGlucoseHighEnablePacket +app.aaps.plugins.eversense.packets.e3.SetSettingGlucoseHighThresholdPacket +app.aaps.plugins.eversense.packets.e3.SetSettingGlucoseLowThresholdPacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveAlarmEnabledPacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveHighAlarmEnabledPacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveHighThresholdPacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveHighTimePacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveLowAlarmEnabledPacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveLowThresholdPacket +app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveLowTimePacket +app.aaps.plugins.eversense.packets.e3.SetSettingRateEnabledPacket +app.aaps.plugins.eversense.packets.e3.SetSettingRateFallingEnabledPacket +app.aaps.plugins.eversense.packets.e3.SetSettingRateFallingThresholdPacket +app.aaps.plugins.eversense.packets.e3.SetSettingRateRisingEnabledPacket +app.aaps.plugins.eversense.packets.e3.SetSettingRateRisingThresholdPacket +app.aaps.plugins.eversense.packets.e3.SetSettingVibratePacket +app.aaps.plugins.eversense.packets.e365.AuthIdentityPacket +app.aaps.plugins.eversense.packets.e365.AuthStartPacket +app.aaps.plugins.eversense.packets.e365.AuthWhoAmIPacket +app.aaps.plugins.eversense.packets.e365.EnterDiagnosticMode365Packet +app.aaps.plugins.eversense.packets.e365.ExitDiagnosticMode365Packet +app.aaps.plugins.eversense.packets.e365.GetActiveAlarmsPacket +app.aaps.plugins.eversense.packets.e365.GetAlertsLogValuesPacket +app.aaps.plugins.eversense.packets.e365.GetCalibrationInfoPacket +app.aaps.plugins.eversense.packets.e365.GetCalibrationLogValuesPacket +app.aaps.plugins.eversense.packets.e365.GetGlucoseDataPacket +app.aaps.plugins.eversense.packets.e365.GetGlucoseLogValuesPacket +app.aaps.plugins.eversense.packets.e365.GetLogRangePacket365 +app.aaps.plugins.eversense.packets.e365.GetPatientSettingsPacket +app.aaps.plugins.eversense.packets.e365.GetSensorInformationPacket +app.aaps.plugins.eversense.packets.e365.GetSignalStrengthPacket +app.aaps.plugins.eversense.packets.e365.KeepAlivePacket +app.aaps.plugins.eversense.packets.e365.Ping365Packet +app.aaps.plugins.eversense.packets.e365.PushAlarmWithDataPacket +app.aaps.plugins.eversense.packets.e365.PushKeepAlive365Packet +app.aaps.plugins.eversense.packets.e365.SetAppVersion365Packet +app.aaps.plugins.eversense.packets.e365.SetBleDisconnect365Packet +app.aaps.plugins.eversense.packets.e365.SetBloodGlucosePointPacket365 +app.aaps.plugins.eversense.packets.e365.SetCurrentDateTimePacket +app.aaps.plugins.eversense.packets.e365.SetHighGlucoseAlarm365Packet +app.aaps.plugins.eversense.packets.e365.SetHighGlucoseAlarmEnabled365Packet +app.aaps.plugins.eversense.packets.e365.SetLowGlucoseAlarm365Packet +app.aaps.plugins.eversense.packets.e365.SetPredictionHighEnabled365Packet +app.aaps.plugins.eversense.packets.e365.SetPredictionHighThreshold365Packet +app.aaps.plugins.eversense.packets.e365.SetPredictionHighTime365Packet +app.aaps.plugins.eversense.packets.e365.SetPredictionLowEnabled365Packet +app.aaps.plugins.eversense.packets.e365.SetPredictionLowThreshold365Packet +app.aaps.plugins.eversense.packets.e365.SetPredictionLowTime365Packet +app.aaps.plugins.eversense.packets.e365.SetRateFallingEnabled365Packet +app.aaps.plugins.eversense.packets.e365.SetRateFallingThreshold365Packet +app.aaps.plugins.eversense.packets.e365.SetRateRisingEnabled365Packet +app.aaps.plugins.eversense.packets.e365.SetRateRisingThreshold365Packet +app.aaps.plugins.eversense.packets.e365.SetRepeatHighGlucose365Packet +app.aaps.plugins.eversense.packets.e365.SetRepeatLowGlucose365Packet +app.aaps.plugins.eversense.packets.e365.SetVibrateMode365Packet diff --git a/plugins/eversense/src/androidHostTest/resources/protocol-reference.zip b/plugins/eversense/src/androidHostTest/resources/protocol-reference.zip new file mode 100644 index 000000000000..1b8b114e1cde Binary files /dev/null and b/plugins/eversense/src/androidHostTest/resources/protocol-reference.zip differ diff --git a/plugins/eversense/src/androidMain/AndroidManifest.xml b/plugins/eversense/src/androidMain/AndroidManifest.xml new file mode 100644 index 000000000000..60b9d66771cf --- /dev/null +++ b/plugins/eversense/src/androidMain/AndroidManifest.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/EversenseCGMPlugin.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/EversenseCGMPlugin.kt new file mode 100644 index 000000000000..6a093a5485b4 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/EversenseCGMPlugin.kt @@ -0,0 +1,522 @@ +package app.aaps.plugins.eversense + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothManager +import android.bluetooth.le.ScanSettings +import android.content.Context +import app.aaps.plugins.eversense.storage.EversenseStore +import android.os.SystemClock +import app.aaps.plugins.eversense.storage.edit +import app.aaps.plugins.eversense.callbacks.EversenseScanCallback +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.eversense.models.EversenseTransmitterSettings +import app.aaps.plugins.eversense.packets.Eversense365Communicator +import app.aaps.plugins.eversense.packets.EversenseE3Communicator +import app.aaps.plugins.eversense.packets.e3.EnterDiagnosticModePacket +import app.aaps.plugins.eversense.packets.e3.ExitDiagnosticModePacket +import app.aaps.plugins.eversense.packets.e365.EnterDiagnosticMode365Packet +import app.aaps.plugins.eversense.packets.e365.ExitDiagnosticMode365Packet +import app.aaps.plugins.eversense.packets.e3.GetCalibrationReadinessPacket +import app.aaps.plugins.eversense.packets.e3.GetSignalStrengthRawPacket +import app.aaps.plugins.eversense.packets.e365.GetSignalStrengthPacket +import app.aaps.plugins.eversense.packets.e365.SetBloodGlucosePointPacket365 +import app.aaps.plugins.eversense.enums.CalibrationReadiness +import app.aaps.plugins.eversense.util.EversenseCrypto365Util +import app.aaps.plugins.eversense.util.EversenseLogger +import app.aaps.plugins.eversense.util.EversenseScanner +import app.aaps.plugins.eversense.util.StorageKeys +import kotlinx.serialization.json.Json +import java.io.File +import java.util.concurrent.CopyOnWriteArrayList +import app.aaps.plugins.eversense.connection.EversenseConnectionController +import app.aaps.plugins.eversense.connection.HandlerConnectionScheduler +import app.aaps.plugins.eversense.connection.SessionStore +import app.aaps.plugins.eversense.callbacks.EversenseWatcher +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseSecureState +import app.aaps.plugins.eversense.enums.EversenseType + +/** + * Core Eversense CGM manager — constructor-injected, no manual singleton. + * + * Provided by the AAPS source graph. Context, BluetoothManager, and EversenseStore + * are non-nullable vals initialized at construction time, eliminating ~40 null checks. + */ +class EversenseCGMPlugin( + private val context: Context, + private val bluetoothManager: BluetoothManager, + val preferences: EversenseStore +) { + init { + // Must run before anything below (or in EversenseGattCallback's construction) does any + // EversenseLogger.* call - EversenseLogger configures Logback on first use, and + // configure() has no effect after that point. Points Eversense's own log file at the + // app's real, permission-free scoped external-files directory (same one AndroidAPS.log + // uses) instead of EversenseLogger's raw-/sdcard fallback, which scoped storage silently + // blocks writes to on modern Android without MANAGE_EXTERNAL_STORAGE - see + // EversenseLogger.configure() for the full story. + val extFilesDir = context.getExternalFilesDir(null) + val eversenseLogDir = if (extFilesDir != null) File(extFilesDir, "eversense").absolutePath else "/sdcard/AndroidAPS/eversense" + EversenseLogger.configure(eversenseLogDir) + } + + @Volatile private var activeCallback: EversenseGattCallback? = null + private val scheduler = HandlerConnectionScheduler() + private val connection = EversenseConnectionController(scheduler, SystemClock::elapsedRealtime, object : EversenseConnectionController.Transport { + override fun open(session: Long): Boolean = openConnection(session) + override fun reuse(session: Long): Boolean = activeCallback?.takeIf { it.session == session }?.reuse() == true + override fun close() { + val old = activeCallback + activeCallback = null + old?.closeSession() + } + }) + private val watchers = CopyOnWriteArrayList() + private var scanner: EversenseScanner? = null + private var scanDeadline: EversenseConnectionController.Task? = null + private var scanToken = 0L + private val scanLock = Any() + + private var shortcutFailures = 0 + private var fullAuthFailures = 0 + private var placementFailures = 0 + + internal fun deliver(session: Long, action: () -> Unit) = connection.deliver(session, action) + internal fun authenticationSucceeded(session: Long) = connection.deliver(session) { + shortcutFailures = 0 + fullAuthFailures = 0 + } + internal fun authenticationFailed(session: Long, shortcut: Boolean) = connection.whileOwned(session) { + if (shortcut) { + if (!hasInternet()) return@whileOwned + if (++shortcutFailures >= 3) { + shortcutFailures = 0 + EversenseCrypto365Util(preferences).disallowUseShortcut() + } + } else if (++fullAuthFailures >= 3) { + fullAuthFailures = 0 + EversenseCrypto365Util(preferences).allowUseShortcut() + } + } + internal fun placementChanged(session: Long, status: Int, is365: Boolean) = connection.whileOwned(session) { + if (status == 19 && !is365) { + if (++placementFailures >= 3) watchers.forEach { it.onTransmitterNotPlaced() } + } else placementFailures = 0 + } + + fun start() = connection.start(username.isNotEmpty() && password.isNotEmpty()) + fun stop() { + isPositioningMode = false + stopScan() + connection.stop() + } + fun onBluetoothAvailable() = connection.bluetoothAvailable() + internal fun sessionActive(session: Long) = connection.active(session) + internal fun sessionReady(session: Long) = connection.deliver(session) { + placementFailures = 0 + connection.ready(session) + } + internal fun sessionDisconnected(session: Long, status: Int, reuse: Boolean = false) = connection.disconnected(session, status, reuse) + + internal fun watchersFor(session: Long): List = listOf(object : EversenseWatcher { + override fun onCGMRead(type: EversenseType, readings: List) { connection.dataReceived(session) } + override fun onConnectionChanged(connected: Boolean) {} + override fun onStateChanged(state: EversenseState) {} + override fun onTransmitterReady() {} + override fun onTransmitterNotPlaced() {} + override fun onAlarmReceived(alarm: ActiveAlarm) {} + }) + watchers.map { watcher -> object : EversenseWatcher { + override fun onConnectionChanged(connected: Boolean) { if (connection.owns(session)) watcher.onConnectionChanged(connected) } + override fun onStateChanged(state: EversenseState) { if (connection.active(session)) watcher.onStateChanged(state) } + override fun onTransmitterReady() { if (connection.active(session)) watcher.onTransmitterReady() } + override fun onTransmitterNotPlaced() { if (connection.active(session)) watcher.onTransmitterNotPlaced() } + override fun onAlarmReceived(alarm: ActiveAlarm) { if (connection.active(session)) watcher.onAlarmReceived(alarm) } + override fun onCGMRead(type: EversenseType, readings: List) { if (connection.active(session)) watcher.onCGMRead(type, readings) } + } } + + // Flag to track positioning mode state for safe diagnostic mode toggling + var isPositioningMode: Boolean = false + private set + + // Credentials set by AAPS layer before any login attempt + internal var username: String = "" + private set + internal var password: String = "" + private set + + fun addWatcher(watcher: EversenseWatcher) { + watchers.addIfAbsent(watcher) + } + + fun removeWatcher(watcher: EversenseWatcher) { + watchers.remove(watcher) + } + + fun cloudStore(): EversenseStore? = connection.cloudStore(preferences) + + fun hasInternet(): Boolean { + val connectivity = context.getSystemService(android.net.ConnectivityManager::class.java) ?: return false + val capabilities = connectivity.getNetworkCapabilities(connectivity.activeNetwork) ?: return false + return capabilities.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) && + capabilities.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED) + } + + fun activeSessionStore(): EversenseStore? = activeCallback?.takeIf { sessionActive(it.session) }?.stateStore + + fun isConnected(): Boolean = activeCallback?.isConnected() == true + fun is365(): Boolean = activeCallback?.is365() == true + + fun getCurrentState(): EversenseState { + val stateJson = preferences.getString(StorageKeys.STATE, null) ?: "{}" + return JSON.decodeFromString(stateJson) + } + + @SuppressLint("MissingPermission") + fun startScan(callback: EversenseScanCallback): AutoCloseable = synchronized(scanLock) { + stopScan() + val token = ++scanToken + val bluetoothScanner = bluetoothManager.adapter?.bluetoothLeScanner + ?: return@synchronized AutoCloseable { } + val newScanner = EversenseScanner(callback) + scanner = newScanner + try { + val settings = ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build() + bluetoothScanner.startScan(null, settings, newScanner) + scanDeadline = scheduler.after(10_000L) { synchronized(scanLock) { if (scanToken == token) stopScan() } } + } catch (e: SecurityException) { + scanner = null + EversenseLogger.warning(TAG, "Cannot scan without Bluetooth permission: $e") + } + AutoCloseable { synchronized(scanLock) { if (scanToken == token) stopScan() } } + } + + @SuppressLint("MissingPermission") + fun stopScan() = synchronized(scanLock) { + scanToken++ + scanDeadline?.cancel(); scanDeadline = null + val old = scanner + scanner = null + if (old != null) try { bluetoothManager.adapter?.bluetoothLeScanner?.stopScan(old) } + catch (e: SecurityException) { EversenseLogger.warning(TAG, "Scan permission was revoked: $e") } + } + + fun forceReconnect(): Boolean = connection.connect(force = true) + + fun connect(device: BluetoothDevice? = null): Boolean { + if (device != null) { + preferences.edit { putString(StorageKeys.REMOTE_DEVICE_KEY, device.address) } + EversenseCrypto365Util(preferences).disallowUseShortcut() + } + return connection.connect(force = device != null) + } + + @SuppressLint("MissingPermission") + private fun openConnection(session: Long): Boolean { + stopScan() + if (username.isEmpty() || password.isEmpty() || bluetoothManager.adapter?.isEnabled != true) return false + val address = preferences.getString(StorageKeys.REMOTE_DEVICE_KEY, null) ?: return false + val device = try { bluetoothManager.adapter.getRemoteDevice(address) } catch (_: IllegalArgumentException) { return false } + val callback = EversenseGattCallback(this, SessionStore(connection, session, preferences), session) + activeCallback = callback + callback.attachGatt(device.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE)) + return callback.hasGatt() + } + + /** Invalidates old work before publishing credentials or region and reconnects once. */ + @Synchronized + fun setCredentials(username: String, password: String, europeanRegion: Boolean) { + val state = JSON.decodeFromString(preferences.getString(StorageKeys.SECURE_STATE, null) ?: "{}") + val changed = state.username != username || state.password != password || state.isEuropeanRegion != europeanRegion + val reconnect = changed || this.username != username || this.password != password + if (!reconnect) return + connection.disconnect() + this.username = username + this.password = password + shortcutFailures = 0 + fullAuthFailures = 0 + if (changed) { + state.username = username + state.password = password + state.isEuropeanRegion = europeanRegion + state.canUseShortcut = false + preferences.edit(commit = true) { + putString(StorageKeys.SECURE_STATE, JSON.encodeToString(state)) + remove(StorageKeys.ACCESS_TOKEN) + remove(StorageKeys.ACCESS_TOKEN_EXPIRY) + remove(StorageKeys.CLOUD_QUEUE) + } + } + if (username.isNotEmpty() && password.isNotEmpty()) connection.connect() + } + + @Synchronized + fun clearCredentials() { + connection.disconnect() + username = "" + password = "" + val state = JSON.decodeFromString(preferences.getString(StorageKeys.SECURE_STATE, null) ?: "{}") + state.username = "" + state.password = "" + state.canUseShortcut = false + preferences.edit(commit = true) { + putString(StorageKeys.SECURE_STATE, JSON.encodeToString(state)) + remove(StorageKeys.ACCESS_TOKEN) + remove(StorageKeys.ACCESS_TOKEN_EXPIRY) + remove(StorageKeys.CLOUD_QUEUE) + } + } + + fun clearStoredDevice() { + disconnect() + placementFailures = 0 + preferences.edit { remove(StorageKeys.REMOTE_DEVICE_KEY) } + EversenseLogger.info(TAG, "Cleared stored device address") + } + + fun disconnect() { + stopScan() + connection.disconnect() + } + + fun setDiagnosticMode(isEnabled: Boolean) { + val callback = activeCallback?.takeIf { it.isConnected() } + if (callback == null) { + EversenseLogger.warning(TAG, "Cannot set diagnostic mode — not connected") + return + } + try { + // Routed through bleExecutor (like every other write path) so this can't race a + // concurrently in-flight write from the Keep Alive sync cycle. + val future = callback.submitToExecutor(readyOnly = true) { doSetDiagnosticMode(callback, isEnabled) } + await(future, 20_000) + } catch (e: Exception) { + EversenseLogger.warning(TAG, "setDiagnosticMode failed: $e") + } + } + + // The actual diagnostic-mode write. Callers MUST already be running on bleExecutor's single + // worker thread - either via setDiagnosticMode() above (the normal entry point, which submits + // this to bleExecutor and blocks), or from another task already running there, like + // submitToExecutorAndSync()'s reconnect handler below. Calling this indirectly through + // setDiagnosticMode() from inside an already-running bleExecutor task deadlocks: the submit + // queues a second task behind the one currently blocked waiting for it, on an executor that + // only has one worker thread - future.get() always times out after 20s, silently, since + // setDiagnosticMode() swallows the resulting TimeoutException as a warning. + private fun doSetDiagnosticMode(callback: EversenseGattCallback, isEnabled: Boolean) { + if (callback.is365()) { + if (isEnabled) { + callback.writePacket(EnterDiagnosticMode365Packet()) + } else { + callback.writePacket(ExitDiagnosticMode365Packet()) + } + EversenseLogger.info(TAG, "Diagnostic mode set to $isEnabled (365)") + } else { + if (isEnabled) { + callback.writePacket(EnterDiagnosticModePacket()) + } else { + callback.writePacket(ExitDiagnosticModePacket()) + } + EversenseLogger.info(TAG, "Diagnostic mode set to $isEnabled (E3)") + } + } + + fun enterPositioningMode() { + isPositioningMode = true + setDiagnosticMode(true) + EversenseLogger.info(TAG, "Diagnostic Mode ENABLED: Positioning active") + } + + // Set whenever we intentionally exit diagnostic/positioning mode. The transmitter reliably + // pushes an alarm code with no EversenseAlarm mapping (-> UNKNOWN) ~1-2s after this transition + // (confirmed from device logs: signal/battery/calibration all healthy at the time - a + // mode-transition status push, not a real fault). EversensePlugin.onAlarmReceived() uses this + // timestamp to suppress just that transient push without masking a genuinely-unrecognized + // alarm arriving at any other time. + @Volatile var lastPositioningModeExitAt: Long = 0L + private set + + fun exitPositioningMode() { + isPositioningMode = false + lastPositioningModeExitAt = System.currentTimeMillis() + setDiagnosticMode(false) + EversenseLogger.info(TAG, "Diagnostic Mode DISABLED: Power saving active") + } + + fun writeSettings(settings: EversenseTransmitterSettings): Boolean { + val callback = activeCallback?.takeIf { it.isConnected() } + if (callback == null) { + EversenseLogger.error(TAG, "Transmitter is not connected") + return false + } + return try { + await(callback.submitToExecutor(readyOnly = true) { + EversenseE3Communicator.writeSettings(callback, callback.stateStore, settings) + }, 60_000) + } catch (e: Exception) { + EversenseLogger.warning(TAG, "writeSettings failed: $e") + false + } + } + + fun sendCalibration(glucoseMgDl: Int, timestampMs: Long = System.currentTimeMillis()): Boolean { + val callback = activeCallback?.takeIf { it.isConnected() } + if (callback == null) { + EversenseLogger.error(TAG, "Transmitter is not connected") + return false + } + val store = callback.operationStore() + return try { + val future = callback.submitToExecutor(readyOnly = true) { + store.contains(StorageKeys.STATE) // Reject an operation captured before a link change. + if (callback.is365()) { + val packet = SetBloodGlucosePointPacket365(glucoseMgDl, timestampMs) + callback.writePacket(packet) + EversenseLogger.info(TAG, "365 calibration sent: $glucoseMgDl mg/dL") + } else { + EversenseE3Communicator.sendCalibration(callback, glucoseMgDl) + } + } + await(future, 20_000) + + val stateJson = store.getString(StorageKeys.STATE, null) ?: "{}" + val updatedState = JSON.decodeFromString(stateJson) + updatedState.lastCalibrationDate = timestampMs + updatedState.nextCalibrationDate = timestampMs + 24 * 60 * 60 * 1000L + updatedState.calibrationReadiness = CalibrationReadiness.WAITING_POST_CALIBRATION + store.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(updatedState)) + } + EversenseLogger.debug(TAG) { "Updated calibration state: lastCalibrationDate=$timestampMs, readiness=WAITING_POST_CALIBRATION" } + + if (!callback.is365()) { + callback.submitToExecutor(readyOnly = true) { + try { + val readinessResponse = callback.writePacket(GetCalibrationReadinessPacket()) + val currentStateJson = store.getString(StorageKeys.STATE, null) ?: "{}" + val currentState = JSON.decodeFromString(currentStateJson) + currentState.calibrationReadiness = readinessResponse.readiness + store.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(currentState)) + } + EversenseLogger.debug(TAG) { "Post-calibration readiness re-read: ${readinessResponse.readiness}" } + watchersFor(callback.session).forEach { it.onStateChanged(currentState) } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Post-calibration readiness re-read failed (non-fatal): $e") + } + } + } + + true + } catch (e: Exception) { + EversenseLogger.error(TAG, "Failed to send calibration: $e") + false + } + } + + fun submitToExecutorAndSync(force: Boolean = false) { + val callback = activeCallback?.takeIf { it.isConnected() } + if (callback == null) { + EversenseLogger.error(TAG, "Cannot sync — not connected") + return + } + if (callback.is365()) { + EversenseLogger.debug(TAG) { "365 transmitter — skipping submitToExecutorAndSync (authV2flow handles it)" } + return + } + callback.submitToExecutor(readyOnly = true) { + if (isPositioningMode) { + // Already running on bleExecutor here - call the write directly, not through + // setDiagnosticMode(), which would submit-and-block on this same single-threaded + // executor and deadlock (see doSetDiagnosticMode's doc comment). + try { + doSetDiagnosticMode(callback, true) + EversenseLogger.info(TAG, "Re-enabled Diagnostic Mode after reconnect") + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Failed to re-enable diagnostic mode after reconnect: $e") + } + } + EversenseLogger.debug(TAG) { "Running E3 fullSync on bleExecutor after connect" } + EversenseE3Communicator.fullSync(callback, callback.stateStore, watchersFor(callback.session), force) + } + } + + fun triggerFullSync(force: Boolean = false) { + val callback = activeCallback?.takeIf { it.isConnected() } + if (callback == null) { + EversenseLogger.error(TAG, "Cannot sync — not connected") + return + } + callback.submitToExecutor(readyOnly = true) { + EversenseLogger.info(TAG, "Triggering full sync on user request") + if (callback.is365()) { + Eversense365Communicator.fullSync(callback, callback.stateStore, watchersFor(callback.session), force) + Eversense365Communicator.readGlucose(callback, callback.stateStore, watchersFor(callback.session)) + } else { + EversenseE3Communicator.fullSync(callback, callback.stateStore, watchersFor(callback.session), force) + EversenseE3Communicator.readGlucose(callback, callback.stateStore, watchersFor(callback.session)) + } + callback.readRssi() + } + } + + internal fun onRssiRead(rssi: Int, session: Long) { + val callback = activeCallback?.takeIf { it.session == session && connection.active(session) } ?: return + val stateJson = callback.stateStore.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + state.placementSignalRssi = rssi + callback.stateStore.edit { putString(StorageKeys.STATE, JSON.encodeToString(state)) } + EversenseLogger.debug(TAG) { "RSSI updated: $rssi dBm" } + watchersFor(session).forEach { it.onStateChanged(state) } + } + + fun readSignalStrength() { + val callback = activeCallback?.takeIf { it.isConnected() } + if (callback == null) { EversenseLogger.warning(TAG, "Cannot read signal strength — not connected"); return } + val store = callback.operationStore() + try { + // Routed through bleExecutor (like every other write path) so this can't race a + // concurrently in-flight write from the Keep Alive sync cycle. + val future = callback.submitToExecutor(readyOnly = true) { + store.contains(StorageKeys.STATE) // Reject an operation captured before a link change. + if (callback.is365()) { + val response = callback.writePacket(GetSignalStrengthPacket()) + response.signalStrength + } else { + val response = callback.writePacket(GetSignalStrengthRawPacket()) + EversenseLogger.debug(TAG) { "E3 signal raw: ${response.rawValue} -> ${response.signalStrength}%" } + response.signalStrength + } + } + val signalStrength = await(future, 20_000) + val stateJson = store.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + state.sensorSignalStrength = signalStrength + store.edit { putString(StorageKeys.STATE, JSON.encodeToString(state)) } + EversenseLogger.debug(TAG) { "Signal strength: $signalStrength%" } + watchersFor(callback.session).forEach { it.onStateChanged(state) } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "readSignalStrength failed: $e") + callback.readRssi() + } + } + + private fun await(future: java.util.concurrent.Future, timeoutMs: Long): T = try { + future.get(timeoutMs, java.util.concurrent.TimeUnit.MILLISECONDS) + } catch (e: Exception) { + future.cancel(true) + if (e is InterruptedException) Thread.currentThread().interrupt() + throw e + } + + fun readRssi() { + activeCallback?.readRssi() + } + + companion object { + private const val TAG = "EversenseCGMManager" + private val JSON = Json { ignoreUnknownKeys = true } + + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/EversenseGattCallback.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/EversenseGattCallback.kt new file mode 100644 index 000000000000..d463ad59b93f --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/EversenseGattCallback.kt @@ -0,0 +1,701 @@ +package app.aaps.plugins.eversense + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCallback +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothGattService +import android.bluetooth.BluetoothProfile +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import app.aaps.plugins.eversense.connection.PacketExchange +import app.aaps.plugins.eversense.connection.SessionStore +import app.aaps.plugins.eversense.enums.EversenseAlarm +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.exceptions.EversenseWriteException +import app.aaps.plugins.eversense.packets.Eversense365Communicator +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.EversenseE3Communicator +import app.aaps.plugins.eversense.packets.e3.EversenseE3Packets +import app.aaps.plugins.eversense.packets.e3.SaveBondingInformationPacket +import app.aaps.plugins.eversense.packets.e365.AuthIdentityPacket +import app.aaps.plugins.eversense.packets.e365.AuthStartPacket +import app.aaps.plugins.eversense.packets.e365.AuthWhoAmIPacket +import app.aaps.plugins.eversense.packets.e365.Eversense365Packets +import app.aaps.plugins.eversense.packets.e365.KeepAlivePacket +import app.aaps.plugins.eversense.packets.e365.PushAlarmWithDataPacket +import app.aaps.plugins.eversense.protocol.NotificationAssembler +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.storage.edit +import app.aaps.plugins.eversense.util.EversenseCrypto365Util +import app.aaps.plugins.eversense.util.EversenseHttp365Util +import app.aaps.plugins.eversense.util.EversenseLogger +import app.aaps.plugins.eversense.util.StorageKeys +import java.util.UUID +import java.util.concurrent.ExecutionException +import java.util.concurrent.Executors +import java.util.concurrent.Future +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException +import java.util.concurrent.atomic.AtomicReference +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock + +class EversenseGattCallback internal constructor( + private val plugin: EversenseCGMPlugin, + private val sessionStore: SessionStore, + internal val session: Long +) : BluetoothGattCallback() { + + @Volatile private var closed = false + private val writeLock = ReentrantLock() + @Volatile private var linkGeneration = 0L + private val workGeneration = ThreadLocal() + internal val stateStore get() = sessionStore.restrict { + workGeneration.get()?.let { it == linkGeneration } ?: true + } + private val preferences get() = stateStore + internal fun operationStore(): EversenseStore { + val generation = linkGeneration + return sessionStore.restrict { generation == linkGeneration } + } + private fun active() = !closed && plugin.sessionActive(session) && + (workGeneration.get()?.let { it == linkGeneration } ?: true) + private fun accepts(gatt: BluetoothGatt?) = active() && gatt != null && (bluetoothGatt == null || bluetoothGatt === gatt) + + companion object { + private const val TAG = "EversenseGattCallback" + + const val serviceUUID = "c3230001-9308-47ae-ac12-3d030892a211" + + private const val requestUUID = "6eb0f021-a7ba-7e7d-66c9-6d813f01d273" + private const val requestSecureV2UUID = "c3230002-9308-47ae-ac12-3d030892a211" + + private const val responseUUID = "6eb0f024-bd60-7aaa-25a7-0029573f4f23" + private const val responseSecureV2UUID = "c3230003-9308-47ae-ac12-3d030892a211" + private const val magicDescriptorUUID = "00002902-0000-1000-8000-00805f9b34fb" + + private const val WRITE_TIMEOUT_MS = 5000L + + } + + // FIX 1: Dedicated BLE executor for callbacks; separate network executor for HTTP calls + // so that network operations in authV2flow() cannot block BLE processing. + private var bleExecutor = Executors.newSingleThreadExecutor() + private var networkExecutor = Executors.newSingleThreadExecutor() + + private val handler = Handler(Looper.getMainLooper()) + @Volatile private var bluetoothGatt: BluetoothGatt? = null + private var eversenseBluetoothService: BluetoothGattService? = null + private var requestCharacteristic: BluetoothGattCharacteristic? = null + private var responseCharacteristic: BluetoothGattCharacteristic? = null + + private var payloadSize: Int = 20 + private var security: EversenseSecurityType = EversenseSecurityType.None + private var cryptoUtil = EversenseCrypto365Util(preferences) + + private val notifications = NotificationAssembler(SystemClock::elapsedRealtime) { notice -> + when (notice) { + NotificationAssembler.Notice.DUPLICATE -> + EversenseLogger.debug(TAG) { "Duplicate notification ignored" } + else -> EversenseLogger.warning(TAG, "Notification assembly: $notice") + } + } + + private val currentExchange = AtomicReference?>(null) + + // FIX 3: Track connection state with a dedicated flag rather than relying on bluetoothGatt + // being non-null, which is not a reliable indicator of actual connection state. + @Volatile + private var connected: Boolean = false + @Volatile private var transmitterReady: Boolean = false + + fun isConnected(): Boolean = connected && transmitterReady + fun isBleConnected(): Boolean = connected + fun is365(): Boolean = security == EversenseSecurityType.SecureV2 + + // Submit a task to the bleExecutor and return a Future so callers can block until complete. + // This ensures calibration and other ad-hoc BLE operations are serialised with Keep Alive + // cycles and do not race with currentPacket assignment. + fun submitToExecutor(readyOnly: Boolean = false, task: () -> R): Future { + val generation = linkGeneration + return try { bleExecutor.submit { + workGeneration.set(generation) + try { + check(active() && (!readyOnly || isConnected())) { "Eversense session is not ready" } + task() + } finally { workGeneration.remove() } + } } catch (e: java.util.concurrent.RejectedExecutionException) { + java.util.concurrent.CompletableFuture.failedFuture(e) + } + } + + fun hasGatt() = bluetoothGatt != null + + @SuppressLint("MissingPermission") + fun reuse(): Boolean { + if (!active()) return false + notifications.reset() + return bluetoothGatt?.connect() == true + } + + @SuppressLint("MissingPermission") + fun closeSession() { + closed = true + connected = false + transmitterReady = false + handler.removeCallbacksAndMessages(null) + currentExchange.getAndSet(null)?.fail(EversenseWriteException("Session closed")) + val old = bluetoothGatt + bluetoothGatt = null + try { + try { old?.disconnect() } catch (_: SecurityException) { } + try { old?.close() } catch (_: SecurityException) { } + } finally { + bleExecutor.shutdownNow().forEach { (it as? Future<*>)?.cancel(false) } + networkExecutor.shutdownNow().forEach { (it as? Future<*>)?.cancel(false) } + } + } + + fun disconnectAndScheduleReconnect() { + if (active()) plugin.sessionDisconnected(session, BluetoothGatt.GATT_SUCCESS) + } + + /** Owns even a GATT handle which never reaches STATE_CONNECTED. */ + @SuppressLint("MissingPermission") + fun attachGatt(gatt: BluetoothGatt?) { + if (gatt == null) return + if (!active()) { gatt.close(); return } + bluetoothGatt?.takeIf { it !== gatt }?.let { + EversenseLogger.info(TAG, "Closing an earlier GATT handle before using the new one") + it.disconnect() + it.close() + } + bluetoothGatt = gatt + } + @SuppressLint("MissingPermission") + fun readRssi() { + bluetoothGatt?.readRemoteRssi() ?: EversenseLogger.warning(TAG, "Cannot read RSSI — not connected") + } + + @SuppressLint("MissingPermission") + override fun onReadRemoteRssi(gatt: BluetoothGatt, rssi: Int, status: Int) = plugin.deliver(session) { handleOnReadRemoteRssi(gatt, rssi, status) } + + private fun handleOnReadRemoteRssi(gatt: BluetoothGatt, rssi: Int, status: Int) { + if (!accepts(gatt)) return + if (status == BluetoothGatt.GATT_SUCCESS) { + EversenseLogger.debug(TAG) { "RSSI: $rssi dBm" } + plugin.onRssiRead(rssi, session) + } else { + EversenseLogger.warning(TAG, "Failed to read RSSI - status: $status") + } + } + + @SuppressLint("MissingPermission") + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) = plugin.deliver(session) { handleOnConnectionStateChange(gatt, status, newState) } + + private fun handleOnConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { + if (!accepts(gatt)) return + EversenseLogger.info(TAG, "Connection state changed - status: $status, newState: $newState") + EversenseLogger.debug(TAG) { "Connected device: ${gatt.device.name}" } + + if (status == BluetoothGatt.GATT_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) { + bluetoothGatt = gatt + // FIX 3: Set connected flag on confirmed STATE_CONNECTED. + connected = true + + preferences.edit(commit = true) { + putString(StorageKeys.REMOTE_DEVICE_KEY, gatt.device.address) + } + + // FIX 5: Both connect and disconnect watcher notifications are now dispatched via + // handler.post() so they always arrive on the main thread, preventing UI thread crashes. + handler.post { + plugin.watchersFor(this.session).forEach { it.onConnectionChanged(true) } + } + + if (!gatt.requestMtu(512)) { + EversenseLogger.warning(TAG, "requestMtu returned false — skipping to discoverServices with default payload size") + payloadSize = 20 + gatt.discoverServices() + } + return + } + + if (newState == BluetoothProfile.STATE_DISCONNECTED || status != BluetoothGatt.GATT_SUCCESS) { + EversenseLogger.warning(TAG, "Disconnected or failed - status: $status, newState: $newState") + + connected = false + transmitterReady = false + linkGeneration++ + currentExchange.getAndSet(null)?.fail(EversenseWriteException("Link interrupted")) + // The controller owns retries. A normal 365 cycle keeps its GATT/bond. + val reuse = status == 19 && is365() + plugin.sessionDisconnected(session, status, reuse) + handler.post { plugin.watchersFor(this.session).forEach { it.onConnectionChanged(false) } } + + plugin.placementChanged(session, status, is365()) + + } + } + + @SuppressLint("MissingPermission") + override fun onMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) = plugin.deliver(session) { handleOnMtuChanged(gatt, mtu, status) } + + private fun handleOnMtuChanged(gatt: BluetoothGatt?, mtu: Int, status: Int) { + if (!accepts(gatt)) return + if (status != 0) { + EversenseLogger.warning(TAG, "MTU negotiation failed (status: $status) — using default payload size of 20") + payloadSize = 20 + } else { + payloadSize = mtu - 3 + } + EversenseLogger.debug(TAG) { "New payload size: $payloadSize" } + + val success = gatt?.discoverServices() + EversenseLogger.info(TAG, "Trigger discover services - success: $success") + } + + @SuppressLint("MissingPermission") + override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) = plugin.deliver(session) { handleOnServicesDiscovered(gatt, status) } + + private fun handleOnServicesDiscovered(gatt: BluetoothGatt?, status: Int) { + if (!accepts(gatt)) return + EversenseLogger.info(TAG, "Discovered services - status: $status") + + if (gatt == null) { + EversenseLogger.error(TAG, "Gatt is null") + return + } + + // FIX 6: Use firstOrNull instead of first. The original code used .first {} which throws + // NoSuchElementException if the service is missing. The null check below it was dead code + // that could never be reached. firstOrNull correctly returns null on no match. + val service = gatt.services.firstOrNull { it.uuid.toString() == serviceUUID } + if (service == null) { + EversenseLogger.error(TAG, "Required service not found -> disconnecting") + gatt.disconnect() + return + } + + eversenseBluetoothService = service + if (service.characteristics.isEmpty()) { + EversenseLogger.error(TAG, "Service has no characteristics -> disconnecting") + gatt.disconnect() + return + } + + var requestChar = service.characteristics.find { it.uuid.toString() == requestUUID } + var responseChar = service.characteristics.find { it.uuid.toString() == responseUUID } + if (requestChar != null && responseChar != null) { + EversenseLogger.info(TAG, "Connected to Eversense E3!") + security = EversenseSecurityType.None + requestCharacteristic = requestChar + responseCharacteristic = responseChar + + gatt.setCharacteristicNotification(requestChar, true) + gatt.setCharacteristicNotification(responseChar, true) + enableNotify(gatt, responseChar) + return + } + + requestChar = service.characteristics.find { it.uuid.toString() == requestSecureV2UUID } + responseChar = service.characteristics.find { it.uuid.toString() == responseSecureV2UUID } + if (requestChar == null || responseChar == null) { + EversenseLogger.error(TAG, "No Eversense request/response characteristic found -> disconnecting") + gatt.disconnect() + return + } + + EversenseLogger.info(TAG, "Connected to Eversense 365!") + security = EversenseSecurityType.SecureV2 + requestCharacteristic = requestChar + responseCharacteristic = responseChar + + gatt.setCharacteristicNotification(requestChar, true) + gatt.setCharacteristicNotification(responseChar, true) + enableNotify(gatt, responseChar) + } + + override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) = plugin.deliver(session) { handleOnDescriptorWrite(gatt, descriptor, status) } + + private fun handleOnDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { + if (!accepts(gatt)) return + EversenseLogger.debug(TAG) { "onDescriptorWrite (${descriptor.uuid}) for characteristic (${descriptor.characteristic.uuid}) - status $status" } + + if (status == BluetoothGatt.GATT_SUCCESS && descriptor.uuid.toString() == magicDescriptorUUID) { + if (descriptor.characteristic.uuid.toString() == responseUUID) { + submitToExecutor { authE3flow() } + } else if (descriptor.characteristic.uuid.toString() == responseSecureV2UUID) { + submitToExecutor { authV2flow() } + } + } + } + + // FIX 7: Override both the deprecated and current API 33+ signature of onCharacteristicChanged. + // On Android 13+ (API 33+) the old single-argument override is never called by the system — + // only the new three-argument version is. Without this override, glucose data would be silently + // dropped on API 33+ devices. Both delegates to a shared handler to avoid code duplication. + @SuppressLint("MissingPermission") + @OptIn(ExperimentalStdlibApi::class) + override fun onCharacteristicChanged( + gatt: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + value: ByteArray + ) = plugin.deliver(session) { handleOnCharacteristicChanged(gatt, characteristic, value) } + + private fun handleOnCharacteristicChanged( + gatt: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + value: ByteArray + ) { + if (!accepts(gatt)) return + handleCharacteristicChanged(gatt, value) + } + + @Deprecated("Deprecated in API 33 — overridden for compatibility with Android < 13") + @SuppressLint("MissingPermission") + @OptIn(ExperimentalStdlibApi::class) + @Suppress("DEPRECATION") + override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) = plugin.deliver(session) { handleOnCharacteristicChanged(gatt, characteristic) } + + private fun handleOnCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { + if (!accepts(gatt)) return + handleCharacteristicChanged(gatt, characteristic.value) + } + + @SuppressLint("MissingPermission") + @OptIn(ExperimentalStdlibApi::class) + private fun handleCharacteristicChanged(gatt: BluetoothGatt, rawData: ByteArray) { + if (!accepts(gatt)) return + EversenseLogger.debug(TAG) { "Received data: ${rawData.toHexString()}" } + + if (rawData.isEmpty()) return + var data = rawData + if (security == EversenseSecurityType.SecureV2) { + data = notifications.accept(rawData) ?: return + + if (data[0] != Eversense365Packets.AuthenticateResponseId) { + data = cryptoUtil.decrypt(data) + EversenseLogger.debug(TAG) { "Decrypted data -> ${data.toHexString()}" } + if (data.isEmpty()) { + // A decrypt/MAC failure means the session key no longer matches the + // transmitter, so retrying the shortcut is guaranteed to fail the same way. + // Force a full WhoAmI + DMS re-auth on the next connect, so we recover on the + // first retry instead of waiting out SHORTCUT_FAIL_THRESHOLD auth timeouts. + if (plugin.hasInternet()) { + EversenseLogger.error(TAG, "Failed to decrypt data — requesting full re-auth on next connect") + cryptoUtil.disallowUseShortcut() + } else { + EversenseLogger.warning(TAG, "Failed to decrypt data offline — retaining registered identity for a new local handshake") + } + disconnectAndScheduleReconnect() + return + } + } + } + + if (!is365() && EversenseE3Packets.isPushPacket(data[0])) { + EversenseLogger.debug(TAG) { "Keep Alive packet received (E3)!" } + submitToExecutor { + // Sync transmitter clock before reading glucose so the glucose timestamp + // reflects phone time, not the drifted transmitter clock. The official app + // always calls postCurrentDateTimeRequest before postReadSensorGlucose. + try { + val currentDatetime = writePacket( + app.aaps.plugins.eversense.packets.e3.GetCurrentDatetimePacket() + ) + if (currentDatetime.needsTimeSync) { + EversenseLogger.info(TAG, "Clock drift detected before glucose read — syncing transmitter clock") + writePacket( + app.aaps.plugins.eversense.packets.e3.SetCurrentDatetimePacket() + ) + } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Pre-glucose clock sync failed (non-fatal): $e") + } + EversenseE3Communicator.readGlucose(this, preferences, plugin.watchersFor(this.session)) + EversenseE3Communicator.fullSync(this, preferences, plugin.watchersFor(this.session)) + } + return + } + + if (data.size >= 2 && Eversense365Packets.isKeepAlivePacket(data[0], data[1])) { + EversenseLogger.debug(TAG) { "Keep Alive packet received (365)!" } + + val packet = KeepAlivePacket() + packet.appendData(data.toUByteArray()) + val response = packet.parseResponse() ?: return + + val fourHalfMinAgo = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(270) + submitToExecutor { + if (response.glucoseDatetime > fourHalfMinAgo) { + Eversense365Communicator.readGlucose(this, preferences, plugin.watchersFor(this.session)) + Eversense365Communicator.fullSync(this, preferences, plugin.watchersFor(this.session)) + } + } + return + } else if (data.size >= 2 && data[0] == Eversense365Packets.NotificationResponseId && data[1] == Eversense365Packets.NotificationAlarmWithData) { + // Push alarm notification. Delegate to PushAlarmWithDataPacket (see its own doc comment + // for the empirically-confirmed byte layout) instead of duplicating the parsing inline, + // matching how KeepAlivePacket is already handled a few lines above. + val packet = PushAlarmWithDataPacket() + packet.appendData(data.toUByteArray()) + val response = packet.parseResponse() ?: run { + EversenseLogger.warning(TAG, "Push alarm packet too short -> skipping") + return + } + if (response.alarm.code == EversenseAlarm.UNKNOWN) { + // Unrecognized/bogus codes (e.g. the removed TxDocked/TxUndocked 68/69) must not + // surface as a real alarm - matches the upstream iOS EversenseKit fix. + EversenseLogger.warning(TAG, "Received unknown push alarm code: ${response.alarm.codeRaw}") + return + } + EversenseLogger.info(TAG, "Push alarm received: ${response.alarm.code.title}") + handler.post { + plugin.watchersFor(this.session).forEach { it.onAlarmReceived(response.alarm) } + } + return + } else if (Eversense365Packets.isNotificationPacket(data[0])) { + EversenseLogger.warning(TAG, "Unknown notification packet received") + return + } + + val exchange = currentExchange.get() ?: run { + EversenseLogger.warning(TAG, "currentPacket is null -> skipping packet") + return + } + + val packet = exchange.packet + synchronized(packet) { + val spec = packet.spec + + // SecureV2 rejects a command with [0xff, command type, error code]. + // Complete the matching exchange as rejected, rather than timing out and + // tearing down an authenticated link (observed: ff 0e 05 for SetAppVersion). + if (security == EversenseSecurityType.SecureV2 && + data.size == 3 && data[0] == 0xff.toByte() && + data[1] == spec.typeId + ) { + EversenseLogger.warning(TAG, "365 command rejected - type: ${data[1].toInt() and 0xff}, error: ${data[2].toInt() and 0xff}") + packet.isErrorResponse = true + exchange.complete() + return + } + + // Only treat 0x80 as an error if it is NOT the expected response ID for this packet. + // ReadSingleByteSerialFlashRegister responses legitimately use 0xAA (170) as their + // response ID — but earlier versions of this code checked 0x80 before checking the + // expected response ID, causing every battery/readiness/calibration read to fail. + if (EversenseE3Packets.isErrorPacket(data[0]) && spec.responseId != data[0]) { + EversenseLogger.error(TAG, "Transmitter returned an error response") + EversenseLogger.debug(TAG) { "Error response data: ${data.toHexString()}" } + packet.isErrorResponse = true + exchange.complete() + return + } + + if (security == EversenseSecurityType.None) { + if (!packet.skipResponseIdValidation && spec.responseId != data[0]) { + EversenseLogger.warning(TAG, "Incorrect responseId - expected: ${spec.responseId}, got: ${data[0]}") + return + } + packet.appendData(data.toUByteArray()) + exchange.complete() + } else { + if (spec.responseId != data[0]) { + EversenseLogger.warning(TAG, "Incorrect responseId - expected: ${spec.responseId}, got: ${data[0]}") + return + } + if (data.size < 2 || spec.typeId != data[1]) { + EversenseLogger.warning(TAG, "Incorrect responseType - expected: ${spec.typeId}, got: ${data.getOrNull(1)}") + return + } + packet.appendData(data.toUByteArray()) + exchange.complete() + } + } + } + + @Suppress("UNCHECKED_CAST", "DEPRECATION") + @SuppressLint("MissingPermission") + fun writePacket(packet: EversenseBasePacket, timeoutMs: Long = WRITE_TIMEOUT_MS): T = writeLock.withLock { + if (!active() || Thread.currentThread().isInterrupted) throw EversenseWriteException("Session closed") + val gatt = bluetoothGatt ?: throw EversenseWriteException("GATT is not connected") + val characteristic = requestCharacteristic ?: throw EversenseWriteException("Request characteristic is missing") + val request = packet.buildRequest(cryptoUtil, payloadSize) ?: throw EversenseWriteException("Cannot build packet") + val exchange = PacketExchange(packet) + try { + var accepted = false + // Register and send under the lifecycle lock: stop either rejects this send or + // observes its exchange and wakes the waiter. Never register after teardown. + plugin.deliver(session) { + if (active()) { + currentExchange.set(exchange) + characteristic.value = request + accepted = gatt.writeCharacteristic(characteristic) + } + } + if (!accepted) throw EversenseWriteException("BLE write was rejected or session closed") + exchange.await(timeoutMs) + if (!active()) throw EversenseWriteException("Session ended during write") + if (packet.isErrorResponse) throw EversenseWriteException("Transmitter rejected the packet") + packet.parseResponse() as? T ?: throw EversenseWriteException("Invalid packet response") + } catch (e: TimeoutException) { + // Do not let a late reply be consumed by the next command on the same link. + if (active()) plugin.sessionDisconnected(session, -1) + throw EversenseWriteException("Packet response timed out after ${timeoutMs}ms") + } catch (e: InterruptedException) { + if (active()) plugin.sessionDisconnected(session, -1) + Thread.currentThread().interrupt() + throw EversenseWriteException("Packet write was interrupted") + } catch (e: ExecutionException) { + throw EversenseWriteException("Packet exchange ended: ${e.cause}") + } finally { + currentExchange.compareAndSet(exchange, null) + } + } + + private fun authE3flow() { + EversenseLogger.info(TAG, "Starting auth flow E3...") + try { + writePacket(SaveBondingInformationPacket()) + } catch (exception: Exception) { + if (!active()) return + EversenseLogger.error(TAG, "Auth flow E3 failed: $exception") + return + } + + EversenseLogger.info(TAG, "E3 auth complete — notifying watchers") + // fullSync is triggered by onConnectionChanged via triggerFullSync on the bleExecutor. + // Do NOT call fullSync here — it would race with the triggerFullSync call. + if (!active()) return + transmitterReady = true + plugin.sessionReady(this.session) + handler.post { plugin.watchersFor(this.session).forEach { it.onTransmitterReady() } } + } + + @SuppressLint("MissingPermission") + private fun authV2flow() { + var shortcutAttempt = false + val generation = linkGeneration + val networkStore = stateStore.restrict { generation == linkGeneration } + // FIX 9: Network calls (login, getFleetSecretV2) are dispatched to a separate networkExecutor + // so they do not block the bleExecutor, which must remain available for BLE callbacks. + try { + shortcutAttempt = cryptoUtil.canUseShortcut() + if (!cryptoUtil.generateKeyPairIfNotExists()) { + bluetoothGatt?.disconnect() + return + } + + if (!cryptoUtil.canUseShortcut()) { + if (!plugin.hasInternet()) { + EversenseLogger.warning(TAG, "365 registration requires internet; retaining stored identity and retrying later") + disconnectAndScheduleReconnect() + return + } + val clientId = cryptoUtil.getClientId() + val whoAmI = writePacket(AuthWhoAmIPacket(clientId)) + + // HTTP results carry the same link generation as the authentication attempt. + val authSession = networkExecutor.submit { + EversenseHttp365Util.login(networkStore) + }.get(65, TimeUnit.SECONDS) ?: run { + bluetoothGatt?.disconnect() + return + } + + authSession as? EversenseHttp365Util.LoginResponseModel ?: run { + bluetoothGatt?.disconnect() + return + } + + // Cache access token so it can be used for cloud uploads without re-login + val expiryMs = System.currentTimeMillis() + (authSession.expires_in * 1000L) + preferences.edit().putString(StorageKeys.ACCESS_TOKEN, authSession.access_token) + .putLong(StorageKeys.ACCESS_TOKEN_EXPIRY, expiryMs).apply() + + val fleet = networkExecutor.submit { + EversenseHttp365Util.getFleetSecretV2( + preferences = networkStore, + accessToken = authSession.access_token, + serialNumber = whoAmI.serialNumber, + nonce = whoAmI.nonce, + flags = whoAmI.flags, + publicKey = cryptoUtil.getClientPublicKey() + ) + }.get(65, TimeUnit.SECONDS) ?: run { + bluetoothGatt?.disconnect() + return + } + + val fleetResponse = fleet as? EversenseHttp365Util.FleetSecretV2ResponseModel ?: run { + bluetoothGatt?.disconnect() + return + } + + @OptIn(ExperimentalStdlibApi::class) + writePacket( + AuthIdentityPacket(fleetResponse.Result.Certificate?.hexToByteArray() ?: byteArrayOf()) + ) + + cryptoUtil.allowUseShortcut() + } + + val signature = cryptoUtil.generateEphem() ?: run { + bluetoothGatt?.disconnect() + return + } + + val session = writePacket(AuthStartPacket(cryptoUtil.getStartSecret(signature))) + cryptoUtil.generateSessionKey(session.sessionPublicKey) + + if (!active()) return + // Auth succeeded — reset both fail counters + plugin.authenticationSucceeded(this.session) + + EversenseLogger.info(TAG, "365 auth complete — ready for full sync") + Eversense365Communicator.fullSync(this, preferences, plugin.watchersFor(this.session), force = true) + // Read glucose immediately after auth so readings don't wait for next Keep Alive + // This prevents late readings after reconnect from fullSync disconnect fix + try { + Eversense365Communicator.readGlucose(this, preferences, plugin.watchersFor(this.session)) + } catch (e: Exception) { + EversenseLogger.warning(TAG, "[365] readGlucose after auth failed (non-fatal): $e") + } + EversenseLogger.info(TAG, "365 transmitter ready — notifying watchers") + if (!active()) return + transmitterReady = true + plugin.sessionReady(this.session) + // Attempt finished successfully; release the in-progress guard. + handler.post { plugin.watchersFor(this.session).forEach { it.onTransmitterReady() } } + + } catch (exception: Exception) { + if (generation != linkGeneration) return + plugin.authenticationFailed(this.session, shortcutAttempt) + if (!active()) return + EversenseLogger.error(TAG, "[365] authV2 failed: $exception") + EversenseLogger.debug(TAG) { exception.stackTraceToString() } + + bluetoothGatt?.disconnect() + } + } + + // FIX 10: enableNotify uses the API 33+ writeDescriptor(descriptor, value) overload when + // available, falling back to the deprecated setValue approach on older API levels. + @SuppressLint("MissingPermission") + @Suppress("DEPRECATION") + private fun enableNotify(gatt: BluetoothGatt, responseCharacteristic: BluetoothGattCharacteristic) { + val descriptor = responseCharacteristic.getDescriptor(UUID.fromString(magicDescriptorUUID)) ?: return + + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) { + gatt.writeDescriptor(descriptor, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) + } else { + descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + gatt.writeDescriptor(descriptor) + } + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/callbacks/EversenseScanCallback.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/callbacks/EversenseScanCallback.kt new file mode 100644 index 000000000000..11fe60053483 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/callbacks/EversenseScanCallback.kt @@ -0,0 +1,7 @@ +package app.aaps.plugins.eversense.callbacks + +import app.aaps.plugins.eversense.models.EversenseScanResult + +interface EversenseScanCallback { + fun onResult(var0: EversenseScanResult) +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/callbacks/EversenseWatcher.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/callbacks/EversenseWatcher.kt new file mode 100644 index 000000000000..aea1b63ce81b --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/callbacks/EversenseWatcher.kt @@ -0,0 +1,15 @@ +package app.aaps.plugins.eversense.callbacks + +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState + +interface EversenseWatcher { + fun onCGMRead(type: EversenseType, readings: List) + fun onStateChanged(state: EversenseState) + fun onConnectionChanged(connected: Boolean) + fun onAlarmReceived(alarm: ActiveAlarm) {} + fun onTransmitterNotPlaced() {} + fun onTransmitterReady() {} +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/EversenseConnectionController.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/EversenseConnectionController.kt new file mode 100644 index 000000000000..1482fa18e6ef --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/EversenseConnectionController.kt @@ -0,0 +1,174 @@ +package app.aaps.plugins.eversense.connection + +import java.util.concurrent.CancellationException + +/** Owns connection intent, one retry, the attempt deadline and the data watchdog. */ +internal class EversenseConnectionController( + private val scheduler: Scheduler, + private val now: () -> Long, + private val transport: Transport +) { + interface Scheduler { + fun after(delayMs: Long, action: () -> Unit): Task + } + fun interface Task { fun cancel() } + interface Transport { + fun open(session: Long): Boolean + fun reuse(session: Long): Boolean + fun close() + } + enum class State { STOPPED, PAUSED, DISCONNECTED, CONNECTING, READY } + + private val lock = Any() + private var running = false + private var wanted = false + private var cloudGeneration = 0L + private var session = 0L + private var attempts = 0 + private var lastData = 0L + private var retry: Task? = null + private var deadline: Task? = null + private var watchdog: Task? = null + @Volatile var state = State.STOPPED + private set + + fun start(autoConnect: Boolean = true) = synchronized(lock) { + if (running) return@synchronized + running = true + wanted = autoConnect + if (wanted) attempt(false) else state = State.PAUSED + } + + fun stop() = synchronized(lock) { + running = false + wanted = false + invalidate(State.STOPPED) + } + + fun disconnect() = synchronized(lock) { + wanted = false + invalidate(if (running) State.PAUSED else State.STOPPED) + } + + fun connect(force: Boolean = false): Boolean = synchronized(lock) { + if (!running) return@synchronized false + wanted = true + if (!force && state == State.READY) return@synchronized true + if (!force && state == State.CONNECTING) return@synchronized false + attempt(false) + } + + fun bluetoothAvailable() = synchronized(lock) { + if (running && wanted) attempt(false) + } + + fun owns(token: Long): Boolean = synchronized(lock) { running && wanted && token == session } + fun active(token: Long): Boolean = synchronized(lock) { owns(token) && (state == State.CONNECTING || state == State.READY) } + + fun deliver(token: Long, action: () -> Unit) = synchronized(lock) { + if (active(token)) action() + } + + fun whileOwned(token: Long, action: () -> Unit) = synchronized(lock) { + if (owns(token)) action() + } + + fun cloudStore(delegate: app.aaps.plugins.eversense.storage.EversenseStore): app.aaps.plugins.eversense.storage.EversenseStore? = synchronized(lock) { + if (!running || !wanted) null else SessionStore(this, cloudGeneration, delegate, cloud = true) + } + + fun withCloudSession(token: Long, action: () -> T): T = synchronized(lock) { + if (!running || !wanted || token != cloudGeneration) throw CancellationException("Eversense cloud session has ended") + action() + } + + fun withSession(token: Long, action: () -> T): T = synchronized(lock) { + if (!active(token)) throw CancellationException("Eversense session has ended") + action() + } + + fun ready(token: Long) = synchronized(lock) { + if (!active(token)) return@synchronized + state = State.READY + attempts = 0 + lastData = now() + deadline?.cancel(); deadline = null + scheduleWatchdog(token) + } + + fun dataReceived(token: Long) = synchronized(lock) { + if (active(token)) lastData = now() + } + + fun disconnected(token: Long, status: Int, reuse: Boolean = false) = synchronized(lock) { + if (!active(token)) return@synchronized + state = State.DISCONNECTED + deadline?.cancel(); deadline = null + watchdog?.cancel(); watchdog = null + if (!reuse) transport.close() + scheduleRetry(if (status == 19 && !reuse) 30_000L else backoff(), reuse) + } + + private fun attempt(reuse: Boolean): Boolean { + retry?.cancel(); retry = null + deadline?.cancel(); deadline = null + watchdog?.cancel(); watchdog = null + if (!reuse) { + session++ // Invalidate callbacks and queued work before closing the old client. + transport.close() + } + state = State.CONNECTING + val token = session + val accepted = try { + if (reuse) transport.reuse(token) else transport.open(token) + } catch (_: SecurityException) { + false + } + if (!accepted) { + state = State.DISCONNECTED + transport.close() + scheduleRetry(60_000L, false) + } else if (state == State.CONNECTING && active(token)) { + deadline = scheduler.after(180_000L) { + synchronized(lock) { + if (active(token) && state == State.CONNECTING) disconnected(token, -1) + } + } + } + return accepted + } + + private fun backoff(): Long = minOf(5_000L * (1L shl minOf(attempts++, 4)), 60_000L) + + private fun scheduleRetry(delay: Long, reuse: Boolean) { + retry?.cancel() + val token = session + retry = scheduler.after(delay) { + synchronized(lock) { + if (owns(token) && state == State.DISCONNECTED) attempt(reuse) + } + } + } + + private fun scheduleWatchdog(token: Long) { + watchdog?.cancel() + watchdog = scheduler.after(60_000L) { + synchronized(lock) { + if (!active(token) || state != State.READY) return@synchronized + if (now() - lastData > 7 * 60_000L) attempt(false) + else scheduleWatchdog(token) + } + } + } + + private fun invalidate(next: State) { + cloudGeneration++ + session++ + state = next + retry?.cancel(); retry = null + deadline?.cancel(); deadline = null + watchdog?.cancel(); watchdog = null + attempts = 0 + transport.close() + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/HandlerConnectionScheduler.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/HandlerConnectionScheduler.kt new file mode 100644 index 000000000000..eef385499f94 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/HandlerConnectionScheduler.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.eversense.connection + +import android.os.Handler +import android.os.Looper + +internal class HandlerConnectionScheduler : EversenseConnectionController.Scheduler { + private val handler = Handler(Looper.getMainLooper()) + override fun after(delayMs: Long, action: () -> Unit): EversenseConnectionController.Task { + val task = Runnable { action() } + handler.postDelayed(task, delayMs) + return EversenseConnectionController.Task { handler.removeCallbacks(task) } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/PacketExchange.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/PacketExchange.kt new file mode 100644 index 000000000000..65256decd7b7 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/PacketExchange.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.eversense.connection + +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit + +/** Completion is retained even when the response arrives before the sender starts waiting. */ +internal class PacketExchange(val packet: T) { + private val response = CompletableFuture() + fun complete() = response.complete(packet) + fun fail(error: Throwable) = response.completeExceptionally(error) + fun await(timeoutMs: Long): T = response.get(timeoutMs, TimeUnit.MILLISECONDS) +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/SessionStore.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/SessionStore.kt new file mode 100644 index 000000000000..2d9393a2ef20 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/connection/SessionStore.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.eversense.connection + +import app.aaps.plugins.eversense.storage.EversenseStore + +/** Rejects state writes from HTTP/BLE work belonging to a closed session. */ +internal class SessionStore( + private val controller: EversenseConnectionController, + private val session: Long, + private val delegate: EversenseStore, + private val valid: () -> Boolean = { true }, + private val cloud: Boolean = false +) : EversenseStore { + fun restrict(valid: () -> Boolean) = SessionStore(controller, session, this, valid, cloud) + + private fun guard(action: () -> T): T { + val checked = { + if (!valid()) throw java.util.concurrent.CancellationException("Eversense link has ended") + action() + } + return if (cloud) controller.withCloudSession(session, checked) else controller.withSession(session, checked) + } + + override fun getString(key: String, defaultValue: String?) = guard { delegate.getString(key, defaultValue) } + override fun getLong(key: String, defaultValue: Long) = guard { delegate.getLong(key, defaultValue) } + override fun getInt(key: String, defaultValue: Int) = guard { delegate.getInt(key, defaultValue) } + override fun getBoolean(key: String, defaultValue: Boolean) = guard { delegate.getBoolean(key, defaultValue) } + override fun contains(key: String) = guard { delegate.contains(key) } + override fun edit(): EversenseStore.Editor { + val editor = guard { delegate.edit() } + return object : EversenseStore.Editor { + override fun putString(key: String, value: String?) = apply { editor.putString(key, value) } + override fun putLong(key: String, value: Long) = apply { editor.putLong(key, value) } + override fun putInt(key: String, value: Int) = apply { editor.putInt(key, value) } + override fun putBoolean(key: String, value: Boolean) = apply { editor.putBoolean(key, value) } + override fun remove(key: String) = apply { editor.remove(key) } + override fun clear() = apply { editor.clear() } + override fun commit(): Boolean = guard { editor.commit() } + override fun apply() { guard { editor.apply() } } + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/BatteryLevel.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/BatteryLevel.kt new file mode 100644 index 000000000000..84a9667accfa --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/BatteryLevel.kt @@ -0,0 +1,38 @@ +package app.aaps.plugins.eversense.enums + +enum class BatteryLevel(val code: Int) { + PERCENTAGE_0(0), + PERCENTAGE_5(1), + PERCENTAGE_10(2), + PERCENTAGE_25(3), + PERCENTAGE_35(4), + PERCENTAGE_45(5), + PERCENTAGE_55(6), + PERCENTAGE_65(7), + PERCENTAGE_75(8), + PERCENTAGE_85(9), + PERCENTAGE_95(10), + PERCENTAGE_100(11), + UNKNOWN(255); + + fun toPercentage(): Int = when (this) { + PERCENTAGE_0 -> 0 + PERCENTAGE_5 -> 5 + PERCENTAGE_10 -> 10 + PERCENTAGE_25 -> 25 + PERCENTAGE_35 -> 35 + PERCENTAGE_45 -> 45 + PERCENTAGE_55 -> 55 + PERCENTAGE_65 -> 65 + PERCENTAGE_75 -> 75 + PERCENTAGE_85 -> 85 + PERCENTAGE_95 -> 95 + PERCENTAGE_100 -> 100 + UNKNOWN -> -1 + } + + companion object { + fun from(code: Int): BatteryLevel = + values().firstOrNull { it.code == code } ?: UNKNOWN + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationFlag.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationFlag.kt new file mode 100644 index 000000000000..d1bbc9bb8cf0 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationFlag.kt @@ -0,0 +1,46 @@ +package app.aaps.plugins.eversense.enums + +enum class CalibrationFlag(val code: Int) { + NOT_ENTERED_FOR_CALIBRATION(0), + ACTUALLY_USED_FOR_CALIBRATION(1), + MARKED_SUSPICIOUS(2), + GLUCOSE_TOO_LOW_TO_READ(3), + GLUCOSE_TOO_HIGH_TO_READ(4), + GLUCOSE_RAPID_CHANGE(5), + INVALID_TIME(6), + INSUFFICIENT_DATA(7), + SENSOR_EOL(8), + DROPOUT_PHASE(9), + AUTO_LINK_MODE_ACTIVE(10), + SENSOR_LED_DISCONNECT(11), + OTHER_FAILURE(12), + THIS_ONE_USED_PREVIOUS_ONE_DELETED(13), + THIS_SUSPICIOUS_PREVIOUS_DELETED(14), + INSUFFICIENT_DATA_POST_FS_ENTRY(15), + UNKNOWN_FAILURE(255); + + fun getTitle(): String = when (this) { + ACTUALLY_USED_FOR_CALIBRATION, + NOT_ENTERED_FOR_CALIBRATION -> "Calibration accepted" + MARKED_SUSPICIOUS -> "Suspicious" + GLUCOSE_TOO_LOW_TO_READ -> "Glucose too low" + GLUCOSE_TOO_HIGH_TO_READ -> "Glucose too high" + GLUCOSE_RAPID_CHANGE -> "Glucose changing too fast" + INVALID_TIME -> "Invalid time" + INSUFFICIENT_DATA, + INSUFFICIENT_DATA_POST_FS_ENTRY -> "Insufficient data" + SENSOR_EOL -> "Sensor End of Life" + DROPOUT_PHASE -> "Dropout phase" + AUTO_LINK_MODE_ACTIVE -> "Autolink" + SENSOR_LED_DISCONNECT -> "Sensor disconnected" + OTHER_FAILURE -> "Other failure" + THIS_ONE_USED_PREVIOUS_ONE_DELETED, + THIS_SUSPICIOUS_PREVIOUS_DELETED -> "Previous calibration deleted" + UNKNOWN_FAILURE -> "Unknown failure" + } + + companion object { + fun from(code: Int): CalibrationFlag = + values().firstOrNull { it.code == code } ?: UNKNOWN_FAILURE + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationMode.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationMode.kt new file mode 100644 index 000000000000..362263a7a4e0 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationMode.kt @@ -0,0 +1,29 @@ +package app.aaps.plugins.eversense.enums + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +enum class CalibrationMode(private val value: Int) { + @SerialName("DAILY_SINGLE") + DAILY_SINGLE(0x01), + + @SerialName("DAILY_DUAL") + DAILY_DUAL(0x02), + + @SerialName("WEEKLY_SINGLE") + WEEKLY_SINGLE(0x03), + + @SerialName("DEFAULT") + DEFAULT(0x04); + + companion object { + fun from365(value: Int): CalibrationMode { + return when(value) { + 0 -> DAILY_SINGLE + 1 -> WEEKLY_SINGLE + else -> DEFAULT + } + } + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationPhase.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationPhase.kt new file mode 100644 index 000000000000..83284f9458b5 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationPhase.kt @@ -0,0 +1,65 @@ +package app.aaps.plugins.eversense.enums + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +enum class CalibrationPhase(private val value: Int) { + + @SerialName("WARMING_UP") + WARMING_UP(0x01), + + @SerialName("INITIALIZATION") + INITIALIZATION(0x02), + + @SerialName("DAILY_CALIBRATION") + DAILY_CALIBRATION(0x03), + + @SerialName("WEEKLY_CALIBRATION") + WEEKLY_CALIBRATION(0x08), + + @SerialName("SUSPICIOUS") + SUSPICIOUS(0x04), + + @SerialName("UNKNOWN") + UNKNOWN(0x05), + + @SerialName("DEBUG") + DEBUG(0x06), + + @SerialName("DROPOUT") + DROPOUT(0x07); + + companion object { + fun fromE3(value: Int): CalibrationPhase { + // Byte mapping from official app Utils$CAL_PHASE enum (decompiled from EU APK v7.1.1): + // 0=UNKNOWN, 1=WARM_UP, 2=INITIALIZATION, 3=DAILY_CALIBRATION, + // 4=SUSPICIOUS, 5=DROPOUT, 6=DEBUG, 7=UNDERTERMINED + return when(value) { + 1 -> WARMING_UP + 2 -> INITIALIZATION + 3 -> DAILY_CALIBRATION + 4 -> SUSPICIOUS + 5 -> DROPOUT + 6 -> DEBUG + 7 -> UNKNOWN + else -> UNKNOWN + } + } + + // phase = raw CalibrationPhase byte (ordinal from official app CAL_PHASE enum) + // calPerDay = raw NumberOfCalPerDay byte: 0 = daily, 1 = weekly + fun from365(phase: Int, calPerDay: Int = 0): CalibrationPhase { + return when(phase) { + 0 -> UNKNOWN + 1 -> WARMING_UP + 2 -> INITIALIZATION + 3 -> if (calPerDay == 1) WEEKLY_CALIBRATION else DAILY_CALIBRATION + 4 -> SUSPICIOUS + 5 -> DROPOUT + 6 -> DEBUG + else -> UNKNOWN + } + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationReadiness.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationReadiness.kt new file mode 100644 index 000000000000..4337b923b659 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CalibrationReadiness.kt @@ -0,0 +1,69 @@ +package app.aaps.plugins.eversense.enums + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +enum class CalibrationReadiness(private val value: Int) { + /** Calibration can be accepted */ + @SerialName("READY") + READY(0x00), + /** Transmitter does not have enough data to do a calibration */ + @SerialName("NOT_ENOUGH_DATA") + NOT_ENOUGH_DATA(0x01), + /** Glucose rate of change is too high to calibrate */ + @SerialName("GLUCOSE_RATE_TOO_HIGH") + GLUCOSE_RATE_TOO_HIGH(0x02), + /** A calibration has already been done in the past 2h */ + @SerialName("TOO_SOON") + TOO_SOON(0x03), + /** Transmitter is in Dropout phase */ + @SerialName("DROPOUT_PHASE") + DROPOUT_PHASE(0x04), + /** Implant is in EOL */ + @SerialName("SENSOR_EOL") + SENSOR_EOL(0x05), + /** No implant is linked to transmitter */ + @SerialName("NO_SENSOR_LINKED") + NO_SENSOR_LINKED(0x06), + /** Transmitter is in unsupported state */ + @SerialName("UNSUPPORTED_MODE") + UNSUPPORTED_MODE(0x07), + /** Transmitter is in post-calibration waiting period */ + @SerialName("WAITING_POST_CALIBRATION") + WAITING_POST_CALIBRATION(0x08), + /** Transmitter disconnect detected */ + @SerialName("LED_DISCONNECT_DETECTED") + LED_DISCONNECT_DETECTED(0x09), + /** Transmitter is in EOL */ + @SerialName("TRANSMITTER_EOL") + TRANSMITTER_EOL(0x0A), + @SerialName("REASON_UNKNOWN") + REASON_UNKNOWN(0xFF); + + companion object { + // E3 mapping — raw byte from register 0x040C + fun from(value: Int): CalibrationReadiness { + return when(value) { + 0 -> READY + 1 -> NOT_ENOUGH_DATA + 2 -> GLUCOSE_RATE_TOO_HIGH + 3 -> TOO_SOON + 4 -> DROPOUT_PHASE + 5 -> SENSOR_EOL + 6 -> NO_SENSOR_LINKED + 7 -> UNSUPPORTED_MODE + 8 -> WAITING_POST_CALIBRATION + 9 -> LED_DISCONNECT_DETECTED + 10 -> TRANSMITTER_EOL + else -> REASON_UNKNOWN + } + } + + // E365 mapping — the official E365 app does not expose calibration readiness. + // Always return READY so calibration submission is not blocked. + fun from365(value: Int): CalibrationReadiness { + return READY + } + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CommandError.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CommandError.kt new file mode 100644 index 000000000000..5889973795d4 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/CommandError.kt @@ -0,0 +1,30 @@ +package app.aaps.plugins.eversense.enums + +enum class CommandError(val code: Int) { + NOT_ALLOWED(1), + UNUSED(2), + INVALID_COMMAND_CODE(3), + INVALID_CRC(4), + INVALID_MESSAGE_LENGTH(5), + BUFFER_OVERFLOW(6), + INVALID_COMMAND_ARGUMENT(7), + SENSOR_READ_ERROR(8), + LOW_BATTERY_ERROR(9), + SENSOR_HARDWARE_FAILURE(10), + TRANSMITTER_HARDWARE_FAILURE(11), + SENSOR_UNABLE_TO_BE_LINKED(12), + TRANSMITTER_IS_BUSY(13), + INVALID_RECORD_NUMBER_RANGE(14), + INVALID_RECORD(15), + CORRUPT_RECORD(16), + CRITICAL_FAULT_ERROR(17), + CRC_ERROR_LOGICAL_BLOCK(18), + ACCESS_DENIED(19), + USB_ONLY(20), + NO_DATA_AVAILABLE(21), + GLUCOSE_BLINDED(22); + + companion object { + fun from(code: Int): CommandError? = values().firstOrNull { it.code == code } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseAlarm.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseAlarm.kt new file mode 100644 index 000000000000..2a33454fa759 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseAlarm.kt @@ -0,0 +1,107 @@ +package app.aaps.plugins.eversense.enums + +enum class EversenseAlarm(val code: Int) { + CRITICAL_FAULT(0), SENSOR_RETIRED(1), EMPTY_BATTERY(2), + SENSOR_TEMPERATURE(3), SENSOR_LOW_TEMPERATURE(4), READER_TEMPERATURE(5), + SENSOR_AWOL(6), INVALID_SENSOR(8), CALIBRATION_REQUIRED(11), + SERIOUSLY_LOW(12), SERIOUSLY_HIGH(13), LOW_GLUCOSE(14), HIGH_GLUCOSE(15), + PREDICTIVE_LOW(18), PREDICTIVE_HIGH(19), RATE_FALLING(20), RATE_RISING(21), + CALIBRATION_GRACE_PERIOD(22), CALIBRATION_EXPIRED(23), + SENSOR_RETIRING_SOON_1(24), SENSOR_RETIRING_SOON_3(26), + SENSOR_RETIRING_SOON_4(27), SENSOR_RETIRING_SOON_5(28), + SENSOR_RETIRING_SOON_6(29), SENSOR_RETIRING_SOON_7(53), + VERY_LOW_BATTERY(31), INVALID_CLOCK(33), SENSOR_STABILITY(34), + TRANSMITTER_DISCONNECTED(35), VIBRATION_CURRENT(36), MSP_ALARM(45), + CALIBRATION_FAILED(47), CALIBRATION_SUSPICIOUS(48), CALIBRATION_NOW(49), + TRANSMITTER_EOL_396(50), TRANSMITTER_EOL_366(51), BATTERY_ERROR(52), + TRANSMITTER_EOL_330(55), TRANSMITTER_EOL_395(56), ONE_CAL(57), + CALIBRATION_SUSPICIOUS_2(59), BATTERY_STATUS(60), SENSOR_CONNECTION(62), + EARLY_SENSOR_RETIREMENT(64), GENERAL_GLUCOSE_SUSPENDED(65), + SENSOR_GRACE(66), SENSOR_SYNC_CONFIRMED(67), + // Codes 68/69 (TxDockedAlert/TxUndockedAlert) are deliberately NOT mapped here - they're not + // real device alarm codes (matches the upstream iOS EversenseKit fix, which removed the + // identical two cases as "custom error codes in Eversense app"; from(code) below falls back + // to UNKNOWN for them, which is filtered out at both alarm entry points - see + // Eversense365Communicator.fullSync (active-alarm list) and EversenseGattCallback's push-alarm + // handling. + TWO_CAL(90), UNKNOWN(255); + + val dmsCode: Int get() = when (this) { + LOW_GLUCOSE -> 0 + HIGH_GLUCOSE -> 1 + RATE_FALLING -> 4 + RATE_RISING -> 5 + PREDICTIVE_LOW -> 6 + PREDICTIVE_HIGH -> 7 + CALIBRATION_NOW -> 8 + CALIBRATION_REQUIRED -> 9 + CALIBRATION_GRACE_PERIOD -> 10 + CALIBRATION_EXPIRED -> 11 + SERIOUSLY_LOW -> 12 + SERIOUSLY_HIGH -> 13 + else -> 255 + } + + val title: String get() = when (this) { + CRITICAL_FAULT -> "Transmitter Error" + SENSOR_RETIRED, SENSOR_GRACE, SENSOR_RETIRING_SOON_1, SENSOR_RETIRING_SOON_3, + SENSOR_RETIRING_SOON_4, SENSOR_RETIRING_SOON_5, SENSOR_RETIRING_SOON_6, + SENSOR_RETIRING_SOON_7 -> "Sensor Replacement" + EMPTY_BATTERY -> "Battery Empty" + SENSOR_TEMPERATURE -> "High Sensor Temperature" + SENSOR_LOW_TEMPERATURE -> "Low Sensor Temperature" + READER_TEMPERATURE -> "High Transmitter Temperature" + SENSOR_AWOL -> "No Sensor Detected" + INVALID_SENSOR -> "New Sensor Detected" + CALIBRATION_REQUIRED -> "Calibrate Now" + SERIOUSLY_LOW -> "Out of Range Low Glucose" + SERIOUSLY_HIGH -> "Out of Range High Glucose" + LOW_GLUCOSE -> "Low Glucose" + HIGH_GLUCOSE -> "High Glucose" + PREDICTIVE_LOW -> "Predicted Low Glucose" + PREDICTIVE_HIGH -> "Predicted High Glucose" + RATE_FALLING -> "Rate Falling" + RATE_RISING -> "Rate Rising" + CALIBRATION_GRACE_PERIOD -> "Calibration Past Due" + CALIBRATION_EXPIRED -> "Calibration Expired" + VERY_LOW_BATTERY -> "Low Battery" + INVALID_CLOCK -> "Invalid Transmitter Time" + TRANSMITTER_DISCONNECTED -> "Transmitter Disconnected" + VIBRATION_CURRENT -> "Vibration Motor" + MSP_ALARM -> "Sensor Replacement" + CALIBRATION_FAILED -> "Calibrate Again" + CALIBRATION_SUSPICIOUS -> "New Calibration Needed" + CALIBRATION_NOW, CALIBRATION_SUSPICIOUS_2 -> "Calibrate Now" + TRANSMITTER_EOL_330, TRANSMITTER_EOL_366, TRANSMITTER_EOL_395, + TRANSMITTER_EOL_396 -> "Transmitter Replacement" + BATTERY_ERROR -> "Battery Error" + ONE_CAL -> "1 Weekly Calibration Phase" + TWO_CAL -> "2 Daily Calibration Phase" + BATTERY_STATUS -> "Battery Status" + SENSOR_CONNECTION -> "Sensor Connection" + EARLY_SENSOR_RETIREMENT -> "Sensor Retirement Area" + GENERAL_GLUCOSE_SUSPENDED -> "Glucose Suspend" + SENSOR_SYNC_CONFIRMED -> "Sensor Sync Confirmed" + SENSOR_STABILITY -> "Sensor Stability" + UNKNOWN -> "Unknown Error" + } + + val isInfo: Boolean get() = this in listOf( + BATTERY_STATUS, ONE_CAL, TWO_CAL, SENSOR_SYNC_CONFIRMED, + SENSOR_RETIRING_SOON_1, SENSOR_RETIRING_SOON_3, SENSOR_RETIRING_SOON_4, + SENSOR_RETIRING_SOON_5, SENSOR_RETIRING_SOON_6, SENSOR_RETIRING_SOON_7 + ) + + val isCritical: Boolean get() = !isWarning && !isInfo + + val isWarning: Boolean get() = this in listOf( + CALIBRATION_NOW, CALIBRATION_FAILED, CALIBRATION_SUSPICIOUS, CALIBRATION_SUSPICIOUS_2, + INVALID_CLOCK, INVALID_SENSOR, PREDICTIVE_HIGH, PREDICTIVE_LOW, + RATE_FALLING, RATE_RISING, TRANSMITTER_EOL_330, TRANSMITTER_EOL_366, TRANSMITTER_EOL_395 + ) + + companion object { + fun from(code: Int): EversenseAlarm = + values().firstOrNull { it.code == code } ?: UNKNOWN + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseE3Memory.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseE3Memory.kt new file mode 100644 index 000000000000..83c00e988948 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseE3Memory.kt @@ -0,0 +1,55 @@ +package app.aaps.plugins.eversense.enums + +enum class EversenseE3Memory(private val address: Long) { + BatteryPercentage(0x0000_0406), + CalibrationReadiness(0x0000_0137), + NextCalibrationDate(0x0000_0470), + NextCalibrationTime(0x0000_0472), + IsOneCalibration(0x0000_0496), + SensorInsertionDate(0x0000_0890), + CalibrationPhase(0x0000_089C), + SensorInsertionTime(0x0000_0892), + LastCalibrationDate(0x0000_08A3), + LastCalibrationTime(0x0000_08A5), + VibrateMode(0x0000_0902), + HighGlucoseAlarmEnabled(0x0000_1029), + HighGlucoseAlarmThreshold(0x0000_110C), + LowGlucoseAlarmThreshold(0x0000_110A), + PredictiveAlert(0x0000_1020), + PredictiveLowTime(0x0000_1021), + PredictiveHighTime(0x0000_1022), + PredictiveLowAlert(0x0000_1027), + PredictiveHighAlert(0x0000_1028), + PredictiveLowTarget(0x0000_1102), + PredictiveHighTarget(0x0000_1104), + RateAlert(0x0000_1010), + RateFallingAlert(0x0000_1025), + RateRisingAlert(0x0000_1026), + RateFallingThreshold(0x0000_1011), + RateRisingThreshold(0x0000_1012), + SensorFieldCurrentRaw(0x0000_049D), + TransmitterSoftwareVersion(0x0000_000A), + TransmitterSoftwareVersionExt(0x0000_00A2), + MmaFeatures(0x0000_040C), + AppVersion(0x0000_0B4B), + BleDisconnect(0x0000_08B2), + HighGlucoseAlarmRepeatIntervalDay(0x0000_1033), + LowGlucoseAlarmRepeatIntervalDay(0x0000_1032), + HighGlucoseAlarmRepeatIntervalNight(0x0000_110F), + LowGlucoseAlarmRepeatIntervalNight(0x0000_110E), + CalibrationsMadeInThisPhase(0x0000_08A1); + + fun getRequestData(): ByteArray { + // Official app sends address as little-endian (LSB first) with trailing 0x00. + // Confirmed from logcat: official app sends [96 04 00] for address 0x0496. + // Format: [addrLSB][addrMSB][0x00] + return byteArrayOf( + this.address.toByte(), // addr LSB + (this.address shr 8).toByte(), // addr MSB + 0x00.toByte(), // trailing zero + ) + } +} + + + diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseSecurityType.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseSecurityType.kt new file mode 100644 index 000000000000..cedd255c66ef --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseSecurityType.kt @@ -0,0 +1,10 @@ +package app.aaps.plugins.eversense.enums + +enum class EversenseSecurityType { + // Eversense E3 + None, + + // Eversense 365 -> generation 2 + // Eversense 365 -> generation 1 is deprecated and not available anymore + SecureV2 +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseTrendArrow.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseTrendArrow.kt new file mode 100644 index 000000000000..bc1eb886f447 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseTrendArrow.kt @@ -0,0 +1,10 @@ +package app.aaps.plugins.eversense.enums + +enum class EversenseTrendArrow(val type: String) { + NONE("NONE"), + SINGLE_UP("SingleUp"), + FORTY_FIVE_UP("FortyFiveUp"), + FLAT("Flat"), + FORTY_FIVE_DOWN("FortyFiveDown"), + SINGLE_DOWN("SingleDown") +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseType.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseType.kt new file mode 100644 index 000000000000..ad44b343e32b --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/EversenseType.kt @@ -0,0 +1,6 @@ +package app.aaps.plugins.eversense.enums + +enum class EversenseType { + EVERSENSE_E3, + EVERSENSE_365 +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/SignalStrength.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/SignalStrength.kt new file mode 100644 index 000000000000..df9b0e999499 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/SignalStrength.kt @@ -0,0 +1,39 @@ +package app.aaps.plugins.eversense.enums + +enum class SignalStrength(val rawThreshold: Int, val threshold: Int) { + NO_SIGNAL(0, 0), + POOR(350, 350), + VERY_LOW(500, 395), + LOW(800, 494), + GOOD(1300, 705), + EXCELLENT(1600, 903); + + val title: String get() = when (this) { + NO_SIGNAL -> "No signal" + POOR -> "Poor" + VERY_LOW -> "Very low" + LOW -> "Low" + GOOD -> "Good" + EXCELLENT -> "Excellent" + } + + companion object { + fun from365(value: Int): SignalStrength = when { + value >= 75 -> EXCELLENT + value >= 48 -> GOOD + value >= 30 -> LOW + value >= 28 -> VERY_LOW + value >= 25 -> POOR + else -> NO_SIGNAL + } + + fun fromRaw(value: Int): SignalStrength = when { + value >= 1600 -> EXCELLENT + value >= 1300 -> GOOD + value >= 800 -> LOW + value >= 500 -> VERY_LOW + value >= 350 -> POOR + else -> NO_SIGNAL + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/TransmitterAlert.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/TransmitterAlert.kt new file mode 100644 index 000000000000..6dfd4000c739 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/enums/TransmitterAlert.kt @@ -0,0 +1,150 @@ +package app.aaps.plugins.eversense.enums + +enum class TransmitterAlert(val code: Int) { + CRITICAL_FAULT_ALARM(0), + SENSOR_RETIRED_ALARM(1), + EMPTY_BATTERY_ALARM(2), + SENSOR_TEMPERATURE_ALARM(3), + SENSOR_LOW_TEMPERATURE_ALARM(4), + READER_TEMPERATURE_ALARM(5), + SENSOR_AWOL_ALARM(6), + SENSOR_ERROR_ALARM(7), + INVALID_SENSOR_ALARM(8), + HIGH_AMBIENT_LIGHT_ALARM(9), + RESERVED_1(10), + SERIOUSLY_LOW_ALARM(12), + SERIOUSLY_HIGH_ALARM(13), + LOW_GLUCOSE_ALARM(14), + HIGH_GLUCOSE_ALARM(15), + LOW_GLUCOSE_ALERT(16), + HIGH_GLUCOSE_ALERT(17), + PREDICTIVE_LOW_ALARM(18), + PREDICTIVE_HIGH_ALARM(19), + RATE_FALLING_ALARM(20), + RATE_RISING_ALARM(21), + CALIBRATION_GRACE_PERIOD_ALARM(22), + CALIBRATION_EXPIRED_ALARM(23), + SENSOR_RETIRING_SOON_1_ALARM(24), + SENSOR_RETIRING_SOON_2_ALARM(25), + SENSOR_RETIRING_SOON_3_ALARM(26), + SENSOR_RETIRING_SOON_4_ALARM(27), + SENSOR_RETIRING_SOON_5_ALARM(28), + SENSOR_RETIRING_SOON_6_ALARM(29), + SENSOR_PREMATURE_REPLACEMENT_ALARM(30), + VERY_LOW_BATTERY_ALARM(31), + LOW_BATTERY_ALARM(32), + INVALID_CLOCK_ALARM(33), + SENSOR_STABILITY(34), + TRANSMITTER_DISCONNECTED(35), + VIBRATION_CURRENT_ALARM(36), + SENSOR_AGED_OUT_ALARM(37), + SENSOR_ON_HOLD_ALARM(38), + MEP_ALARM(39), + EDR_ALARM_0(40), + EDR_ALARM_1(41), + EDR_ALARM_2(42), + EDR_ALARM_3(43), + EDR_ALARM_4(44), + MSP_ALARM(45), + RESERVED_2(46), + TRANSMITTER_EOL_396(50), + TRANSMITTER_EOL_366(51), + BATTERY_ERROR_ALARM(52), + SENSOR_RETIRING_SOON_7_ALARM(53), + RESERVED_3(54), + TRANSMITTER_EOL_330(55), + TRANSMITTER_EOL_395(56), + ONE_CAL(57), + TWO_CAL(58), + TRANSMITTER_RECONNECTED(60), + APP_RESERVED_1(63), + SYSTEM_TIME(64), + APP_RESERVED_2(65), + INCOMPATIBLE_TX(66), + SENSOR_FILE(67), + SENSOR_RELINK(68), + NEW_PASSWORD_DETECTED(69), + BATTERY_OPTIMIZATION(70), + NO_ALARM_ACTIVE(71), + NUMBER_OF_MESSAGES(72); + + val canBlindGlucose: Boolean get() = this in setOf( + HIGH_GLUCOSE_ALARM, HIGH_GLUCOSE_ALERT, + LOW_GLUCOSE_ALARM, LOW_GLUCOSE_ALERT, + PREDICTIVE_HIGH_ALARM, PREDICTIVE_LOW_ALARM, + RATE_FALLING_ALARM, RATE_RISING_ALARM + ) + + val title: String get() = when (this) { + CRITICAL_FAULT_ALARM -> "Critical Fault" + SENSOR_RETIRED_ALARM -> "Sensor Retired" + EMPTY_BATTERY_ALARM -> "Empty Battery" + SENSOR_TEMPERATURE_ALARM -> "Sensor High Temperature" + SENSOR_LOW_TEMPERATURE_ALARM -> "Sensor Low Temperature" + READER_TEMPERATURE_ALARM -> "Transmitter High Temperature" + SENSOR_AWOL_ALARM -> "No Sensor Detected" + SENSOR_ERROR_ALARM -> "Sensor Hardware Error" + INVALID_SENSOR_ALARM -> "Invalid Sensor" + HIGH_AMBIENT_LIGHT_ALARM -> "High Ambient Light" + RESERVED_1 -> "Reserved 1" + SERIOUSLY_LOW_ALARM -> "Seriously Low Glucose" + SERIOUSLY_HIGH_ALARM -> "Seriously High Glucose" + LOW_GLUCOSE_ALARM -> "Low Glucose" + HIGH_GLUCOSE_ALARM -> "High Glucose" + LOW_GLUCOSE_ALERT -> "Low Glucose Alert" + HIGH_GLUCOSE_ALERT -> "High Glucose Alert" + PREDICTIVE_LOW_ALARM -> "Predicted Low Glucose" + PREDICTIVE_HIGH_ALARM -> "Predicted High Glucose" + RATE_FALLING_ALARM -> "Rate Falling" + RATE_RISING_ALARM -> "Rate Rising" + CALIBRATION_GRACE_PERIOD_ALARM -> "Calibration Grace Period" + CALIBRATION_EXPIRED_ALARM -> "Calibration Expired" + SENSOR_RETIRING_SOON_1_ALARM -> "Sensor Retiring Soon 1" + SENSOR_RETIRING_SOON_2_ALARM -> "Sensor Retiring Soon 2" + SENSOR_RETIRING_SOON_3_ALARM -> "Sensor Retiring Soon 3" + SENSOR_RETIRING_SOON_4_ALARM -> "Sensor Retiring Soon 4" + SENSOR_RETIRING_SOON_5_ALARM -> "Sensor Retiring Soon 5" + SENSOR_RETIRING_SOON_6_ALARM -> "Sensor Retiring Soon 6" + SENSOR_PREMATURE_REPLACEMENT_ALARM -> "Sensor Premature Replacement" + VERY_LOW_BATTERY_ALARM -> "Very Low Battery" + LOW_BATTERY_ALARM -> "Low Battery" + INVALID_CLOCK_ALARM -> "Invalid Clock" + SENSOR_STABILITY -> "Sensor Instability" + TRANSMITTER_DISCONNECTED -> "Transmitter Disconnected" + VIBRATION_CURRENT_ALARM -> "Vibration Motor" + SENSOR_AGED_OUT_ALARM -> "Sensor Aged Out" + SENSOR_ON_HOLD_ALARM -> "Sensor Suspend" + MEP_ALARM -> "MEP Alarm" + EDR_ALARM_0 -> "EDR Alarm 0" + EDR_ALARM_1 -> "EDR Alarm 1" + EDR_ALARM_2 -> "EDR Alarm 2" + EDR_ALARM_3 -> "EDR Alarm 3" + EDR_ALARM_4 -> "EDR Alarm 4" + MSP_ALARM -> "MSP Alarm" + RESERVED_2 -> "Reserved 2" + TRANSMITTER_EOL_396 -> "Transmitter EOL 396" + TRANSMITTER_EOL_366 -> "Transmitter EOL 366" + BATTERY_ERROR_ALARM -> "Battery Error" + SENSOR_RETIRING_SOON_7_ALARM -> "Sensor Retiring Soon 7" + RESERVED_3 -> "Reserved 3" + TRANSMITTER_EOL_330 -> "Transmitter EOL 330" + TRANSMITTER_EOL_395 -> "Transmitter EOL 395" + ONE_CAL -> "1 Daily Calibration Phase" + TWO_CAL -> "2 Daily Calibrations Phase" + TRANSMITTER_RECONNECTED -> "Transmitter Reconnected" + APP_RESERVED_1 -> "App Reserved 1" + SYSTEM_TIME -> "System Time" + APP_RESERVED_2 -> "App Reserved 2" + INCOMPATIBLE_TX -> "Incompatible Transmitter" + SENSOR_FILE -> "Sensor File" + SENSOR_RELINK -> "Sensor Re-link" + NEW_PASSWORD_DETECTED -> "New Password Detected" + BATTERY_OPTIMIZATION -> "App Performance" + NO_ALARM_ACTIVE -> "No Alarm Active" + NUMBER_OF_MESSAGES -> "Number of Messages" + } + + companion object { + fun from(code: Int): TransmitterAlert? = values().firstOrNull { it.code == code } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/exceptions/EversenseWriteException.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/exceptions/EversenseWriteException.kt new file mode 100644 index 000000000000..b9fe6bd507f2 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/exceptions/EversenseWriteException.kt @@ -0,0 +1,4 @@ +package app.aaps.plugins.eversense.exceptions + +class EversenseWriteException(override val message: String) : Exception(message) { +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/ActiveAlarm.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/ActiveAlarm.kt new file mode 100644 index 000000000000..7445397f0022 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/ActiveAlarm.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.eversense.models + +import app.aaps.plugins.eversense.enums.EversenseAlarm +import kotlinx.serialization.Serializable + +@Serializable +data class ActiveAlarm( + val code: EversenseAlarm, + val codeRaw: Int, + val flag: Int, + val priority: Int +) diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseCGMResult.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseCGMResult.kt new file mode 100644 index 000000000000..e3283e86a9fe --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseCGMResult.kt @@ -0,0 +1,12 @@ +package app.aaps.plugins.eversense.models + +import app.aaps.plugins.eversense.enums.EversenseTrendArrow + +@kotlinx.serialization.Serializable +data class EversenseCGMResult( + val glucoseInMgDl: Int, + val datetime: Long, + val trend: EversenseTrendArrow, + val sensorId: String = "", + val rawResponseHex: String = "" +) diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseScanResult.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseScanResult.kt new file mode 100644 index 000000000000..29e117ef1e73 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseScanResult.kt @@ -0,0 +1,5 @@ +package app.aaps.plugins.eversense.models + +import android.bluetooth.BluetoothDevice + +data class EversenseScanResult(val name: String, val rssi: Int, val device: BluetoothDevice) diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseSecureState.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseSecureState.kt new file mode 100644 index 000000000000..ed043304b503 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseSecureState.kt @@ -0,0 +1,19 @@ +package app.aaps.plugins.eversense.models + +import kotlinx.serialization.Serializable + +@Serializable +class EversenseSecureState { + var canUseShortcut: Boolean = false + var username: String = "" + var password: String = "" + var clientId: String = "" + var privateKey: String = "" + var publicKey: String = "" + + // 365 only. Selects the EU/OUS DMS hosts in EversenseHttp365Util instead of the US + // ones. Defaults to false so every existing (US) user's saved state deserializes + // unchanged. E3 doesn't need this — its OUS support is unconditional, see + // EversenseHttpE3Util. + var isEuropeanRegion: Boolean = false +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseState.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseState.kt new file mode 100644 index 000000000000..89bdc43d0087 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/EversenseState.kt @@ -0,0 +1,52 @@ +package app.aaps.plugins.eversense.models + +import app.aaps.plugins.eversense.enums.CalibrationMode +import app.aaps.plugins.eversense.packets.e365.CalibrationHistoryItem +import app.aaps.plugins.eversense.enums.CalibrationPhase +import app.aaps.plugins.eversense.enums.CalibrationReadiness +import kotlinx.serialization.Serializable + +@Serializable +class EversenseState { + var lastSync: Long = 0 + var insertionDate: Long = 0 + var calibrationPhase: CalibrationPhase = CalibrationPhase.UNKNOWN + var calibrationReadiness: CalibrationReadiness = CalibrationReadiness.REASON_UNKNOWN + var calibrationMode: CalibrationMode = CalibrationMode.DEFAULT + var nextCalibrationDate: Long = 0 + var lastCalibrationDate: Long = 0 + var batteryPercentage: Int = 0 + var recentGlucoseDatetime: Long = 0 + var recentGlucoseValue: Int = 0 + var lastGlucoseRaw: Int = 0 + var placementSignalRssi: Int = 0 + var sensorSignalStrength: Int = 0 + var activeAlarms: List = emptyList() + var firmwareVersion: String = "" + var mmaFeatures: Int = 0 + var extFirmwareVersion: String = "" + var transmitterSerialNumber: String = "" + var transmitterName: String = "" + var sensorId: String = "" + var settings = EversenseTransmitterSettings() + var calibrationHistory: List = emptyList() +} + +@Serializable +class EversenseTransmitterSettings { + var vibrateEnabled: Boolean = true + var glucoseHighAlarmEnabled: Boolean = true + var glucoseHighAlarmThreshold: Int = 250 + var glucoseLowAlarmThreshold: Int = 60 + var rateFallingAlarmEnabled: Boolean = true + var rateFallingAlarmThreshold: Double = 1.5 + var rateRisingAlarmEnabled: Boolean = true + var rateRisingAlarmThreshold: Double = 1.5 + var predictiveHighAlarmEnabled: Boolean = true + var predictiveHighAlarmThreshold: Int = 180 + var predictiveHighAlarmMinutes: Int = 5 + var predictiveLowAlarmEnabled: Boolean = true + var predictiveLowAlarmThreshold: Int = 70 + var predictiveLowAlarmMinutes: Int = 5 +} + diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/GlucoseHistoryItem.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/GlucoseHistoryItem.kt new file mode 100644 index 000000000000..786035c623b3 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/models/GlucoseHistoryItem.kt @@ -0,0 +1,10 @@ +package app.aaps.plugins.eversense.models + +import app.aaps.plugins.eversense.enums.EversenseTrendArrow + +data class GlucoseHistoryItem( + val valueInMgDl: Int, + val datetime: Long, + val trend: EversenseTrendArrow, + val rawResponseHex: String = "" +) diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/Eversense365Communicator.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/Eversense365Communicator.kt new file mode 100644 index 000000000000..f2cc693eb4c1 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/Eversense365Communicator.kt @@ -0,0 +1,279 @@ +package app.aaps.plugins.eversense.packets + +import app.aaps.plugins.eversense.storage.EversenseStore +import android.os.Handler +import android.os.Looper +import app.aaps.plugins.eversense.storage.edit +import app.aaps.plugins.eversense.EversenseGattCallback +import app.aaps.plugins.eversense.callbacks.EversenseWatcher +import app.aaps.plugins.eversense.enums.EversenseAlarm +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.eversense.models.EversenseTransmitterSettings +import app.aaps.plugins.eversense.packets.e365.GetActiveAlarmsPacket +import app.aaps.plugins.eversense.packets.e365.Ping365Packet +import app.aaps.plugins.eversense.packets.e365.SetAppVersion365Packet +import app.aaps.plugins.eversense.packets.e365.SetBleDisconnect365Packet +import app.aaps.plugins.eversense.packets.e365.GetCalibrationLogValuesPacket +import app.aaps.plugins.eversense.packets.e365.GetGlucoseLogValuesPacket +import app.aaps.plugins.eversense.packets.e365.GetLogRangePacket365 +import app.aaps.plugins.eversense.packets.e365.SetHighGlucoseAlarm365Packet +import app.aaps.plugins.eversense.packets.e365.SetHighGlucoseAlarmEnabled365Packet +import app.aaps.plugins.eversense.packets.e365.SetLowGlucoseAlarm365Packet +import app.aaps.plugins.eversense.packets.e365.SetPredictionHighEnabled365Packet +import app.aaps.plugins.eversense.packets.e365.SetPredictionHighThreshold365Packet +import app.aaps.plugins.eversense.packets.e365.SetPredictionHighTime365Packet +import app.aaps.plugins.eversense.packets.e365.SetPredictionLowEnabled365Packet +import app.aaps.plugins.eversense.packets.e365.SetPredictionLowThreshold365Packet +import app.aaps.plugins.eversense.packets.e365.SetPredictionLowTime365Packet +import app.aaps.plugins.eversense.packets.e365.SetRateFallingEnabled365Packet +import app.aaps.plugins.eversense.packets.e365.SetRateFallingThreshold365Packet +import app.aaps.plugins.eversense.packets.e365.SetRateRisingEnabled365Packet +import app.aaps.plugins.eversense.packets.e365.SetRateRisingThreshold365Packet +import app.aaps.plugins.eversense.packets.e365.SetRepeatHighGlucose365Packet +import app.aaps.plugins.eversense.packets.e365.SetRepeatLowGlucose365Packet +import app.aaps.plugins.eversense.packets.e365.SetVibrateMode365Packet +import app.aaps.plugins.eversense.packets.e365.LogType +import app.aaps.plugins.eversense.packets.e365.GetCalibrationInfoPacket +import app.aaps.plugins.eversense.packets.e365.GetGlucoseDataPacket +import app.aaps.plugins.eversense.packets.e365.GetPatientSettingsPacket +import app.aaps.plugins.eversense.packets.e365.GetSensorInformationPacket +import app.aaps.plugins.eversense.packets.e365.SetCurrentDateTimePacket +import app.aaps.plugins.eversense.util.EversenseLogger +import app.aaps.plugins.eversense.util.StorageKeys +import kotlinx.serialization.json.Json +import java.util.concurrent.TimeUnit +import kotlin.math.abs + +class Eversense365Communicator { + companion object { + private const val TAG = "Eversense365Communicator" + private val JSON = Json { ignoreUnknownKeys = true } + private val handler = Handler(Looper.getMainLooper()) + + private var sensorIdLength = 10 + + // The transmitter's history log and its "current glucose" characteristic timestamp the + // same physical measurement a few seconds apart (log entry first, live characteristic a + // moment later) - on a fast, already-connected keep-alive round trip that gap is usually + // too small for the log to have caught up yet, but after a slower full reconnect (BLE + // connect + service discovery + auth) there's enough elapsed time for the log to already + // contain it. The backfill filter below excludes any history entry within this tolerance + // of the live reading's timestamp so it isn't double-counted as a distinct reading - + // comfortably under the ~5-minute reading cadence, so a real gap still backfills correctly. + // + // The same slip happens at the OTHER end too: the history log can timestamp a reading we + // already stored last cycle (previousGlucoseDatetime) a second or two later than the live + // characteristic did back then. A bare ">" comparison against previousGlucoseDatetime has + // zero tolerance for that, so the already-seen reading re-backfills as "new" the moment the + // log catches up to it. Apply the same tolerance on this end too. + private val BACKFILL_DEDUP_TOLERANCE_MS = TimeUnit.SECONDS.toMillis(90) + + fun readGlucose(gatt: EversenseGattCallback, preferences: EversenseStore, watchers: List) { + val stateJson = preferences.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + + val glucoseData = gatt.writePacket(GetGlucoseDataPacket(sensorIdLength)) + if (glucoseData.datetime <= state.recentGlucoseDatetime) { + EversenseLogger.warning(TAG, "Glucose data is still recent after reading - currentReading: ${glucoseData.datetime}, lastReading: ${state.recentGlucoseDatetime}") + return + } + + var currentGlucose = glucoseData.glucoseInMgDl + + val result = mutableListOf() + val previousGlucoseDatetime = state.recentGlucoseDatetime + state.recentGlucoseDatetime = glucoseData.datetime + state.recentGlucoseValue = currentGlucose + state.lastGlucoseRaw = glucoseData.glucoseInMgDl + state.sensorSignalStrength = glucoseData.signalStrength + EversenseLogger.debug(TAG) { "Sensor signal strength from glucose packet: ${glucoseData.signalStrength}" } + + state.sensorId = glucoseData.sensorId + + result += EversenseCGMResult( + glucoseInMgDl = currentGlucose, + datetime = glucoseData.datetime, + trend = glucoseData.trend, + sensorId = glucoseData.sensorId, + rawResponseHex = glucoseData.rawResponseHex + ) + + // Read last calibration entry for DMS upload (must run while GATT is connected) + try { + val calibLogRange = gatt.writePacket( + GetLogRangePacket365(LogType.CALIBRATIONS) + ) + if (calibLogRange.rangeTo > calibLogRange.rangeFrom) { + val calibFrom = maxOf(calibLogRange.rangeTo - 1, calibLogRange.rangeFrom) + val calibHistory = gatt.writePacket( + GetCalibrationLogValuesPacket(from = calibFrom, to = calibLogRange.rangeTo) + ) + state.calibrationHistory = calibHistory.calibrationHistory + EversenseLogger.debug(TAG) { "Calibration: ${calibHistory.count} entries read (range $calibFrom..${calibLogRange.rangeTo})" } + } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Could not read calibration history: $e") + } + + // Read glucose history for backfill — use previousGlucoseDatetime so gap readings are included + try { + val logRange = gatt.writePacket(GetLogRangePacket365(LogType.GLUCOSE)) + val range = app.aaps.plugins.eversense.util.RangeCalculator.calculateGlucoseRange( + logRange.rangeFrom, logRange.rangeTo, previousGlucoseDatetime + ) + val history = gatt.writePacket( + GetGlucoseLogValuesPacket(from = range.from, to = range.to, sensorIdLength = sensorIdLength) + ) + val backfill = history.glucoseHistory + .filter { it.datetime > previousGlucoseDatetime + BACKFILL_DEDUP_TOLERANCE_MS && it.datetime < glucoseData.datetime - BACKFILL_DEDUP_TOLERANCE_MS } + .map { item -> EversenseCGMResult(glucoseInMgDl = item.valueInMgDl, datetime = item.datetime, trend = item.trend, sensorId = state.sensorId, rawResponseHex = item.rawResponseHex) } + if (backfill.isNotEmpty()) { + result.addAll(0, backfill) + EversenseLogger.debug(TAG) { "Backfill: added ${backfill.size} historical readings" } + } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Could not read glucose history: $e") + } + + preferences.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(state)) + } + + handler.post { + watchers.forEach { it.onCGMRead(EversenseType.EVERSENSE_365, result) } + watchers.forEach { it.onStateChanged(state) } + } + } + + fun fullSync(gatt: EversenseGattCallback, preferences: EversenseStore, watchers: List, force: Boolean = false) { + val stateJsonCheck = preferences.getString(StorageKeys.STATE, null) ?: "{}" + val stateCheck = JSON.decodeFromString(stateJsonCheck) + val fourMinAgo = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(240) + if (!force && stateCheck.lastSync > fourMinAgo) { + EversenseLogger.debug(TAG) { "365 fullSync skipped — last sync was recent (${(System.currentTimeMillis() - stateCheck.lastSync) / 1000}s ago)" } + return + } + try { + val stateJson = preferences.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + + var sensorInformation = gatt.writePacket(GetSensorInformationPacket()) + + // Ping transmitter first — matches iOS fullSync order + try { gatt.writePacket(Ping365Packet()) } catch (e: Exception) { EversenseLogger.warning(TAG, "Ping failed: $e") } + + if (abs(System.currentTimeMillis() - sensorInformation.transmitterDatetime) > 10_000) { + EversenseLogger.debug(TAG) { "Updating transmitter datetime" } + gatt.writePacket(SetCurrentDateTimePacket()) + sensorInformation = gatt.writePacket(GetSensorInformationPacket()) + } + + sensorIdLength = sensorInformation.sensorIdLength + state.insertionDate = sensorInformation.insertionDate + state.batteryPercentage = sensorInformation.batteryLevel + state.firmwareVersion = sensorInformation.version + state.extFirmwareVersion = sensorInformation.extVersion + state.transmitterSerialNumber = sensorInformation.serialNumber + state.transmitterName = sensorInformation.transmitterName + EversenseLogger.debug(TAG) { "Transmitter serialNumber='${sensorInformation.serialNumber}' transmitterName='${sensorInformation.transmitterName}'" } + EversenseLogger.debug(TAG) { "Firmware version: ${sensorInformation.version} / ${sensorInformation.extVersion}" } + + val calibrationInfo = gatt.writePacket(GetCalibrationInfoPacket()) + state.calibrationPhase = calibrationInfo.currentPhase + state.calibrationReadiness = calibrationInfo.calibrationReadiness + state.calibrationMode = calibrationInfo.calibrationMode + state.nextCalibrationDate = calibrationInfo.nextCalibration + state.lastCalibrationDate = calibrationInfo.lastCalibration + + val patientSettings = gatt.writePacket(GetPatientSettingsPacket()) + state.settings.vibrateEnabled = patientSettings.vibrateMode + state.settings.glucoseHighAlarmEnabled = patientSettings.highGlucoseEnabled + state.settings.glucoseHighAlarmThreshold = patientSettings.highGlucoseAlarmInMgDl + state.settings.glucoseLowAlarmThreshold = patientSettings.lowGlucoseAlarmInMgDl + state.settings.rateFallingAlarmEnabled = patientSettings.rateFallingEnabled + state.settings.rateFallingAlarmThreshold = patientSettings.rateFallingThreshold + state.settings.rateRisingAlarmEnabled = patientSettings.rateRisingEnabled + state.settings.rateRisingAlarmThreshold = patientSettings.rateRisingThreshold + state.settings.predictiveHighAlarmEnabled = patientSettings.predictionHighEnabled + state.settings.predictiveHighAlarmMinutes = patientSettings.predictionRisingInterval + state.settings.predictiveHighAlarmThreshold = patientSettings.predictionRisingThreshold + state.settings.predictiveLowAlarmEnabled = patientSettings.predictionLowEnabled + state.settings.predictiveLowAlarmMinutes = patientSettings.predictionFallingInterval + state.settings.predictiveLowAlarmThreshold = patientSettings.predictionFallingThreshold + + // Send app version — iOS sends "8.0.4" in every fullSync + try { gatt.writePacket(SetAppVersion365Packet()) } catch (e: Exception) { EversenseLogger.warning(TAG, "SetAppVersion failed: $e") } + + // Test the packet's standard five-minute interval; this firmware rejects zero. + try { + gatt.writePacket(SetBleDisconnect365Packet(300)) + EversenseLogger.info(TAG, "SetBleDisconnect accepted: 300 seconds") + } catch (e: Exception) { + EversenseLogger.warning(TAG, "SetBleDisconnect (300 seconds) failed: $e") + } + + // Read active alarms + try { + val activeAlarms = gatt.writePacket(GetActiveAlarmsPacket()) + // Drop unrecognized codes (e.g. the removed TxDocked/TxUndocked 68/69) so they + // can't masquerade as a real ongoing alarm - matches the upstream iOS EversenseKit fix. + val filteredAlarms = activeAlarms.alarms.filter { it.code != EversenseAlarm.UNKNOWN } + state.activeAlarms = filteredAlarms + EversenseLogger.debug(TAG) { "Active alarms: ${filteredAlarms.map { it.code.title }}" } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Could not read active alarms: $e") + } + + state.lastSync = System.currentTimeMillis() + EversenseLogger.debug(TAG) { "Completed full sync - datetime: ${state.lastSync}" } + preferences.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(state)) + } + + handler.post { + watchers.forEach { it.onStateChanged(state) } + } + } catch (exception: Exception) { + EversenseLogger.error(TAG, "Failed to do full sync: $exception") + EversenseLogger.debug(TAG) { exception.stackTraceToString() } + // Disconnect on fullSync failure so BLE session resets cleanly rather than looping + // with broken GATT state. Must use disconnectAndScheduleReconnect() here, not plain + // disconnect() - see that method's doc comment for why a self-initiated disconnect + // doesn't reliably re-trigger onConnectionStateChange() (and therefore its reconnect + // scheduling) on its own. + EversenseLogger.warning(TAG, "Disconnecting after fullSync failure to reset BLE session") + gatt.disconnectAndScheduleReconnect() + } + } + + fun writeSettings(gatt: EversenseGattCallback, preferences: EversenseStore, settings: EversenseTransmitterSettings): Boolean { + return try { + gatt.writePacket(SetVibrateMode365Packet(settings.vibrateEnabled)) + gatt.writePacket(SetHighGlucoseAlarmEnabled365Packet(settings.glucoseHighAlarmEnabled)) + gatt.writePacket(SetHighGlucoseAlarm365Packet(settings.glucoseHighAlarmThreshold)) + gatt.writePacket(SetLowGlucoseAlarm365Packet(settings.glucoseLowAlarmThreshold)) + gatt.writePacket(SetRateFallingEnabled365Packet(settings.rateFallingAlarmEnabled)) + gatt.writePacket(SetRateFallingThreshold365Packet(settings.rateFallingAlarmThreshold)) + gatt.writePacket(SetRateRisingEnabled365Packet(settings.rateRisingAlarmEnabled)) + gatt.writePacket(SetRateRisingThreshold365Packet(settings.rateRisingAlarmThreshold)) + gatt.writePacket(SetPredictionLowEnabled365Packet(settings.predictiveLowAlarmEnabled)) + gatt.writePacket(SetPredictionLowThreshold365Packet(settings.predictiveLowAlarmThreshold)) + gatt.writePacket(SetPredictionLowTime365Packet(settings.predictiveLowAlarmMinutes)) + gatt.writePacket(SetPredictionHighEnabled365Packet(settings.predictiveHighAlarmEnabled)) + gatt.writePacket(SetPredictionHighThreshold365Packet(settings.predictiveHighAlarmThreshold)) + gatt.writePacket(SetPredictionHighTime365Packet(settings.predictiveHighAlarmMinutes)) + EversenseLogger.debug(TAG) { "365 settings written successfully" } + preferences.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(JSON.decodeFromString(preferences.getString(StorageKeys.STATE, null) ?: "{}").also { it.settings = settings })) + } + true + } catch (e: Exception) { + EversenseLogger.error(TAG, "Failed to write 365 settings: $e") + false + } + } + } +} + diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/EversenseBasePacket.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/EversenseBasePacket.kt new file mode 100644 index 000000000000..3535bffc96d5 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/EversenseBasePacket.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.eversense.packets + +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.packets.e365.Eversense365Packets +import app.aaps.plugins.eversense.protocol.PacketSpec +import app.aaps.plugins.eversense.protocol.WireEncoding +import app.aaps.plugins.eversense.util.EversenseCrypto365Util +import java.io.ByteArrayOutputStream + +/** Packet adapters describe only their payload and result; this engine owns wire framing. */ +abstract class EversenseBasePacket(val spec: PacketSpec) { + private val response = ByteArrayOutputStream() + private var snapshot: UByteArray? = null + protected val receivedData: UByteArray + get() = snapshot ?: response.toByteArray().toUByteArray().also { snapshot = it } + + @Volatile var isErrorResponse = false + open val skipResponseIdValidation = false + open fun getRequestData(): ByteArray = byteArrayOf() + abstract fun parseResponse(): Response? + protected fun getStartIndex(): Int = spec.responseOffset + + fun appendData(data: UByteArray) { + response.write(data.toByteArray()) + snapshot = null + } + + fun buildRequest(cryptoUtil: EversenseCrypto365Util, payloadSize: Int): ByteArray { + val payload = getRequestData() + return when (spec.securityType) { + EversenseSecurityType.None -> WireEncoding.e3(spec.requestId, payload) + EversenseSecurityType.SecureV2 -> { + val plain = byteArrayOf(spec.requestId, spec.typeId) + payload + val message = if (spec.requestId == Eversense365Packets.AuthenticateCommandId) plain else cryptoUtil.encrypt(plain) + WireEncoding.v2(message, payloadSize) + } + } + } + + abstract class Response +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/EversenseE3Communicator.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/EversenseE3Communicator.kt new file mode 100644 index 000000000000..05b58e721fe0 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/EversenseE3Communicator.kt @@ -0,0 +1,367 @@ +package app.aaps.plugins.eversense.packets + +import app.aaps.plugins.eversense.storage.EversenseStore +import android.os.Handler +import android.os.Looper +import app.aaps.plugins.eversense.storage.edit +import app.aaps.plugins.eversense.EversenseGattCallback +import app.aaps.plugins.eversense.callbacks.EversenseWatcher +import app.aaps.plugins.eversense.enums.CalibrationMode +import app.aaps.plugins.eversense.enums.CalibrationReadiness +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.eversense.models.EversenseTransmitterSettings +import app.aaps.plugins.eversense.packets.e3.GetBatteryPercentagePacket +import app.aaps.plugins.eversense.packets.e3.GetVersionPacket +import app.aaps.plugins.eversense.packets.e3.GetVersionExtendedPacket +import app.aaps.plugins.eversense.packets.e3.GetMmaFeaturesPacket +import app.aaps.plugins.eversense.packets.e3.GetHighGlucoseRepeatIntervalPacket +import app.aaps.plugins.eversense.packets.e3.GetLowGlucoseRepeatIntervalPacket +import app.aaps.plugins.eversense.packets.e3.SetBleDisconnectPacket +import app.aaps.plugins.eversense.packets.e3.SetAppVersionE3Packet +import app.aaps.plugins.eversense.packets.e3.GetCalibrationDailyPacket +import app.aaps.plugins.eversense.packets.e3.GetCalibrationPhasePacket +import app.aaps.plugins.eversense.packets.e3.GetCalibrationReadinessPacket +import app.aaps.plugins.eversense.packets.e3.GetCurrentDatetimePacket +import app.aaps.plugins.eversense.packets.e3.PingPacket +import app.aaps.plugins.eversense.packets.e3.GetCurrentGlucosePacket +import app.aaps.plugins.eversense.packets.e3.GetInsertionDatePacket +import app.aaps.plugins.eversense.packets.e3.GetInsertionTimePacket +import app.aaps.plugins.eversense.packets.e3.GetLastCalibrationDatePacket +import app.aaps.plugins.eversense.packets.e3.GetLastCalibrationTimePacket +import app.aaps.plugins.eversense.packets.e3.GetSettingGlucoseHighEnabled +import app.aaps.plugins.eversense.packets.e3.GetSettingGlucoseHighThresholdPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingGlucoseLowThresholdPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveHighEnabledPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveHighThresholdPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveHighTimePacket +import app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveLowEnabledPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveLowThresholdPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingPredictiveLowTimePacket +import app.aaps.plugins.eversense.packets.e3.GetSettingRateFallingEnabledPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingRateFallingThresholdPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingRateRisingEnabledPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingRateRisingThresholdPacket +import app.aaps.plugins.eversense.packets.e3.GetSettingVibratePacket +import app.aaps.plugins.eversense.packets.e3.SendCalibrationPacket +import app.aaps.plugins.eversense.packets.e3.SetCurrentDatetimePacket +import app.aaps.plugins.eversense.packets.e3.SetSettingGlucoseHighEnablePacket +import app.aaps.plugins.eversense.packets.e3.SetSettingGlucoseHighThresholdPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingGlucoseLowThresholdPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveHighAlarmEnabledPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveHighThresholdPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveHighTimePacket +import app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveLowAlarmEnabledPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveLowThresholdPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingPredictiveLowTimePacket +import app.aaps.plugins.eversense.packets.e3.SetSettingRateFallingEnabledPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingRateFallingThresholdPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingRateRisingEnabledPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingRateRisingThresholdPacket +import app.aaps.plugins.eversense.packets.e3.SetSettingVibratePacket +import app.aaps.plugins.eversense.util.EversenseLogger +import app.aaps.plugins.eversense.util.StorageKeys +import kotlinx.serialization.json.Json +import java.util.concurrent.TimeUnit + +class EversenseE3Communicator { + companion object { + private const val TAG = "EversenseE3Communicator" + private val JSON = Json { ignoreUnknownKeys = true } + private val handler = Handler(Looper.getMainLooper()) + + fun readGlucose(gatt: EversenseGattCallback, preferences: EversenseStore, watchers: List) { + val stateJson = preferences.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + val recentCutoffTime = System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(60) + + if (recentCutoffTime < state.recentGlucoseDatetime) { + EversenseLogger.warning(TAG, "Glucose data is still recent - lastReading: ${state.recentGlucoseDatetime}") + return + } + + try { + EversenseLogger.debug(TAG) { "Reading current glucose..." } + val glucoseData = gatt.writePacket(GetCurrentGlucosePacket()) + if (glucoseData.datetime <= state.recentGlucoseDatetime) { + EversenseLogger.warning(TAG, "Glucose data is still recent after reading - currentReading: ${glucoseData.datetime}, lastReading: ${state.recentGlucoseDatetime}") + return + } + + var currentGlucose = glucoseData.glucoseInMgDl + + val result = mutableListOf() + state.recentGlucoseDatetime = glucoseData.datetime + state.recentGlucoseValue = currentGlucose + state.lastGlucoseRaw = glucoseData.glucoseInMgDl + result += EversenseCGMResult( + glucoseInMgDl = currentGlucose, + datetime = glucoseData.datetime, + trend = glucoseData.trend, + sensorId = state.sensorId, + rawResponseHex = glucoseData.rawResponseHex + ) + + // TODO: read history for backfill - deliberately not implemented. Eversense is + // phasing out E3 in favor of 365 (its EU/OUS successor), so this isn't worth + // building for a shrinking user base. + + preferences.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(state)) + } + + // Read RSSI to update placement signal after each glucose reading + try { + EversenseLogger.debug(TAG) { "Reading RSSI for placement signal..." } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Failed to read RSSI: $e") + } + + handler.post { + watchers.forEach { + it.onCGMRead(EversenseType.EVERSENSE_E3, result) + } + } + } catch (exception: Exception) { + EversenseLogger.error(TAG, "Got exception during readGlucose - exception $exception") + } + } + + fun fullSync(gatt: EversenseGattCallback, preferences: EversenseStore, watchers: List, force: Boolean = false) { + try { + val stateJson = preferences.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + val prevLastCalibrationDate = state.lastCalibrationDate + + val freshnessThreshold = if (state.calibrationReadiness == CalibrationReadiness.WAITING_POST_CALIBRATION) + TimeUnit.SECONDS.toMillis(60) else TimeUnit.SECONDS.toMillis(180) + val freshnessCutoff = System.currentTimeMillis() - freshnessThreshold + + if (!force && freshnessCutoff < state.lastSync) { + EversenseLogger.warning(TAG, "State is still fresh - lastSync: ${state.lastSync}") + return + } + + // Send ping first ΓÇö the official app calls postPingRequest() before any + // ReadSingleByte commands. Without it the transmitter rejects 0x2A with + // InvalidMessageLength (error 5) for every address. + EversenseLogger.debug(TAG) { "Pinging transmitter..." } + try { + gatt.writePacket(PingPacket()) + EversenseLogger.debug(TAG) { "Ping successful" } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Ping failed (non-fatal): $e") + } + + EversenseLogger.debug(TAG) { "Reading current datetime..." } + val currentDatetime = gatt.writePacket(GetCurrentDatetimePacket()) + if (currentDatetime.needsTimeSync) { + EversenseLogger.debug(TAG) { "Send SetCurrentDatetimePacket..." } + gatt.writePacket(SetCurrentDatetimePacket()) + } + + // The E3 battery register returns an enum index (0-11) mapped to display percentages. + // Mapping sourced from official Eversense app BATTERY_LEVEL enum (fromStrength). + try { + EversenseLogger.debug(TAG) { "Reading battery percentage..." } + val batteryRaw = gatt.writePacket(GetBatteryPercentagePacket()) + EversenseLogger.debug(TAG) { "Battery raw register value: ${batteryRaw.percentage}" } + state.batteryPercentage = when (batteryRaw.percentage) { + 0 -> 0 + 1 -> 5 + 2 -> 10 + 3 -> 25 + 4 -> 35 + 5 -> 45 + 6 -> 55 + 7 -> 65 + 8 -> 75 + 9 -> 85 + 10 -> 95 + 11 -> 100 + else -> batteryRaw.percentage + } + EversenseLogger.debug(TAG) { "Battery percentage mapped: ${state.batteryPercentage}%" } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Battery read failed (non-fatal): $e") + } + + // All flash register reads below are wrapped in try/catch. + // Paolo's E3 firmware 6.04 rejects ReadTwoByte/ReadFourByte commands + // with InvalidMessageLength (error 5) ΓÇö these must be non-fatal so + // fullSync completes and lastSync updates even if reads fail. + + try { + EversenseLogger.debug(TAG) { "Reading insertion datetime..." } + val insertionDate = gatt.writePacket(GetInsertionDatePacket()) + val insertionTime = gatt.writePacket(GetInsertionTimePacket()) + val combined = insertionDate.date + insertionTime.time + val minDate = 1577836800000L // 2020-01-01 + val maxDate = 1893456000000L // 2030-01-01 + if (combined in minDate..maxDate) { + state.insertionDate = combined + EversenseLogger.debug(TAG) { "Insertion date accepted: $combined" } + } else { + EversenseLogger.warning(TAG, "Insertion date out of plausible range, ignoring: $combined") + } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Insertion datetime read failed (non-fatal): $e") + } + + try { + EversenseLogger.debug(TAG) { "Reading calibration info..." } + val calibrationPhase = gatt.writePacket(GetCalibrationPhasePacket()) + val calibrationReadiness = gatt.writePacket(GetCalibrationReadinessPacket()) + val lastCalibrationDate = gatt.writePacket(GetLastCalibrationDatePacket()) + val lastCalibrationTime = gatt.writePacket(GetLastCalibrationTimePacket()) + state.calibrationPhase = calibrationPhase.phase + state.calibrationReadiness = calibrationReadiness.readiness + val minCalDate = 1577836800000L // 2020-01-01 + val maxCalDate = 1893456000000L // 2030-01-01 + val newLastCal = lastCalibrationDate.date + lastCalibrationTime.time + if (newLastCal in minCalDate..maxCalDate) { + if (newLastCal != prevLastCalibrationDate && prevLastCalibrationDate != 0L) { + EversenseLogger.debug(TAG) { "Calibration detected from external source: lastCalibrationDate changed from $prevLastCalibrationDate to $newLastCal" } + } + state.lastCalibrationDate = newLastCal + // E3's calibration cadence is a fixed 24h - derive nextCalibrationDate from + // lastCalibrationDate instead of querying the transmitter for it. The device's + // own GetNextCalibrationDate/TimePacket registers proved unreliable in practice + // (matches the upstream iOS EversenseKit fix, which dropped the same two BLE + // reads for the identical reason - see EversenseKit commit d71d14564f). + state.nextCalibrationDate = newLastCal + TimeUnit.HOURS.toMillis(24) + EversenseLogger.debug(TAG) { "lastCalibrationDate accepted: $newLastCal, nextCalibrationDate derived: ${state.nextCalibrationDate}" } + } else { + EversenseLogger.warning(TAG, "lastCalibrationDate out of plausible range, ignoring: $newLastCal") + } + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Calibration info read failed (non-fatal): $e") + } + + try { + val isDailyCalibration = gatt.writePacket(GetCalibrationDailyPacket()) + state.calibrationMode = if (isDailyCalibration.isDaily) CalibrationMode.DAILY_SINGLE else CalibrationMode.DAILY_DUAL + } catch (e: Exception) { + state.calibrationMode = CalibrationMode.DEFAULT + } + + // Transmitter settings ΓÇö all non-fatal + try { + EversenseLogger.debug(TAG) { "Reading transmitter settings..." } + val vibrateEnabled = gatt.writePacket(GetSettingVibratePacket()) + val glucoseHighEnabled = gatt.writePacket(GetSettingGlucoseHighEnabled()) + val glucoseHighThreshold = gatt.writePacket(GetSettingGlucoseHighThresholdPacket()) + val glucoseLowThreshold = gatt.writePacket(GetSettingGlucoseLowThresholdPacket()) + val rateFallingEnabled = gatt.writePacket(GetSettingRateFallingEnabledPacket()) + val rateFallingThreshold = gatt.writePacket(GetSettingRateFallingThresholdPacket()) + val rateRisingEnabled = gatt.writePacket(GetSettingRateRisingEnabledPacket()) + val rateRisingThreshold = gatt.writePacket(GetSettingRateRisingThresholdPacket()) + val predictiveHighEnabled = gatt.writePacket(GetSettingPredictiveHighEnabledPacket()) + val predictiveHighTime = gatt.writePacket(GetSettingPredictiveHighTimePacket()) + val predictiveHighThreshold = gatt.writePacket(GetSettingPredictiveHighThresholdPacket()) + val predictiveLowEnabled = gatt.writePacket(GetSettingPredictiveLowEnabledPacket()) + val predictiveLowTime = gatt.writePacket(GetSettingPredictiveLowTimePacket()) + val predictiveLowThreshold = gatt.writePacket(GetSettingPredictiveLowThresholdPacket()) + state.settings.vibrateEnabled = vibrateEnabled.enabled + state.settings.glucoseHighAlarmEnabled = glucoseHighEnabled.enabled + state.settings.glucoseHighAlarmThreshold = glucoseHighThreshold.threshold + state.settings.glucoseLowAlarmThreshold = glucoseLowThreshold.threshold + state.settings.rateFallingAlarmEnabled = rateFallingEnabled.enabled + state.settings.rateFallingAlarmThreshold = rateFallingThreshold.threshold + state.settings.rateRisingAlarmEnabled = rateRisingEnabled.enabled + state.settings.rateRisingAlarmThreshold = rateRisingThreshold.threshold + state.settings.predictiveHighAlarmEnabled = predictiveHighEnabled.enabled + state.settings.predictiveHighAlarmMinutes = predictiveHighTime.minutes + state.settings.predictiveHighAlarmThreshold = predictiveHighThreshold.threshold + state.settings.predictiveLowAlarmEnabled = predictiveLowEnabled.enabled + state.settings.predictiveLowAlarmMinutes = predictiveLowTime.minutes + state.settings.predictiveLowAlarmThreshold = predictiveLowThreshold.threshold + } catch (e: Exception) { + EversenseLogger.warning(TAG, "Settings read failed (non-fatal): $e") + } + + // Get firmware version ΓÇö aligns with iOS GetVersionPacket + try { + val version = gatt.writePacket(GetVersionPacket()) + if (version != null) state.firmwareVersion = version.version + } catch (e: Exception) { EversenseLogger.warning(TAG, "GetVersion failed: $e") } + + // Get extended firmware version + try { + val extVersion = gatt.writePacket(GetVersionExtendedPacket()) + if (extVersion != null) state.extFirmwareVersion = extVersion.extVersion + } catch (e: Exception) { EversenseLogger.warning(TAG, "GetVersionExtended failed: $e") } + + // Get MMA features + try { + val mma = gatt.writePacket(GetMmaFeaturesPacket()) + if (mma != null) state.mmaFeatures = mma.value + } catch (e: Exception) { EversenseLogger.warning(TAG, "GetMmaFeatures failed: $e") } + + // Set app version ΓÇö iOS sends 8.0.4 in every fullSync + try { gatt.writePacket(SetAppVersionE3Packet()) } catch (e: Exception) { EversenseLogger.warning(TAG, "SetAppVersionE3 failed: $e") } + + // Set BLE disconnect timeout ΓÇö 10s + try { gatt.writePacket(SetBleDisconnectPacket(10)) } catch (e: Exception) { EversenseLogger.warning(TAG, "SetBleDisconnect E3 failed: $e") } + + state.lastSync = System.currentTimeMillis() + EversenseLogger.debug(TAG) { "Completed full sync - datetime: ${state.lastSync}" } + preferences.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(state)) + } + + handler.post { + watchers.forEach { + it.onStateChanged(state) + } + } + } catch (exception: Exception) { + EversenseLogger.error(TAG, "Failed to do full sync: $exception") + } + } + + fun writeSettings(gatt: EversenseGattCallback, preferences: EversenseStore, settings: EversenseTransmitterSettings): Boolean { + try { + gatt.writePacket(SetSettingVibratePacket(settings.vibrateEnabled)) + + gatt.writePacket(SetSettingGlucoseHighEnablePacket(settings.glucoseHighAlarmEnabled)) + gatt.writePacket(SetSettingGlucoseHighThresholdPacket(settings.glucoseHighAlarmThreshold)) + gatt.writePacket(SetSettingGlucoseLowThresholdPacket(settings.glucoseLowAlarmThreshold)) + + gatt.writePacket(SetSettingRateFallingEnabledPacket(settings.rateFallingAlarmEnabled)) + gatt.writePacket(SetSettingRateFallingThresholdPacket(settings.rateFallingAlarmThreshold)) + gatt.writePacket(SetSettingRateRisingEnabledPacket(settings.rateRisingAlarmEnabled)) + gatt.writePacket(SetSettingRateRisingThresholdPacket(settings.rateRisingAlarmThreshold)) + + gatt.writePacket(SetSettingPredictiveHighAlarmEnabledPacket(settings.predictiveHighAlarmEnabled)) + gatt.writePacket(SetSettingPredictiveHighTimePacket(settings.predictiveHighAlarmMinutes)) + gatt.writePacket(SetSettingPredictiveHighThresholdPacket(settings.predictiveHighAlarmThreshold)) + gatt.writePacket(SetSettingPredictiveLowAlarmEnabledPacket(settings.predictiveLowAlarmEnabled)) + gatt.writePacket(SetSettingPredictiveLowTimePacket(settings.predictiveLowAlarmMinutes)) + gatt.writePacket(SetSettingPredictiveLowThresholdPacket(settings.predictiveLowAlarmThreshold)) + + val stateJson = preferences.getString(StorageKeys.STATE, null) ?: "{}" + val state = JSON.decodeFromString(stateJson) + state.settings = settings + preferences.edit(commit = true) { + putString(StorageKeys.STATE, JSON.encodeToString(state)) + } + + return true + } catch (exception: Exception) { + EversenseLogger.error(TAG, "Failed to write settings: $exception") + return false + } + } + + // Send a blood glucose calibration value to the E3 transmitter. + // The transmitter must be in CalibrationReadiness.READY state. + // Throws EversenseWriteException if the packet fails. + fun sendCalibration(gatt: EversenseGattCallback, glucoseMgDl: Int) { + EversenseLogger.debug(TAG) { "Sending calibration value: $glucoseMgDl mg/dL" } + gatt.writePacket(SendCalibrationPacket(glucoseMgDl), 15000L) + EversenseLogger.debug(TAG) { "Calibration sent successfully" } + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3CalibrationCommands.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3CalibrationCommands.kt new file mode 100644 index 000000000000..d6638133f62b --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3CalibrationCommands.kt @@ -0,0 +1,27 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.protocol.CalibrationPayload +import app.aaps.plugins.eversense.protocol.PacketSpec +import app.aaps.plugins.eversense.protocol.PacketTime + +class SendCalibrationPacket(private val glucoseMgDl: Int, private val sampleTimeMs: Long = PacketTime.nowMillis()) : + EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.SendBloodGlucoseDataWithTwoTimestampsCommandId, EversenseE3Packets.SendBloodGlucoseDataWithTwoTimestampsResponseId)) { + + override fun getRequestData(): ByteArray = CalibrationPayload.e3(glucoseMgDl, sampleTimeMs, PacketTime.nowMillis()) + + override fun parseResponse(): Response? = if (receivedData.isEmpty()) null else Response() + + class Response : EversenseBasePacket.Response() +} + +class SetBloodGlucosePointPacket(private val glucoseInMgDl: Int, private val sampleTimestamp: Long = PacketTime.nowMillis()) : + EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.SendBloodGlucoseDataWithTwoTimestampsCommandId, EversenseE3Packets.SendBloodGlucoseDataWithTwoTimestampsResponseId)) { + override val skipResponseIdValidation = true + + override fun getRequestData(): ByteArray = CalibrationPayload.e3(glucoseInMgDl, sampleTimestamp, PacketTime.nowMillis()) + + override fun parseResponse(): Response? = if (receivedData.isEmpty()) null else Response() + + class Response : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3HistoryQueries.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3HistoryQueries.kt new file mode 100644 index 000000000000..bd8db433611d --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3HistoryQueries.kt @@ -0,0 +1,144 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.enums.CalibrationFlag +import app.aaps.plugins.eversense.enums.EversenseAlarm +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Parser +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Writer +import app.aaps.plugins.eversense.protocol.PacketSpec + +class GetAlertLogPacket(private val index: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadAllSensorGlucoseAlertsInSpecifiedRangeCommandId, EversenseE3Packets.ReadAllSensorGlucoseAlertsInSpecifiedRangeResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Writer.writeInt16(index) + EversenseE3Writer.writeInt16(index) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val recordIndex = (receivedData[s].toInt() and 0xFF) or ((receivedData[s + 1].toInt() and 0xFF) shl 8) + val datetime = EversenseE3Parser.readDate(receivedData, s + 2) + EversenseE3Parser.readTime(receivedData, s + 4) + val alarmCode = receivedData[s + 7].toInt() and 0xFF + return Response( + index = recordIndex, + datetime = datetime, + alarm = EversenseAlarm.from(alarmCode) + ) + } + + data class Response( + val index: Int, + val datetime: Long, + val alarm: EversenseAlarm + ) : EversenseBasePacket.Response() +} + +class GetCalibrationLogPacket(private val index: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadLogOfBloodGlucoseDataInSpecifiedRangeCommandId, EversenseE3Packets.ReadLogOfBloodGlucoseDataInSpecifiedRangeResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Writer.writeInt16(index) + EversenseE3Writer.writeInt16(index) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val recordIndex = (receivedData[s].toInt() and 0xFF) or ((receivedData[s + 1].toInt() and 0xFF) shl 8) + val datetime = EversenseE3Parser.readDate(receivedData, s + 2) + EversenseE3Parser.readTime(receivedData, s + 4) + val glucoseInMgDl = (receivedData[s + 6].toInt() and 0xFF) or ((receivedData[s + 8].toInt() and 0xFF) shl 7) + val flagCode = receivedData[s + 9].toInt() and 0xFF + return Response( + index = recordIndex, + datetime = datetime, + glucoseInMgDl = glucoseInMgDl, + flag = CalibrationFlag.from(flagCode) + ) + } + + data class Response( + val index: Int, + val datetime: Long, + val glucoseInMgDl: Int, + val flag: CalibrationFlag + ) : EversenseBasePacket.Response() +} + +/** + * Reads the first and last record numbers for the blood glucose (calibration) log (16-bit indices). + * Use [GetGlucoseLogRangePacket] for sensor glucose log range. + */ + +class GetCalibrationLogRangePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadFirstAndLastBloodGlucoseDataRecordNumbersCommandId, EversenseE3Packets.ReadFirstAndLastBloodGlucoseDataRecordNumbersResponseId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val from = (receivedData[s].toInt() and 0xFF) or ((receivedData[s + 1].toInt() and 0xFF) shl 8) + val to = (receivedData[s + 2].toInt() and 0xFF) or ((receivedData[s + 3].toInt() and 0xFF) shl 8) + return Response(rangeFrom = from, rangeTo = to) + } + + data class Response(val rangeFrom: Int, val rangeTo: Int) : EversenseBasePacket.Response() +} + +class GetGlucoseLogPacket(private val index: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadAllSensorGlucoseDataInSpecifiedRangeCommandId, EversenseE3Packets.ReadAllSensorGlucoseDataInSpecifiedRangeResponseId)) { + + override fun getRequestData(): ByteArray { + // 24-bit (3-byte) index sent as both from and to + return byteArrayOf( + index.toByte(), + (index shr 8).toByte(), + (index shr 16).toByte(), + index.toByte(), + (index shr 8).toByte(), + (index shr 16).toByte() + ) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val recordIndex = (receivedData[s].toInt() and 0xFF) or + ((receivedData[s + 1].toInt() and 0xFF) shl 8) or + ((receivedData[s + 2].toInt() and 0xFF) shl 16) + val datetime = EversenseE3Parser.readDate(receivedData, s + 3) + EversenseE3Parser.readTime(receivedData, s + 5) + val glucoseInMgDl = (receivedData[s + 7].toInt() and 0xFF) or ((receivedData[s + 8].toInt() and 0xFF) shl 8) + return Response( + index = recordIndex, + datetime = datetime, + glucoseInMgDl = glucoseInMgDl + ) + } + + data class Response( + val index: Int, + val datetime: Long, + val glucoseInMgDl: Int + ) : EversenseBasePacket.Response() +} + +/** + * Reads the first and last record numbers for the sensor glucose log (24-bit indices). + * Use [GetCalibrationLogRangePacket] for blood glucose (calibration) log range. + */ + +class GetGlucoseLogRangePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadFirstAndLastSensorGlucoseRecordNumbersCommandId, EversenseE3Packets.ReadFirstAndLastSensorGlucoseRecordNumbersResponseId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val from = (receivedData[s].toInt() and 0xFF) or + ((receivedData[s + 1].toInt() and 0xFF) shl 8) or + ((receivedData[s + 2].toInt() and 0xFF) shl 16) + val to = (receivedData[s + 3].toInt() and 0xFF) or + ((receivedData[s + 4].toInt() and 0xFF) shl 8) or + ((receivedData[s + 5].toInt() and 0xFF) shl 16) + return Response(rangeFrom = from, rangeTo = to) + } + + data class Response(val rangeFrom: Int, val rangeTo: Int) : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3RegisterPacket.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3RegisterPacket.kt new file mode 100644 index 000000000000..ec3d707bb27c --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3RegisterPacket.kt @@ -0,0 +1,10 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.enums.EversenseE3Memory +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.protocol.PacketSpec + +/** Register addressing is shared by all E3 register readers. */ +abstract class E3RegisterPacket(spec: PacketSpec, private val register: EversenseE3Memory) : EversenseBasePacket(spec) { + final override fun getRequestData(): ByteArray = register.getRequestData() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3RegisterQueries.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3RegisterQueries.kt new file mode 100644 index 000000000000..4f6f99e73a9c --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3RegisterQueries.kt @@ -0,0 +1,333 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.enums.CalibrationPhase +import app.aaps.plugins.eversense.enums.CalibrationReadiness +import app.aaps.plugins.eversense.enums.EversenseE3Memory +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Parser +import app.aaps.plugins.eversense.protocol.PacketSpec + +class GetBatteryPercentagePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.BatteryPercentage) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + // The E3 battery register returns an enum index (0-11). Clamp to valid range. + val raw = receivedData[getStartIndex()].toInt() and 0xFF + val percentage = raw.coerceIn(0, 11) + return Response(percentage = percentage) + } + + data class Response(val percentage: Int) : EversenseBasePacket.Response() +} + +class GetBleDisconnectPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.BleDisconnect) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val intervalSeconds = (receivedData[s].toInt() and 0xFF) or ((receivedData[s + 1].toInt() and 0xFF) shl 8) + return Response(intervalSeconds = intervalSeconds) + } + + data class Response(val intervalSeconds: Int) : EversenseBasePacket.Response() +} + +class GetCalibrationDailyPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.IsOneCalibration) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + // Official app: IsOneCalibration register value 0x01 = one calibration per day (daily single) + return Response(isDaily = receivedData[getStartIndex()].toInt() and 0xFF == 0x01) + } + + data class Response(val isDaily: Boolean) : EversenseBasePacket.Response() +} + +class GetCalibrationPhasePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.CalibrationPhase) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(phase = CalibrationPhase.fromE3(receivedData[getStartIndex()].toInt())) + } + + data class Response(val phase: CalibrationPhase) : EversenseBasePacket.Response() +} + +class GetCalibrationReadinessPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.CalibrationReadiness) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(readiness = CalibrationReadiness.from(receivedData[getStartIndex()].toInt())) + } + + data class Response(val readiness: CalibrationReadiness) : EversenseBasePacket.Response() +} + +class GetCompletedCalibrationsCountPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.CalibrationsMadeInThisPhase) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val count = (receivedData[s].toInt() and 0xFF) or ((receivedData[s + 1].toInt() and 0xFF) shl 8) + return Response(count = count) + } + + data class Response(val count: Int) : EversenseBasePacket.Response() +} + +class GetInsertionDatePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.SensorInsertionDate) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(date = EversenseE3Parser.readDate(receivedData, getStartIndex())) + } + + data class Response(val date: Long) : EversenseBasePacket.Response() +} + +class GetInsertionTimePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.SensorInsertionTime) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(time = EversenseE3Parser.readTime(receivedData, getStartIndex())) + } + + data class Response(val time: Long) : EversenseBasePacket.Response() +} + +class GetIsOneCalPhasePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.IsOneCalibration) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response(value = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val value: Boolean) : EversenseBasePacket.Response() +} + +class GetLastCalibrationDatePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.LastCalibrationDate) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response(date = EversenseE3Parser.readDate(receivedData, getStartIndex())) + } + + data class Response(val date: Long) : EversenseBasePacket.Response() +} + +class GetLastCalibrationTimePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.LastCalibrationTime) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response(time = EversenseE3Parser.readTime(receivedData, getStartIndex())) + } + + data class Response(val time: Long) : EversenseBasePacket.Response() +} + +class GetSettingGlucoseHighEnabled : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.HighGlucoseAlarmEnabled) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingGlucoseHighThresholdPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.HighGlucoseAlarmThreshold) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response( + threshold = EversenseE3Parser.readGlucose(receivedData, getStartIndex()) + ) + } + + data class Response(val threshold: Int) : EversenseBasePacket.Response() +} + +class GetSettingGlucoseLowThresholdPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.LowGlucoseAlarmThreshold) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(threshold = EversenseE3Parser.readGlucose(receivedData, getStartIndex())) + } + + data class Response(val threshold: Int): EversenseBasePacket.Response() +} + +class GetSettingPredictiveAlarmEnabledPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveAlert) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingPredictiveHighEnabledPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveHighAlert) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingPredictiveHighThresholdPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveHighTarget) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(threshold = EversenseE3Parser.readGlucose(receivedData, getStartIndex())) + } + + data class Response(val threshold: Int) : EversenseBasePacket.Response() +} + +class GetSettingPredictiveHighTimePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveHighTime) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(minutes = receivedData[getStartIndex()].toInt()) + } + + data class Response(val minutes: Int) : EversenseBasePacket.Response() +} + +class GetSettingPredictiveLowEnabledPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveLowAlert) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingPredictiveLowThresholdPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveLowTarget) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(threshold = EversenseE3Parser.readGlucose(receivedData, getStartIndex())) + } + + data class Response(val threshold: Int) : EversenseBasePacket.Response() +} + +class GetSettingPredictiveLowTimePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.PredictiveLowTime) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(minutes = receivedData[getStartIndex()].toInt()) + } + + data class Response(val minutes: Int) : EversenseBasePacket.Response() +} + +class GetSettingRateEnabledPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.RateAlert) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingRateFallingEnabledPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.RateFallingAlert) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingRateFallingThresholdPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.RateFallingThreshold) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(threshold = receivedData[getStartIndex()].toDouble() / 10) + } + + data class Response(val threshold: Double): EversenseBasePacket.Response() +} + +class GetSettingRateRisingEnabledPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.RateRisingAlert) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(enabled = receivedData[getStartIndex()].toInt() == 0x55) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} + +class GetSettingRateRisingThresholdPacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.RateRisingThreshold) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response(threshold = receivedData[getStartIndex()].toDouble() / 10) + } + + data class Response(val threshold: Double) : EversenseBasePacket.Response() +} + +class GetSettingVibratePacket : E3RegisterPacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId), EversenseE3Memory.VibrateMode) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response( + enabled = receivedData[getStartIndex()].toInt() == 0x55 + ) + } + + data class Response(val enabled: Boolean) : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3SessionCommands.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3SessionCommands.kt new file mode 100644 index 000000000000..8ae7bfb25a6f --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3SessionCommands.kt @@ -0,0 +1,354 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.enums.EversenseE3Memory +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Parser +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Writer +import app.aaps.plugins.eversense.protocol.GlucoseDecoders +import app.aaps.plugins.eversense.protocol.PacketSpec +import app.aaps.plugins.eversense.protocol.PacketTime +import app.aaps.plugins.eversense.util.EversenseLogger +import app.aaps.plugins.eversense.util.MessageCoder +import java.util.TimeZone +import kotlin.math.abs + +class EnterDiagnosticModePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.EnterDiagnosticModeCommandId, EversenseE3Packets.EnterDiagnosticModeResponseId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class ExitDiagnosticModePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ExitDiagnosticModeCommandId, EversenseE3Packets.ExitDiagnosticModeResponseId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class GetCurrentDatetimePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadCurrentTransmitterDateAndTimeCommandId, EversenseE3Packets.ReadCurrentTransmitterDateAndTimeResponseId)) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + val start = getStartIndex() + val date = EversenseE3Parser.readDate(receivedData, start) + val time = EversenseE3Parser.readTime(receivedData, start + 2) + val timeZoneOffset = EversenseE3Parser.readTimezone(receivedData, start + 4) + var needsTimeSync = false + val actualTimeZoneOffset = TimeZone.getDefault().getOffset(PacketTime.nowMillis()).toLong() + // Allow time drift <10s + if (abs(PacketTime.nowMillis() - (date + time)) > 10_000) { + EversenseLogger.warning("GetCurrentDatetimePacket", "time drift detected... drift: ${abs(PacketTime.nowMillis() - (date + time))} ms") + needsTimeSync = true + } else if (actualTimeZoneOffset != timeZoneOffset) { + EversenseLogger.warning("GetCurrentDatetimePacket", "timezone mismatch - received: $timeZoneOffset, actual: $actualTimeZoneOffset") + needsTimeSync = true + } + return Response(date + time, timeZoneOffset, needsTimeSync) + } + + data class Response(val datetime: Long, val timezoneOffset: Long, val needsTimeSync: Boolean): EversenseBasePacket.Response() +} + +class GetCurrentGlucosePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadSensorGlucoseCommandId, EversenseE3Packets.ReadSensorGlucoseResponseId)) { + + override fun parseResponse(): Response? = GlucoseDecoders.e3(receivedData)?.let { + Response(it.timestamp, it.glucose, it.trend, it.raw) + } + + data class Response(val datetime: Long, val glucoseInMgDl: Int, val trend: EversenseTrendArrow, val rawResponseHex: String = "") : EversenseBasePacket.Response() +} + +class GetGlucoseAlertsAndStatusPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadSensorGlucoseAlertsAndStatusCommandId, EversenseE3Packets.ReadSensorGlucoseAlertsAndStatusResponseId)) { + private val STATUS_FLAG_COUNT = 13 + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val s = getStartIndex() + val rawContent = receivedData.drop(s + 1).dropLast(2).map { it.toInt() and 0xFF } + val content = IntArray(STATUS_FLAG_COUNT) + val offset = STATUS_FLAG_COUNT - rawContent.size.coerceAtMost(STATUS_FLAG_COUNT) + rawContent.take(STATUS_FLAG_COUNT).forEachIndexed { i, v -> content[offset + i] = v } + if (content.all { it == 0 }) return Response(alarms = emptyList()) + val alarms = mutableListOf() + fun add(alarm: app.aaps.plugins.eversense.enums.EversenseAlarm?) { + alarm?.let { alarms.add(ActiveAlarm(code = it, codeRaw = it.code, flag = 0, priority = 0)) } + } + add(MessageCoder.messageCodeForGlucoseLevelAlarmFlags(content[0])) + add(MessageCoder.messageCodeForGlucoseLevelAlertFlags(content[1])) + add(MessageCoder.messageCodeForRateAlertFlags(content[2])) + add(MessageCoder.messageCodeForPredictiveAlertFlags(content[3])) + add(MessageCoder.messageCodeForSensorHardwareAndAlertFlags(content[4])) + add(MessageCoder.messageCodeForSensorReadAlertFlags(content[5])) + add(MessageCoder.messageCodeForSensorReplacementFlags(content[6])) + add(MessageCoder.messageCodeForSensorCalibrationFlags(content[7])) + add(MessageCoder.messageCodeForTransmitterStatusAlertFlags(content[8])) + add(MessageCoder.messageCodeForTransmitterBatteryAlertFlags(content[9])) + add(MessageCoder.messageCodeForTransmitterEOLAlertFlags(content[10])) + add(MessageCoder.messageCodeForSensorReplacementFlags2(content[11])) + add(MessageCoder.messageCodeForCalibrationSwitchFlags(content[12])) + return Response(alarms = alarms) + } + + data class Response(val alarms: List) : EversenseBasePacket.Response() +} + +class GetHighGlucoseRepeatIntervalPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray = EversenseE3Memory.HighGlucoseAlarmRepeatIntervalDay.getRequestData() + + override fun parseResponse(): Response? { + if (receivedData.size < getStartIndex() + 1) return null + return Response(intervalMinutes = receivedData[getStartIndex()].toInt() and 0xFF) + } + + data class Response(val intervalMinutes: Int) : EversenseBasePacket.Response() +} + +class GetLowGlucoseRepeatIntervalPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray = EversenseE3Memory.LowGlucoseAlarmRepeatIntervalDay.getRequestData() + + override fun parseResponse(): Response? { + if (receivedData.size < getStartIndex() + 1) return null + return Response(intervalMinutes = receivedData[getStartIndex()].toInt() and 0xFF) + } + + data class Response(val intervalMinutes: Int) : EversenseBasePacket.Response() +} + +class GetMmaFeaturesPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray = EversenseE3Memory.MmaFeatures.getRequestData() + + override fun parseResponse(): Response? { + if (receivedData.size < getStartIndex() + 1) return null + return Response(value = receivedData[getStartIndex()].toInt() and 0xFF) + } + + data class Response(val value: Int) : EversenseBasePacket.Response() +} + +class GetSignalStrengthRawPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId)) { + companion object { + // Raw thresholds matching iOS EversenseKit SignalStrength.swift rawThreshold values + const val THRESHOLD_EXCELLENT = 1600 + const val THRESHOLD_GOOD = 1300 + const val THRESHOLD_LOW = 800 + const val THRESHOLD_VERY_LOW = 500 + const val THRESHOLD_POOR = 350 + } + + override fun getRequestData(): ByteArray = EversenseE3Memory.SensorFieldCurrentRaw.getRequestData() + + override fun parseResponse(): Response? { + val start = getStartIndex() + if (receivedData.size < start + 2) return null + // Little-endian UInt16 — matches iOS: UInt16(data[start]) | (UInt16(data[start + 1]) << 8) + val raw = (receivedData[start].toInt() and 0xFF) or + ((receivedData[start + 1].toInt() and 0xFF) shl 8) + // Classify the RAW flash value using iOS EversenseKit SignalStrength.threshold + // values (903/705/494/395/350), then map to a 0-100 percentage that the + // placement activity bar thresholds (75/48/30/28/25) bucket correctly. + // The previous code used raw/20, which systematically under-reported signal + // (a good placement at raw>=903 displayed as "Fair" instead of "Excellent"). + val signalPercent = when { + raw >= 903 -> 80 // Excellent -> 5 bars + raw >= 705 -> 55 // Good -> 4 bars + raw >= 494 -> 35 // Low -> 3 bars + raw >= 395 -> 28 // Very low -> 2 bars + raw >= 350 -> 25 // Poor -> 1 bar + else -> 0 // No signal -> 0 bars + } + return Response(rawValue = raw, signalStrength = signalPercent) + } + + data class Response( + val rawValue: Int, + val signalStrength: Int // 0-100 scaled, matching iOS implementation + ) : EversenseBasePacket.Response() +} + +class GetVersionExtendedPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadFourByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadFourByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray = EversenseE3Memory.TransmitterSoftwareVersionExt.getRequestData() + + override fun parseResponse(): Response? { + val start = getStartIndex() + if (receivedData.size < start + 4) return null + val extVersion = (start until start + 4).map { receivedData[it].toInt().toChar() }.joinToString("") + return Response(extVersion = extVersion.trim()) + } + + data class Response(val extVersion: String) : EversenseBasePacket.Response() +} + +class GetVersionPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.ReadFourByteSerialFlashRegisterCommandId, EversenseE3Packets.ReadFourByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray = EversenseE3Memory.TransmitterSoftwareVersion.getRequestData() + + override fun parseResponse(): Response? { + val start = getStartIndex() + if (receivedData.size < start + 4) return null + val version = (start until start + 4).map { receivedData[it].toInt().toChar() }.joinToString("") + return Response(version = version.trim()) + } + + data class Response(val version: String) : EversenseBasePacket.Response() +} + +class PingPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.PingCommandId, EversenseE3Packets.PingResponseId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SaveBondingInformationPacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.SaveBLEBondingInformationCommandId, EversenseE3Packets.SaveBLEBondingInformationResponseId)) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return SaveBondingInformationResponse() + } + + class SaveBondingInformationResponse() : Response() +} + +class SetAppVersionE3Packet(private val appVersion: String = "8.0.4") : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteFourByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteFourByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + val parts = appVersion.split(".") + val i0 = parts.getOrNull(0)?.toIntOrNull() ?: 0 + val i1 = parts.getOrNull(1)?.toIntOrNull() ?: 0 + val i2 = parts.getOrNull(2)?.toIntOrNull() ?: 0 + val addr = EversenseE3Memory.AppVersion.getRequestData() + return byteArrayOf(addr[0], addr[1], addr[2], + (i2 and 0xFF).toByte(), + ((i2 and 0xFF00) shr 8).toByte(), + (i1 and 0xFF).toByte(), + (i0 and 0xFF).toByte() + ) + } + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetBleDisconnectPacket(private val intervalSeconds: Int = 300) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteTwoByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + val addr = EversenseE3Memory.BleDisconnect.getRequestData() + return byteArrayOf(addr[0], addr[1], addr[2], + (intervalSeconds and 0xFF).toByte(), + ((intervalSeconds shr 8) and 0xFF).toByte() + ) + } + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetCurrentDatetimePacket : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.SetCurrentTransmitterDateAndTimeCommandId, EversenseE3Packets.SetCurrentTransmitterDateAndTimeResponseId)) { + + override fun getRequestData(): ByteArray { + val now = PacketTime.nowMillis() + return EversenseE3Writer.writeDate(now) + + EversenseE3Writer.writeTime(now) + + EversenseE3Writer.writeTimezone(now) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() {} +} + +class SetHighGlucoseRepeatIntervalDayPacket(private val intervalMinutes: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.HighGlucoseAlarmRepeatIntervalDay.getRequestData() + + byteArrayOf(intervalMinutes.toByte()) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetHighGlucoseRepeatIntervalNightPacket(private val intervalMinutes: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.HighGlucoseAlarmRepeatIntervalNight.getRequestData() + + byteArrayOf(intervalMinutes.toByte()) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetLowGlucoseRepeatIntervalDayPacket(private val intervalMinutes: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.LowGlucoseAlarmRepeatIntervalDay.getRequestData() + + byteArrayOf(intervalMinutes.toByte()) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetLowGlucoseRepeatIntervalNightPacket(private val intervalMinutes: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.LowGlucoseAlarmRepeatIntervalNight.getRequestData() + + byteArrayOf(intervalMinutes.toByte()) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + return Response() + } + + class Response : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3SettingsCommands.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3SettingsCommands.kt new file mode 100644 index 000000000000..e2c31165b9b7 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/E3SettingsCommands.kt @@ -0,0 +1,263 @@ +package app.aaps.plugins.eversense.packets.e3 + +import app.aaps.plugins.eversense.enums.EversenseE3Memory +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Writer +import app.aaps.plugins.eversense.protocol.PacketSpec + +class SetSettingGlucoseHighEnablePacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.HighGlucoseAlarmEnabled.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response() : EversenseBasePacket.Response() +} + +class SetSettingGlucoseHighThresholdPacket(private val threshold: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteTwoByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.HighGlucoseAlarmThreshold.getRequestData() + EversenseE3Writer.writeInt16(threshold) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response() : EversenseBasePacket.Response() +} + +class SetSettingGlucoseLowThresholdPacket(private val threshold: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteTwoByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.LowGlucoseAlarmThreshold.getRequestData() + EversenseE3Writer.writeInt16(threshold) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response() : EversenseBasePacket.Response() +} + +class SetSettingPredictiveAlarmEnabledPacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveAlert.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingPredictiveHighAlarmEnabledPacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveHighAlert.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingPredictiveHighThresholdPacket(private val threshold: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteTwoByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveHighTarget.getRequestData() + EversenseE3Writer.writeInt16(threshold) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingPredictiveHighTimePacket(private val minutes: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveHighTime.getRequestData() + byteArrayOf(minutes.toByte()) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingPredictiveLowAlarmEnabledPacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveLowAlert.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingPredictiveLowThresholdPacket(private val threshold: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteTwoByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteTwoByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveLowTarget.getRequestData() + EversenseE3Writer.writeInt16(threshold) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingPredictiveLowTimePacket(private val minutes: Int) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.PredictiveLowTime.getRequestData() + byteArrayOf(minutes.toByte()) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingRateEnabledPacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.RateAlert.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingRateFallingEnabledPacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.RateFallingAlert.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingRateFallingThresholdPacket(private val threshold: Double) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.RateFallingThreshold.getRequestData() + EversenseE3Writer.writeDouble(threshold) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingRateRisingEnabledPacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.RateRisingAlert.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingRateRisingThresholdPacket(private val threshold: Double) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.RateRisingThreshold.getRequestData() + EversenseE3Writer.writeDouble(threshold) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} + +class SetSettingVibratePacket(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.e3(EversenseE3Packets.WriteSingleByteSerialFlashRegisterCommandId, EversenseE3Packets.WriteSingleByteSerialFlashRegisterResponseId)) { + + override fun getRequestData(): ByteArray { + return EversenseE3Memory.VibrateMode.getRequestData() + EversenseE3Writer.writeBoolean(enabled) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/EversenseE3Packets.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/EversenseE3Packets.kt new file mode 100644 index 000000000000..6c1a50aa8b24 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/EversenseE3Packets.kt @@ -0,0 +1,131 @@ +package app.aaps.plugins.eversense.packets.e3 + +class EversenseE3Packets { + companion object { + const val AssertSnoozeAgainsAlarmCommandId = 20.toByte() + const val AssertSnoozeAgainsAlarmResponseId = 148.toByte() + const val CalibrationAlertPush = 77.toByte() + const val CalibrationPush = 67.toByte() + const val CalibrationSwitchPush = 76.toByte() + const val ChangeTimingParametersCommandId = 117.toByte() + const val ChangeTimingParametersResponseId = 245.toByte() + const val ClearErrorFlagsCommandId = 4.toByte() + const val ClearErrorFlagsResponseId = 132.toByte() + const val DisconnectBLESavingBondingInformationCommandId = 116.toByte() + const val DisconnectBLESavingBondingInformationResponseId = 244.toByte() + const val EnterDiagnosticModeCommandId = 118.toByte() + const val EnterDiagnosticModeResponseId = 246.toByte() + const val ErrorResponseId = 128.toByte() + const val ExerciseVibrationCommandId = 106.toByte() + const val ExerciseVibrationResponseId = 234.toByte() + const val ExitDiagnosticModeCommandId = 119.toByte() + const val ExitDiagnosticModeResponseId = 247.toByte() + const val GlucoseLevelAlarmPush = 64.toByte() + const val GlucoseLevelAlertPush = 65.toByte() + const val HardwareStatusPush = 69.toByte() + const val KeepAlivePush = 80.toByte() + const val LinkTransmitterWithSensorCommandId = 2.toByte() + const val LinkTransmitterWithSensorResponseId = 130.toByte() + const val MarkPatientEventRecordAsDeletedCommandId = 29.toByte() + const val MarkPatientEventRecordAsDeletedResponseId = 157.toByte() + const val PingCommandId = 1.toByte() + const val PingResponseId = 129.toByte() + const val RateAndPredictiveAlertPush = 66.toByte() + const val ReadAllAvailableSensorsResponseId = 134.toByte() + const val ReadAllSensorGlucoseAlertsInSpecifiedRangeCommandId = 113.toByte() + const val ReadAllSensorGlucoseAlertsInSpecifiedRangeResponseId = 241.toByte() + const val ReadAllSensorGlucoseDataInSpecifiedRangeCommandId = 112.toByte() + const val ReadAllSensorGlucoseDataInSpecifiedRangeResponseId = 240.toByte() + const val ReadCurrentTransmitterDateAndTimeCommandId = 25.toByte() + const val ReadCurrentTransmitterDateAndTimeResponseId = 153.toByte() + const val ReadFirstAndLastBloodGlucoseDataRecordNumbersCommandId = 23.toByte() + const val ReadFirstAndLastBloodGlucoseDataRecordNumbersResponseId = 151.toByte() + const val ReadFirstAndLastErrorLogRecordNumbersCommandId = 39.toByte() + const val ReadFirstAndLastErrorLogRecordNumbersResponseId = 167.toByte() + const val ReadFirstAndLastMiscEventLogRecordNumbersCommandId = 35.toByte() + const val ReadFirstAndLastMiscEventLogRecordNumbersResponseId = 163.toByte() + const val ReadFirstAndLastPatientEventRecordNumbersCommandId = 28.toByte() + const val ReadFirstAndLastPatientEventRecordNumbersResponseId = 156.toByte() + const val ReadFirstAndLastSensorGlucoseAlertRecordNumbersCommandId = 18.toByte() + const val ReadFirstAndLastSensorGlucoseAlertRecordNumbersResponseId = 146.toByte() + const val ReadFirstAndLastSensorGlucoseRecordNumbersCommandId = 14.toByte() + const val ReadFirstAndLastSensorGlucoseRecordNumbersResponseId = 142.toByte() + const val ReadFourByteSerialFlashRegisterCommandId = 46.toByte() + const val ReadFourByteSerialFlashRegisterResponseId = 174.toByte() + const val ReadLogOfBloodGlucoseDataInSpecifiedRangeCommandId = 114.toByte() + const val ReadLogOfBloodGlucoseDataInSpecifiedRangeResponseId = 242.toByte() + const val ReadLogOfPatientEventsInSpecifiedRangeCommandId = 115.toByte() + const val ReadLogOfPatientEventsInSpecifiedRangeResponseId = 243.toByte() + const val ReadNByteSerialFlashRegisterCommandId = 48.toByte() + const val ReadNByteSerialFlashRegisterResponseId = 176.toByte() + const val ReadSensorGlucoseAlertsAndStatusCommandId = 16.toByte() + const val ReadSensorGlucoseAlertsAndStatusResponseId = 144.toByte() + const val ReadSensorGlucoseCommandId = 8.toByte() + const val ReadSensorGlucoseResponseId = 136.toByte() + const val ReadSingleBloodGlucoseDataRecordCommandId = 22.toByte() + const val ReadSingleBloodGlucoseDataRecordResponseId = 150.toByte() + const val ReadSingleByteSerialFlashRegisterCommandId = 42.toByte() + const val ReadSingleByteSerialFlashRegisterResponseId = 170.toByte() + const val ReadSingleMiscEventLogCommandId = 34.toByte() + const val ReadSingleMiscEventLogResponseId = 162.toByte() + const val ReadSinglePatientEventCommandId = 27.toByte() + const val ReadSinglePatientEventResponseId = 155.toByte() + const val ReadSingleSensorGlucoseAlertRecordCommandId = 17.toByte() + const val ReadSingleSensorGlucoseAlertRecordResponseId = 145.toByte() + const val ReadSingleSensorGlucoseDataRecordResponseId = 137.toByte() + const val ReadTwoByteSerialFlashRegisterCommandId = 44.toByte() + const val ReadTwoByteSerialFlashRegisterResponseId = 172.toByte() + const val ResetTransmitterCommandId = 3.toByte() + const val ResetTransmitterResponseId = 131.toByte() + const val SaveBLEBondingInformationCommandId = 105.toByte() + const val SaveBLEBondingInformationResponseId = 233.toByte() + const val SendBloodGlucoseDataCommandId = 21.toByte() + const val SendBloodGlucoseDataResponseId = 149.toByte() + // E3 uses a different calibration command with two timestamps (sample + current) + const val SendBloodGlucoseDataWithTwoTimestampsCommandId = 60.toByte() // 0x3C + const val SendBloodGlucoseDataWithTwoTimestampsResponseId = 188.toByte() // 0xBC + + const val SensorReadAlertPush = 73.toByte() + const val SensorReplacement2Push = 75.toByte() + const val SensorReplacementPush = 68.toByte() + const val SetCurrentTransmitterDateAndTimeCommandId = 7.toByte() + const val SetCurrentTransmitterDateAndTimeResponseId = 135.toByte() + const val StartSelfTestSequenceCommandId = 5.toByte() + const val StartSelfTestSequenceResponseId = 133.toByte() + const val TestResponseId = 224.toByte() + const val TransmitterBatteryPush = 71.toByte() + const val TransmitterEOLPush = 74.toByte() + const val WriteFourByteSerialFlashRegisterCommandId = 47.toByte() + const val WriteFourByteSerialFlashRegisterResponseId = 175.toByte() + const val WriteNByteSerialFlashRegisterCommandId = 49.toByte() + const val WriteNByteSerialFlashRegisterResponseId = 177.toByte() + const val WritePatientEventCommandId = 26.toByte() + const val WritePatientEventResponseId = 154.toByte() + const val WriteSingleByteSerialFlashRegisterCommandId = 43.toByte() + const val WriteSingleByteSerialFlashRegisterResponseId = 171.toByte() + const val WriteSingleMiscEventLogRecordCommandId = 36.toByte() + const val WriteSingleMiscEventLogRecordResponseId = 164.toByte() + const val WriteTwoByteSerialFlashRegisterCommandId = 45.toByte() + const val WriteTwoByteSerialFlashRegisterResponseId = 173.toByte() + + fun isPushPacket(data: Byte): Boolean { + // KeepAlivePush (0x50) triggers normal glucose + sync cycle. + // GlucoseLevelAlarmPush (0x40), GlucoseLevelAlertPush (0x41), + // RateAndPredictiveAlertPush (0x42) are glucose push notifications + // that the transmitter sends unsolicited after calibration or alarm events. + // TransmitterBatteryPush (0x47) and SensorReadAlertPush (0x49) are also + // push packets — without them AAPS would wait up to 100s for KeepAlive + // instead of reacting immediately to the real-time glucose push. + return data == KeepAlivePush || + data == GlucoseLevelAlarmPush || + data == GlucoseLevelAlertPush || + data == RateAndPredictiveAlertPush || + data == TransmitterBatteryPush || + data == SensorReadAlertPush + } + + fun isErrorPacket(data: Byte): Boolean { + return data == ErrorResponseId + } + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/util/E3WireValues.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/util/E3WireValues.kt new file mode 100644 index 000000000000..3c4f371a7396 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e3/util/E3WireValues.kt @@ -0,0 +1,46 @@ +package app.aaps.plugins.eversense.packets.e3.util + +import app.aaps.plugins.eversense.protocol.BinaryFields +import app.aaps.plugins.eversense.protocol.WireEncoding +import java.util.TimeZone +import kotlin.math.abs + +/** Compatibility entry points for the shared binary codec; no packet owns its own date math. */ +class EversenseE3Writer { + companion object { + fun generateChecksumCRC16(data: ByteArray): ByteArray = WireEncoding.crc16(data) + fun writeDate(timestamp: Long): ByteArray = BinaryFields.date(timestamp) + fun writeTime(timestamp: Long): ByteArray = BinaryFields.time(timestamp) + fun writeTimezone(timestamp: Long): ByteArray { + val offset = TimeZone.getDefault().getOffset(timestamp) + return BinaryFields.time(abs(offset).toLong()) + byteArrayOf(if (offset < 0) 0xff.toByte() else 0) + } + fun writeBoolean(value: Boolean): ByteArray = byteArrayOf(if (value) 0x55 else 0) + fun writeDouble(value: Double): ByteArray = writeInt16((value * 10).toInt()) + fun writeInt16(value: Int): ByteArray = BinaryFields.littleEndian(value.toLong(), 2) + } +} + +class EversenseE3Parser { + companion object { + private fun available(data: UByteArray, start: Int, width: Int, operation: String) { + require(data.size >= start + width) { "$operation: data too short (size=${data.size}, start=$start)" } + } + fun readDate(data: UByteArray, start: Int): Long { + available(data, start, 2, "readDate") + return BinaryFields.dateMillis(data, start) + } + fun readTime(data: UByteArray, start: Int): Long { + available(data, start, 2, "readTime") + return BinaryFields.timeMillis(data, start) + } + fun readTimezone(data: UByteArray, start: Int): Long { + available(data, start, 3, "readTimezone") + return BinaryFields.offsetMillis(data, start) + } + fun readGlucose(data: UByteArray, start: Int): Int { + available(data, start, 2, "readGlucose") + return BinaryFields.unsigned(data, start, 2).toInt() + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365DataQueries.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365DataQueries.kt new file mode 100644 index 000000000000..404435eb32d4 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365DataQueries.kt @@ -0,0 +1,482 @@ +package app.aaps.plugins.eversense.packets.e365 + +import app.aaps.plugins.eversense.enums.CalibrationFlag +import app.aaps.plugins.eversense.enums.CalibrationMode +import app.aaps.plugins.eversense.enums.CalibrationPhase +import app.aaps.plugins.eversense.enums.CalibrationReadiness +import app.aaps.plugins.eversense.enums.EversenseAlarm +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.GlucoseHistoryItem +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.e365.utils.toInt +import app.aaps.plugins.eversense.packets.e365.utils.toShort +import app.aaps.plugins.eversense.packets.e365.utils.toUnix +import app.aaps.plugins.eversense.packets.e365.utils.toUtfString +import app.aaps.plugins.eversense.protocol.GlucoseDecoders +import app.aaps.plugins.eversense.protocol.PacketSpec +import app.aaps.plugins.eversense.util.EversenseLogger +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlinx.serialization.Serializable + +class GetActiveAlarmsPacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadActiveAlerts)) { + + override fun getRequestData(): ByteArray = byteArrayOf() + // 42 22 -> CmdType & CmdId + // 03 -> Active alarm count + // [code, flag, priority] * count -> 3 bytes per alarm + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + val count = receivedData[2].toInt() and 0xFF + val alarms = mutableListOf() + for (i in 0 until count) { + val offsetStart = i * 3 + 3 + if (receivedData.size < offsetStart + 3) { + EversenseLogger.warning("GetActiveAlarmsPacket", "Missing data for alarm $i") + break + } + alarms.add(ActiveAlarm( + code = EversenseAlarm.from(receivedData[offsetStart].toInt() and 0xFF), + codeRaw = receivedData[offsetStart].toInt() and 0xFF, + flag = receivedData[offsetStart + 1].toInt() and 0xFF, + priority = receivedData[offsetStart + 2].toInt() and 0xFF + )) + } + alarms.sortBy { it.priority } + EversenseLogger.debug("GetActiveAlarmsPacket") { "Active alarms: ${alarms.map { it.code.title }}" } + return Response(count = count, alarms = alarms) + } + + data class Response( + val count: Int, + val alarms: List + ) : EversenseBasePacket.Response() +} + +data class AlertHistoryItem( + val datetime: Long, + val code: EversenseAlarm +) + +class GetAlertsLogValuesPacket( + private val from: Int, + private val to: Int +) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadLogsId, Eversense365Packets.ReadLogValue)) { + + override fun getRequestData(): ByteArray { + return byteArrayOf( + Eversense365Packets.LogTypeAlerts, + (from and 0xFF).toByte(), ((from shr 8) and 0xFF).toByte(), + ((from shr 16) and 0xFF).toByte(), ((from shr 24) and 0xFF).toByte(), + (to and 0xFF).toByte(), ((to shr 8) and 0xFF).toByte(), + ((to shr 16) and 0xFF).toByte(), ((to shr 24) and 0xFF).toByte() + ) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + if (receivedData[6].toInt() != Eversense365Packets.LogTypeAlerts.toInt()) { + EversenseLogger.error("GetAlertsLogValuesPacket", "Invalid log type: ${receivedData[6]}") + return Response(count = 0, alertHistory = emptyList()) + } + val actualData = receivedData.drop(7).toUByteArray() + val recordLength = 60 + val history = mutableListOf() + var i = 0 + while (i + recordLength <= actualData.size) { + val chunk = actualData.copyOfRange(i, i + recordLength) + val datetime = chunk.copyOfRange(4, 12).toUnix() + val alarmCode = chunk[12].toInt() and 0xFF + history.add(AlertHistoryItem(datetime = datetime, code = EversenseAlarm.from(alarmCode))) + i += recordLength + } + return Response(count = history.size, alertHistory = history) + } + + data class Response( + val count: Int, + val alertHistory: List + ) : EversenseBasePacket.Response() +} + +class GetCalibrationInfoPacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadCalibrationInfo)) { +// Parsed message: + // 42 1D -> CmdType & CmdId + // 00 -> Current calibration phase + // 06 -> Ready for calibration (CALIBRATION_READINESS) + // 00 00 00 00 00 00 00 00 -> Next calibration datetime + // 00 -> Number of calibrations per day + // 00 -> Number of calibrations in this Phase + // 00 00 -> Minutes allowed before next calibration due + // 00 00 -> Minutes allowed after next calibration due + // 00 00 -> Number of completed calibrations + // 00 00 00 00 00 00 00 00 -> Start datetime of current phase + // 00 00 -> Sensor lifetime + // 00 00 -> Warmup duration + // 00 00 -> Minutes until next calibration + // 00 00 00 00 00 00 00 00 -> Last calibration datetime + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + val calPerDay = receivedData[12].toInt() + val rawReadiness = receivedData[3].toInt() and 0xFF + EversenseLogger.debug("GetCalibrationInfoPacket") { "Raw calibration readiness byte: $rawReadiness (0x${rawReadiness.toString(16)})" } + return Response( + currentPhase = CalibrationPhase.from365(receivedData[2].toInt(), calPerDay), + calibrationReadiness = CalibrationReadiness.from365(rawReadiness), + calibrationMode = CalibrationMode.from365(calPerDay), + nextCalibration = receivedData.copyOfRange(4, 12).toUnix(), + lastCalibration = receivedData.copyOfRange(34, 42).toUnix(), + ) + } + + data class Response( + val currentPhase: CalibrationPhase, + val calibrationReadiness: CalibrationReadiness, + val calibrationMode: CalibrationMode, + val nextCalibration: Long, + val lastCalibration: Long + ) : EversenseBasePacket.Response() +} + +@Serializable + +data class CalibrationHistoryItem( + val datetime: Long, + val glucoseInMgDl: Int, + val flag: CalibrationFlag +) + +class GetCalibrationLogValuesPacket( + private val from: Int, + private val to: Int +) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadLogsId, Eversense365Packets.ReadLogValue)) { + + override fun getRequestData(): ByteArray { + return byteArrayOf( + Eversense365Packets.LogTypeCalibrations, + (from and 0xFF).toByte(), ((from shr 8) and 0xFF).toByte(), + ((from shr 16) and 0xFF).toByte(), ((from shr 24) and 0xFF).toByte(), + (to and 0xFF).toByte(), ((to shr 8) and 0xFF).toByte(), + ((to shr 16) and 0xFF).toByte(), ((to shr 24) and 0xFF).toByte() + ) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + if (receivedData[6].toInt() != Eversense365Packets.LogTypeCalibrations.toInt()) { + EversenseLogger.error("GetCalibrationLogValuesPacket", "Invalid log type: ${receivedData[6]}") + return Response(count = 0, calibrationHistory = emptyList()) + } + val actualData = receivedData.drop(7).toUByteArray() + val recordLength = 56 + // Offset: recordLength(4) + datetime(8) + FsStartEndFlag(2) + ProcessingDatetime(8) + // + SampleDatetime(8) + MmaFSDatetime(8) + DecisionDatetime(8) = 46 + val offsetGlucose = 4 + 8 + 2 + 8 + 8 + 8 + 8 + val offsetFlag = offsetGlucose + 2 + val history = mutableListOf() + var i = 0 + while (i + recordLength <= actualData.size) { + val chunk = actualData.copyOfRange(i, i + recordLength) + val datetime = chunk.copyOfRange(4, 12).toUnix() + val glucose = (chunk[offsetGlucose].toInt() and 0xFF) or ((chunk[offsetGlucose + 1].toInt() and 0xFF) shl 8) + val flag = CalibrationFlag.from(chunk[offsetFlag].toInt() and 0xFF) + history.add(CalibrationHistoryItem(datetime = datetime, glucoseInMgDl = glucose, flag = flag)) + i += recordLength + } + return Response(count = history.size, calibrationHistory = history) + } + + data class Response( + val count: Int, + val calibrationHistory: List + ) : EversenseBasePacket.Response() +} + +class GetGlucoseDataPacket(private val sensorIdLen: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadGlucoseData)) { + + override fun parseResponse(): Response? = GlucoseDecoders.v2(receivedData, sensorIdLen)?.let { + Response(it.timestamp, it.glucose, it.trend, it.signal, it.sensorId, it.raw) + } + + data class Response(val datetime: Long, val glucoseInMgDl: Int, val trend: EversenseTrendArrow, + val signalStrength: Int, val sensorId: String = "", val rawResponseHex: String = "") : EversenseBasePacket.Response() +} + +class GetGlucoseLogValuesPacket( + private val from: Int, + private val to: Int, + private val sensorIdLength: Int = 10 +) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, 0x62.toByte(), Eversense365Packets.ReadLogValue)) { + + override fun getRequestData(): ByteArray { + val logType: Byte = 13 // LogTypes.Glucose + return byteArrayOf( + logType, + (from and 0xFF).toByte(), ((from shr 8) and 0xFF).toByte(), + ((from shr 16) and 0xFF).toByte(), ((from shr 24) and 0xFF).toByte(), + (to and 0xFF).toByte(), ((to shr 8) and 0xFF).toByte(), + ((to shr 16) and 0xFF).toByte(), ((to shr 24) and 0xFF).toByte() + ) + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + if (receivedData[6].toInt() != 13) { + EversenseLogger.error("GetGlucoseLogValuesPacket", "Invalid log type: ${receivedData[6]}") + return Response(count = 0, glucoseHistory = emptyList()) + } + val actualData = receivedData.drop(7).toUByteArray() + val recordLength = 193 + val offsetGlucose = sensorIdLength + 8 + 4 + val offsetTrend = offsetGlucose + 2 + 4 + val history = mutableListOf() + var i = 0 + while (i + recordLength <= actualData.size) { + val chunk = actualData.copyOfRange(i, i + recordLength) + val datetime = chunk.copyOfRange(4, 12).toUnix() + val glucose = (chunk[offsetGlucose].toInt() and 0xFF) or + ((chunk[offsetGlucose + 1].toInt() and 0xFF) shl 8) + val trend = getTrend(chunk[offsetTrend].toInt() and 0xFF) + i += recordLength + // Safety ceiling matches EversenseKit's (loopandlearn/bastiaanv, the reference iOS + // implementation this port is based on), tightened from 1000 to 450 mg/dl. + if (glucose >= 450) { + EversenseLogger.warning("GetGlucoseLogValuesPacket", "Glucose exceeds limits: $glucose — skipping") + continue + } + val rawHex = chunk.joinToString("") { "%02X".format(it.toInt()) } + history.add(GlucoseHistoryItem(valueInMgDl = glucose, datetime = datetime, trend = trend, rawResponseHex = rawHex)) + } + EversenseLogger.debug("GetGlucoseLogValuesPacket") { "History records: ${history.size}" } + return Response(count = history.size, glucoseHistory = history) + } + + private fun getTrend(value: Int): EversenseTrendArrow = + GlucoseDecoders.trend(value, extended = true, unknown = EversenseTrendArrow.FLAT) + + data class Response( + val count: Int, + val glucoseHistory: List + ) : EversenseBasePacket.Response() +} + +enum class LogType(val value: Byte) { + ALERTS(0), + CALIBRATIONS(6), + GLUCOSE(13) +} + +class GetLogRangePacket365(private val logType: LogType) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadLogRange)) { + + override fun getRequestData(): ByteArray = byteArrayOf(logType.value) + // 42 38 -> CmdType & CmdId + // XX -> log type + // 00 00 00 00 -> rangeFrom (UInt32 little-endian) + // 00 00 00 00 -> rangeTo (UInt32 little-endian) + + override fun parseResponse(): Response? { + if (receivedData.size < 11) return null + val rangeFrom = ((receivedData[3].toLong() and 0xFF) or + ((receivedData[4].toLong() and 0xFF) shl 8) or + ((receivedData[5].toLong() and 0xFF) shl 16) or + ((receivedData[6].toLong() and 0xFF) shl 24)).toInt() + val rangeTo = ((receivedData[7].toLong() and 0xFF) or + ((receivedData[8].toLong() and 0xFF) shl 8) or + ((receivedData[9].toLong() and 0xFF) shl 16) or + ((receivedData[10].toLong() and 0xFF) shl 24)).toInt() + app.aaps.plugins.eversense.util.EversenseLogger.debug("GetLogRangePacket365") { "Log range: $rangeFrom - $rangeTo" } + return Response(rangeFrom = rangeFrom, rangeTo = rangeTo) + } + + data class Response(val rangeFrom: Int, val rangeTo: Int) : EversenseBasePacket.Response() +} + +class GetPatientSettingsPacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadPatientInformation)) { + + override fun parseResponse(): Response? { + if (receivedData.size < 65) { + return null + } + // Message parsed: + // 42 21 -> CmdType & CmdId + // 44 33 30 36 33 36 36 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 -> Transmitter name + // 38 2E 30 2E 34 00 00 00 00 00 00 00 00 00 00 00 -> Recent MMA Version + // 00 -> Is clinical mode enabled + // 00 -> Is do not Disturb Enabled + // 2C 01 -> BLE connect time in sec -> 300s + // 46 00 -> Low sugar target in mg/dl + // B4 00 -> High sugar target in mg/dl + // 00 -> Alarm rate falling enabled + // 19 -> Alarm rate falling threshold + // 00 -> Alarm rate rising enabled + // 19 -> Alarm rate rising threshold + // 00 -> Alarm Predictive Low enabled + // 14 -> Alarm Predictive Low Time + // 00 -> Alarm Predictive High enabled + // 14 -> Alarm Predictive High Time + // 01 -> Alarm High Glucose enabled + // FA 00 -> Alarm High Glucose Threshold + // 1E -> Alarm High Glucose Repeat Interval + // 41 00 -> Alarm Low Glucose Threshold + // 0F -> Alarm Low Glucose Repeat Interval + // 34 -> Battery Temp Thresh Mode Change + // 44 -> Battery Temp Thresh Warn + return Response( + vibrateMode = receivedData[44].toInt() != 0x00, + highGlucoseEnabled = receivedData[59].toInt() != 0x00, + highGlucoseAlarmInMgDl = receivedData.copyOfRange(60, 62).toShort().toInt(), + lowGlucoseAlarmInMgDl = receivedData.copyOfRange(63, 65).toShort().toInt(), + predictionLowEnabled = receivedData[55].toInt() != 0x00, + predictionHighEnabled = receivedData[57].toInt() != 0x00, + predictionFallingInterval = receivedData[56].toInt(), + predictionRisingInterval = receivedData[58].toInt(), + predictionFallingThreshold = receivedData.copyOfRange(47, 49).toShort().toInt(), + predictionRisingThreshold = receivedData.copyOfRange(49, 51).toShort().toInt(), + rateFallingEnabled = receivedData[51].toInt() != 0x00, + rateRisingEnabled = receivedData[53].toInt() != 0x00, + rateFallingThreshold = receivedData[52].toDouble() / 10, + rateRisingThreshold = receivedData[54].toDouble() / 10, + ) + } + + data class Response( + val vibrateMode: Boolean, + val highGlucoseEnabled: Boolean, + val lowGlucoseAlarmInMgDl: Int, + val highGlucoseAlarmInMgDl: Int, + val predictionLowEnabled: Boolean, + val predictionHighEnabled: Boolean, + val predictionFallingInterval: Int, + val predictionRisingInterval: Int, + val predictionFallingThreshold: Int, + val predictionRisingThreshold: Int, + val rateFallingEnabled: Boolean, + val rateRisingEnabled: Boolean, + val rateFallingThreshold: Double, + val rateRisingThreshold: Double + ) : EversenseBasePacket.Response() +} + +class GetSensorInformationPacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadSensorInformation)) { +// 42 20 + // 33 30 36 33 36 36 00 00 00 00 00 00 00 00 00 00 + // 44 33 30 36 33 36 36 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + // 26 9f 14 b7 c4 00 00 00 + // 29 6d 23 06 + // 30352e30302e30312e30374d000030312e30360030312e30300030312e30300030312e30300000000111008c012c01010a7900000000000076000083d959f3c30000006d01790000000000007600005730352e30302e30312e30374d2d303600000000000000000030312e30302e30312e30320000000000 + // Message parsed: + // 42 20 -> CmdType & CmdId + // 33 30 36 33 36 36 00 00 00 00 00 00 00 00 00 00 -> Serial number + // 44 33 30 36 33 36 36 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 -> Transmitter name + // 1A 44 08 CB BF 00 00 00 -> Current datetime + // 29 6D 23 06 -> Transmitter model + // 30 35 2E 30 30 2E 30 31 2E 30 37 4D 00 00 -> Current firmware version + // 30 31 2E 30 36 00 -> Comm version + // 30 31 2E 30 30 00 -> Register map version + // 30 31 2E 30 30 00 -> Log map version + // 30 31 2E 30 30 00 -> Push map version + // 00 -> Glucose algorithm version major + // 00 -> Glucose algorithm version minor + // 01 -> MMA functionality + // 11 00 -> Transmitter mode + // 8C 01 -> Transmitter life remaining + // 2C 01 -> Sensor sample interval + // 01 -> Sensor type + // 0A -> Sensor ID length + // 00 00 00 00 00 00 00 00 00 00 -> Sensor ID (size is based on previous value) + // 00 00 00 00 00 00 00 00 -> Sensor insertion date + // 00 00 -> Sensor life remaining + // 00 00 00 00 00 00 00 00 00 00 -> Detected sensor ID (length is based on Sensor ID length) + // 62 -> Battery percentage + // 30 35 2E 30 30 2E 30 31 2E 30 37 4D 2D 30 36 00 -> Firmware version + // 00 00 00 00 00 00 00 00 -> Operation start datetime + // 30 31 2E 30 30 2E 30 31 2E 30 32 00 00 00 00 00 -> Other firmware version + + override fun parseResponse(): Response? { + if (receivedData.size < 104) { + return null + } + val sensorIdLength = receivedData[103].toInt() + val sensorIdDoubleLength = 2 * sensorIdLength + if (receivedData.size < 139 + sensorIdDoubleLength) { + return null + } + return Response( + serialNumber = receivedData.copyOfRange(2, 18).toUtfString(), + transmitterName = receivedData.copyOfRange(18, 43).toUtfString(), + transmitterDatetime = receivedData.copyOfRange(43, 51).toUnix(), + insertionDate = receivedData.copyOfRange(104+sensorIdLength, 112+sensorIdLength).toUnix(), + mmaFeatures = receivedData[95].toInt(), + batteryLevel = receivedData[114+sensorIdDoubleLength].toInt(), + version = receivedData.copyOfRange(115+sensorIdDoubleLength, 131+sensorIdDoubleLength).toUtfString(), + extVersion = receivedData.copyOfRange(131+sensorIdDoubleLength, 139+sensorIdDoubleLength).toUtfString(), + sensorIdLength = sensorIdLength, + communicationProtocolVersion = receivedData.copyOfRange(69, 75).toUtfString().toDouble() + ) + } + + data class Response( + val serialNumber: String, + val transmitterName: String, + val transmitterDatetime: Long, + val insertionDate: Long, + val mmaFeatures: Int, + val batteryLevel: Int, + val version: String, + val extVersion: String, + val sensorIdLength: Int, + val communicationProtocolVersion: Double + ) : EversenseBasePacket.Response() +} + +class GetSignalStrengthPacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadSignalStrength)) { + + override fun getRequestData(): ByteArray = byteArrayOf() + // Parsed message: + // 42 1B -> CmdType & CmdId + // 01 -> SensorType + // 0A -> Sensor ID length + // 00 00 00 00 00 00 00 00 00 00 -> Sensor ID (length = byte[3]) + // XX XX XX XX XX XX XX XX -> Timestamp + // XX XX -> Signal Strength (raw) + // XX XX XX XX -> Signal Coupling (little-endian float, multiply by 100 for percentage) + // XX -> Placement + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) return null + app.aaps.plugins.eversense.util.EversenseLogger.debug("GetSignalStrengthPacket") { + "Raw response: " + receivedData.joinToString(" ") { it.toString(16).padStart(2, '0') } + } + // Byte [3] = sensor ID length + val sensorIdLength = receivedData[3].toInt() and 0xFF + // Signal coupling float starts at byte 14 + sensorIdLength + val couplingStart = 14 + sensorIdLength + if (receivedData.size < couplingStart + 4) { + app.aaps.plugins.eversense.util.EversenseLogger.warning("GetSignalStrengthPacket", "Response too short: ${receivedData.size} bytes, need ${couplingStart + 4}") + return Response(signalStrength = 0) + } + // Read little-endian float and multiply by 100 for percentage + val floatBytes = byteArrayOf( + receivedData[couplingStart].toByte(), + receivedData[couplingStart + 1].toByte(), + receivedData[couplingStart + 2].toByte(), + receivedData[couplingStart + 3].toByte() + ) + val signalFloat = ByteBuffer.wrap(floatBytes) + .order(ByteOrder.LITTLE_ENDIAN) + .float + val signalPercent = (signalFloat * 100).toInt().coerceIn(0, 100) + app.aaps.plugins.eversense.util.EversenseLogger.debug("GetSignalStrengthPacket") { "sensorIdLength: $sensorIdLength, signalFloat: $signalFloat -> $signalPercent%" } + return Response(signalStrength = signalPercent) + } + + data class Response( + val signalStrength: Int // 0-100, transmitter-to-sensor placement signal + ) : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365SessionCommands.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365SessionCommands.kt new file mode 100644 index 000000000000..94d831f375ae --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365SessionCommands.kt @@ -0,0 +1,246 @@ +package app.aaps.plugins.eversense.packets.e365 + +import app.aaps.plugins.eversense.enums.EversenseAlarm +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.packets.e365.utils.toByteArray +import app.aaps.plugins.eversense.packets.e365.utils.toTimeZone +import app.aaps.plugins.eversense.packets.e365.utils.toUnix +import app.aaps.plugins.eversense.packets.e365.utils.toUnixArray +import app.aaps.plugins.eversense.protocol.CalibrationPayload +import app.aaps.plugins.eversense.protocol.PacketSpec +import app.aaps.plugins.eversense.protocol.PacketTime +import java.time.ZonedDateTime +import java.util.TimeZone +import kotlin.math.abs + +class AuthIdentityPacket(val secret: ByteArray) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.AuthenticateCommandId, Eversense365Packets.AuthenticateResponseId, Eversense365Packets.AuthenticateIdentity)) { + + override fun getRequestData(): ByteArray { + return secret + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response() + } + + class Response: EversenseBasePacket.Response() +} + +class AuthStartPacket(val secret: ByteArray) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.AuthenticateCommandId, Eversense365Packets.AuthenticateResponseId, Eversense365Packets.AuthenticateStart)) { + + override fun getRequestData(): ByteArray { + return secret + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response( + receivedData.copyOfRange(2, 66).toByteArray() + ) + } + + data class Response( + val sessionPublicKey: ByteArray + ) : EversenseBasePacket.Response() +} + +class AuthWhoAmIPacket(private val clientId: ByteArray) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.AuthenticateCommandId, Eversense365Packets.AuthenticateResponseId, Eversense365Packets.AuthenticateWhoAmI)) { + + override fun getRequestData(): ByteArray { + return clientId + } + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response( + receivedData.copyOfRange(2, 34).toByteArray(), + receivedData.copyOfRange(34, 42).toByteArray(), + ((receivedData[42].toInt() shl 8) or receivedData[43].toInt()) == 0, + ) + } + + data class Response( + val serialNumber: ByteArray, + val nonce: ByteArray, + val flags: Boolean + ) : EversenseBasePacket.Response() +} + +class EnterDiagnosticMode365Packet : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.OperationCommandId, Eversense365Packets.OperationResponseId, Eversense365Packets.EnterDiagnosticModeOperationId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class ExitDiagnosticMode365Packet : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.OperationCommandId, Eversense365Packets.OperationResponseId, Eversense365Packets.ExitDiagnosticModeOperationId)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class KeepAlivePacket : EversenseBasePacket(PacketSpec.v2(-1, Eversense365Packets.NotificationResponseId, Eversense365Packets.NotificationKeepAlive)) { + + override fun parseResponse(): Response? { + if (receivedData.isEmpty()) { + return null + } + return Response( + glucoseDatetime = receivedData.copyOfRange(11, 19).toUnix(), + ) + } + + data class Response(val glucoseDatetime: Long) : EversenseBasePacket.Response() +} + +class Ping365Packet : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.ReadCommandId, Eversense365Packets.ReadResponseId, Eversense365Packets.ReadPing)) { + + override fun getRequestData(): ByteArray = byteArrayOf() + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +/** + * Push notification packet for alarms with data payload. + * + * Packet format (empirically confirmed against real device logs - alarm code at [2] correctly + * decoded real alarms like HIGH_GLUCOSE across multiple live captures; [3] was observed to be + * constant/always 0, i.e. it's the reserved byte, not the code): + * [0] = 0x44 (NotificationResponseId) + * [1] = 0x03 (AlarmWithData) + * [2] = alarm code + * [3] = reserved + * [4..11] = alarm datetime (Unix2000) + * [12..] = alarm data + */ + +class PushAlarmWithDataPacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.NotificationResponseId, Eversense365Packets.NotificationAlarmWithData, 0)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.size < 12) return null + val alarmCode = receivedData[2].toInt() and 0xFF + val alarm = EversenseAlarm.from(alarmCode) + val datetime = receivedData.copyOfRange(4, 12).toUnix() + return Response( + alarm = ActiveAlarm(code = alarm, codeRaw = alarmCode, flag = 0, priority = 0), + datetime = datetime + ) + } + + data class Response( + val alarm: ActiveAlarm, + val datetime: Long + ) : EversenseBasePacket.Response() +} + +/** + * Push keep-alive packet that includes battery level and most recent glucose datetime. + * + * Offsets: + * [10] = battery level (raw enum value) + * [11..18] = most recent glucose datetime (Unix2000) + */ + +class PushKeepAlive365Packet : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.NotificationResponseId, Eversense365Packets.NotificationKeepAlive, 0)) { + + override fun getRequestData(): ByteArray = ByteArray(0) + + override fun parseResponse(): Response? { + if (receivedData.size < 19) return null + val batteryLevel = receivedData[OFFSET_BATTERY_LEVEL].toInt() and 0xFF + val glucoseDatetime = receivedData.copyOfRange( + OFFSET_GLUCOSE_DATETIME_START, + OFFSET_GLUCOSE_DATETIME_END + ).toUnix() + return Response( + batteryLevelRaw = batteryLevel, + mostRecentGlucoseDatetime = glucoseDatetime + ) + } + + data class Response( + val batteryLevelRaw: Int, + val mostRecentGlucoseDatetime: Long + ) : EversenseBasePacket.Response() + companion object { + private const val OFFSET_BATTERY_LEVEL = 10 + private const val OFFSET_GLUCOSE_DATETIME_START = 11 + private const val OFFSET_GLUCOSE_DATETIME_END = 19 + } +} + +class SetAppVersion365Packet(private val appVersion: String = "8.0.4") : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteAppVersion)) { + + override fun getRequestData(): ByteArray { + val data = ByteArray(18) + val versionBytes = appVersion.toByteArray(Charsets.US_ASCII) + versionBytes.copyInto(data, 0, 0, minOf(versionBytes.size, 18)) + return data + } + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetBleDisconnect365Packet(private val intervalSeconds: Int = 300) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteBleDisconnect)) { + + override fun getRequestData(): ByteArray { + // UInt16 little-endian interval in seconds + return byteArrayOf( + (intervalSeconds and 0xFF).toByte(), + ((intervalSeconds shr 8) and 0xFF).toByte() + ) + } + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetBloodGlucosePointPacket365(private val glucoseInMgDl: Int, private val timestampMs: Long = PacketTime.nowMillis()) : + EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteCalibration)) { + + override fun getRequestData(): ByteArray = CalibrationPayload.v2(glucoseInMgDl, timestampMs, PacketTime.nowMillis()) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetCurrentDateTimePacket : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteCurrentDateTime)) { + + override fun getRequestData(): ByteArray { + val now = PacketTime.nowMillis() + val timezoneOffset = TimeZone.getDefault().getOffset(now) + val timezoneNegative = if (timezoneOffset < 0) 255.toByte() else 0.toByte() + var request = now.toUnixArray() + request += abs(timezoneOffset).toTimeZone() + request += byteArrayOf(timezoneNegative) + return request + } + + override fun parseResponse(): Response { + return Response() + } + + class Response : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365SettingsCommands.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365SettingsCommands.kt new file mode 100644 index 000000000000..77de51bb2966 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/E365SettingsCommands.kt @@ -0,0 +1,183 @@ +package app.aaps.plugins.eversense.packets.e365 + +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.packets.EversenseBasePacket +import app.aaps.plugins.eversense.protocol.PacketSpec +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class SetHighGlucoseAlarm365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteHighGlucoseAlarm)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetHighGlucoseAlarmEnabled365Packet(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteHighGlucoseAlarmEnable)) { + + override fun getRequestData(): ByteArray = byteArrayOf(if (enabled) 1 else 0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetLowGlucoseAlarm365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteLowGlucoseAlarm)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetPredictionHighEnabled365Packet(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WritePredictionHighEnabled)) { + + override fun getRequestData(): ByteArray = byteArrayOf(if (enabled) 1 else 0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetPredictionHighThreshold365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WritePredictionHighThreshold)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetPredictionHighTime365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WritePredictionHighTime)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetPredictionLowEnabled365Packet(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WritePredictionLowEnabled)) { + + override fun getRequestData(): ByteArray = byteArrayOf(if (enabled) 1 else 0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetPredictionLowThreshold365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WritePredictionLowThreshold)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetPredictionLowTime365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WritePredictionLowTime)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetRateFallingEnabled365Packet(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteRateFallingEnabled)) { + + override fun getRequestData(): ByteArray = byteArrayOf(if (enabled) 1 else 0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetRateFallingThreshold365Packet(private val value: Double) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteRateFallingThreshold)) { + + override fun getRequestData(): ByteArray { + val buf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN) + buf.putFloat(value.toFloat()) + return buf.array() + } + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetRateRisingEnabled365Packet(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteRateRisingEnabled)) { + + override fun getRequestData(): ByteArray = byteArrayOf(if (enabled) 1 else 0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetRateRisingThreshold365Packet(private val value: Double) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteRateRisingThreshold)) { + + override fun getRequestData(): ByteArray { + val buf = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN) + buf.putFloat(value.toFloat()) + return buf.array() + } + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetRepeatHighGlucose365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteHighGlucoseAlarmRepeat)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetRepeatLowGlucose365Packet(private val value: Int) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteLowGlucoseAlarmRepeat)) { + + override fun getRequestData(): ByteArray = byteArrayOf( + (value and 0xFF).toByte(), + ((value shr 8) and 0xFF).toByte() + ) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} + +class SetVibrateMode365Packet(private val enabled: Boolean) : EversenseBasePacket(PacketSpec.v2(Eversense365Packets.WriteCommandId, Eversense365Packets.WriteResponseId, Eversense365Packets.WriteVibrateMode)) { + + override fun getRequestData(): ByteArray = byteArrayOf(if (enabled) 1 else 0) + + override fun parseResponse(): Response = Response() + + class Response : EversenseBasePacket.Response() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/Eversense365Packets.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/Eversense365Packets.kt new file mode 100644 index 000000000000..72eb6731c6c5 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/Eversense365Packets.kt @@ -0,0 +1,75 @@ +package app.aaps.plugins.eversense.packets.e365 + +class Eversense365Packets { + companion object { + + const val AuthenticateCommandId = 0x09.toByte() + const val AuthenticateResponseId = 0x0B.toByte() + + const val ReadCommandId = 0x02.toByte() + const val ReadResponseId = 0x42.toByte() + + const val WriteCommandId = 0x03.toByte() + const val WriteResponseId = 0x43.toByte() + const val OperationCommandId = 0x01.toByte() + const val OperationResponseId = 0x41.toByte() + const val EnterDiagnosticModeOperationId = 0x08.toByte() + const val ExitDiagnosticModeOperationId = 0x09.toByte() + + const val NotificationResponseId = 0x44.toByte() + + const val AuthenticateWhoAmI = 0x01.toByte() + const val AuthenticateIdentity = 0x02.toByte() + const val AuthenticateStart = 0x03.toByte() + + const val ReadPing = 0x01.toByte() + const val ReadLogRangeOld = 0x09.toByte() + const val ReadSignalStrength = 0x1B.toByte() + const val ReadCalibrationInfo = 0x1D.toByte() + const val ReadGlucoseData = 0x1F.toByte() + const val ReadSensorInformation = 0x20.toByte() + const val ReadPatientInformation = 0x21.toByte() + const val ReadActiveAlerts = 0x22.toByte() + const val ReadLogRange = 0x38.toByte() + const val ReadLogValue = 0x3A.toByte() + + const val WriteCurrentDateTime = 0x01.toByte() + const val WriteCalibration = 0x0C.toByte() + const val WriteAppVersion = 0x0E.toByte() + const val WriteVibrateMode = 0x10.toByte() + const val WriteBleDisconnect = 0x11.toByte() + const val WritePredictionLowThreshold = 0x12.toByte() + const val WritePredictionHighThreshold = 0x13.toByte() + const val WriteRateFallingEnabled = 0x14.toByte() + const val WriteRateFallingThreshold = 0x15.toByte() + const val WriteRateRisingEnabled = 0x16.toByte() + const val WriteRateRisingThreshold = 0x17.toByte() + const val WritePredictionLowEnabled = 0x18.toByte() + const val WritePredictionLowTime = 0x19.toByte() + const val WritePredictionHighEnabled = 0x1A.toByte() + const val WritePredictionHighTime = 0x1B.toByte() + const val WriteHighGlucoseAlarmEnable = 0x1C.toByte() + const val WriteHighGlucoseAlarm = 0x1D.toByte() + const val WriteHighGlucoseAlarmRepeat = 0x1E.toByte() + const val WriteLowGlucoseAlarm = 0x1F.toByte() + const val WriteLowGlucoseAlarmRepeat = 0x20.toByte() + + const val NotificationKeepAlive = 0x02.toByte() + const val NotificationAlarmWithData = 0x03.toByte() + + const val ReadLogsId = 0x62.toByte() + + const val LogTypeAlerts: Byte = 0 + const val LogTypeCalibrations: Byte = 6 + const val LogTypeGlucose: Byte = 13 + + + fun isNotificationPacket(value: Byte): Boolean { + return value == NotificationResponseId + } + + fun isKeepAlivePacket(value1: Byte, value2: Byte): Boolean { + return value1 == NotificationResponseId && value2 == NotificationKeepAlive + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/utils/ByteArrayUtil.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/utils/ByteArrayUtil.kt new file mode 100644 index 000000000000..404d131edc33 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/packets/e365/utils/ByteArrayUtil.kt @@ -0,0 +1,19 @@ +package app.aaps.plugins.eversense.packets.e365.utils + +import app.aaps.plugins.eversense.protocol.BinaryFields + +fun UByteArray.toUtfString(): String = buildString { + this@toUtfString.filter { it.toInt() != 0 }.forEach { append(it.toInt().toChar()) } +} +fun Short.toByteArray(): ByteArray = BinaryFields.littleEndian(toLong(), 2) +fun Int.toTimeZone(): ByteArray { + val minutes = this / 60_000 + return BinaryFields.clockFields(minutes / 60, minutes % 60) +} +fun UByteArray.toShort(): Short = BinaryFields.unsigned(this, width = 2).toShort() +fun UByteArray.toInt(): Int = BinaryFields.unsigned(this, width = 2).toInt() +fun UByteArray.toLong(): Long = BinaryFields.unsigned(this) +fun ByteArray.toLong(): Long = BinaryFields.unsigned(toUByteArray()) +const val UNIX = 946_684_800_000 +fun UByteArray.toUnix(): Long = BinaryFields.sensorTimestamp(this) +fun Long.toUnixArray(): ByteArray = BinaryFields.sensorTimestamp(this) diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/BinaryFields.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/BinaryFields.kt new file mode 100644 index 000000000000..022857655927 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/BinaryFields.kt @@ -0,0 +1,59 @@ +package app.aaps.plugins.eversense.protocol + +import java.util.Calendar +import java.util.TimeZone + +/** Binary primitives shared by E3, 365 and DMS; protocol units remain explicit at call sites. */ +internal object BinaryFields { + private val utc = TimeZone.getTimeZone("GMT") + const val SENSOR_EPOCH_MS = 946_684_800_000L + + fun littleEndian(value: Long, width: Int): ByteArray = ByteArray(width) { position -> + (value ushr (position * 8)).toByte() + } + fun unsigned(bytes: UByteArray, offset: Int = 0, width: Int = bytes.size - offset): Long { + var number = 0L + repeat(width) { position -> number = number or (bytes[offset + position].toLong() shl (position * 8)) } + return number + } + private fun calendar(timestamp: Long) = Calendar.getInstance(utc).apply { timeInMillis = timestamp } + + fun date(timestamp: Long): ByteArray { + val value = calendar(timestamp) + val month = value.get(Calendar.MONTH) + 1 + val bits = value.get(Calendar.DAY_OF_MONTH) or ((month and 7) shl 5) or + (((value.get(Calendar.YEAR) - 2000) * 2 + (month ushr 3)) shl 8) + return littleEndian(bits.toLong(), 2) + } + fun time(timestamp: Long): ByteArray { + val value = calendar(timestamp) + return clockFields(value.get(Calendar.HOUR_OF_DAY), value.get(Calendar.MINUTE), value.get(Calendar.SECOND)) + } + fun clockFields(hour: Int, minute: Int, second: Int = 0): ByteArray = byteArrayOf( + (((minute and 7) shl 5) or (second / 2)).toByte(), + ((hour shl 3) or ((minute and 56) ushr 3)).toByte() + ) + fun dateMillis(bytes: UByteArray, offset: Int): Long { + val bits = unsigned(bytes, offset, 2).toInt() + val year = 2000 + (bits ushr 9) + val month = ((bits ushr 5) and 7) + (((bits ushr 8) and 1) * 8) + return Calendar.getInstance(utc).apply { + clear() + set(year, month - 1, bits and 31, 0, 0, 0) + }.timeInMillis + } + fun timeMillis(bytes: UByteArray, offset: Int): Long { + val bits = unsigned(bytes, offset, 2).toInt() + val hours = bits ushr 11 + val minutes = (bits ushr 5) and 63 + val seconds = (bits and 31) * 2 + return ((hours * 60L + minutes) * 60 + seconds) * 1000 + } + fun offsetMillis(bytes: UByteArray, offset: Int): Long { + val bits = unsigned(bytes, offset, 2).toInt() + val magnitude = ((bits ushr 11) * 60L + ((bits ushr 5) and 63)) * 60_000 + return if (bytes[offset + 2].toInt() == 0) magnitude else -magnitude + } + fun sensorTimestamp(bytes: UByteArray): Long = SENSOR_EPOCH_MS + unsigned(bytes) / 1024 * 1000 + fun sensorTimestamp(timestamp: Long): ByteArray = littleEndian((timestamp - SENSOR_EPOCH_MS) / 1000 * 1024, 8) +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/CalibrationPayload.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/CalibrationPayload.kt new file mode 100644 index 000000000000..e41a661379c1 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/CalibrationPayload.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.eversense.protocol + +/** Calibration wire layouts keep sample time separate from the submission clock. */ +internal object CalibrationPayload { + fun e3(glucose: Int, sampledAt: Long, submittedAt: Long): ByteArray = + BinaryFields.date(sampledAt) + BinaryFields.time(sampledAt) + + BinaryFields.date(submittedAt) + BinaryFields.time(submittedAt) + + BinaryFields.littleEndian(glucose.toLong(), 2) + byteArrayOf(0, 0, 0, 0x55) + + fun v2(glucose: Int, sampledAt: Long, submittedAt: Long): ByteArray = + BinaryFields.sensorTimestamp(sampledAt) + BinaryFields.sensorTimestamp(submittedAt) + + BinaryFields.littleEndian(glucose.toLong(), 2) + byteArrayOf(1, 0, 0) +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/GlucoseDecoders.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/GlucoseDecoders.kt new file mode 100644 index 000000000000..db1c7faa2bc0 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/GlucoseDecoders.kt @@ -0,0 +1,65 @@ +package app.aaps.plugins.eversense.protocol + +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.packets.e3.util.EversenseE3Parser +import app.aaps.plugins.eversense.util.EversenseLogger + +/** Generation-specific layouts share primitives, while preserving their different validity rules. */ +internal object GlucoseDecoders { + data class Reading(val timestamp: Long, val glucose: Int, val trend: EversenseTrendArrow, + val signal: Int = 0, val sensorId: String = "", val raw: String) + + fun e3(bytes: UByteArray): Reading? { + if (bytes.isEmpty()) return null + val glucose = EversenseE3Parser.readGlucose(bytes, 9) + if (glucose !in 20..450) return null + return Reading( + timestamp = EversenseE3Parser.readDate(bytes, 4) + EversenseE3Parser.readTime(bytes, 6), + glucose = glucose, + trend = trend(bytes[13].toInt(), extended = false), + raw = hex(bytes) + ) + } + + fun v2(bytes: UByteArray, fallbackSensorLength: Int): Reading? { + if (bytes.isEmpty()) return null + val length = bytes[11].toInt().takeUnless { it == 0 } ?: fallbackSensorLength + val signal = BinaryFields.unsigned(bytes, 22 + length, 2).toInt() + val sensor = bytes.copyOfRange(12, 12 + length) + val glucose = BinaryFields.unsigned(bytes, 20 + length, 2).toInt() + // The frozen 365 implementation rejects 450 itself; E3 accepts that boundary. + if (glucose >= 450) { + EversenseLogger.warning("GetGlucoseDataPacket", "Glucose exceeds safety limits: $glucose — rejecting") + return null + } + return Reading( + timestamp = BinaryFields.sensorTimestamp(bytes.copyOfRange(12 + length, 20 + length)), + glucose = glucose, + trend = trend(bytes[164 + length].toInt(), extended = true), + signal = signal, + sensorId = hex(sensor), + raw = hex(bytes) + ) + } + + fun trend(value: Int, extended: Boolean, unknown: EversenseTrendArrow = EversenseTrendArrow.NONE): EversenseTrendArrow = when (value) { + 1 -> EversenseTrendArrow.SINGLE_DOWN + 2 -> EversenseTrendArrow.FORTY_FIVE_DOWN + 4 -> EversenseTrendArrow.FLAT + 8 -> EversenseTrendArrow.FORTY_FIVE_UP + 16 -> EversenseTrendArrow.SINGLE_UP + 32 -> if (extended) EversenseTrendArrow.SINGLE_DOWN else unknown + 64 -> if (extended) EversenseTrendArrow.SINGLE_UP else unknown + else -> unknown + } + + private fun hex(bytes: UByteArray): String { + val digits = "0123456789abcdef" + return CharArray(bytes.size * 2).also { chars -> + bytes.forEachIndexed { index, byte -> + chars[index * 2] = digits[byte.toInt() ushr 4] + chars[index * 2 + 1] = digits[byte.toInt() and 15] + } + }.concatToString() + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/NotificationAssembler.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/NotificationAssembler.kt new file mode 100644 index 000000000000..0d3710e5153d --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/NotificationAssembler.kt @@ -0,0 +1,56 @@ +package app.aaps.plugins.eversense.protocol + +import java.io.ByteArrayOutputStream + +/** Reassembles one 365 notification stream without owning Bluetooth, storage or retry policy. */ +internal class NotificationAssembler( + private val now: () -> Long, + private val notice: (Notice) -> Unit = {} +) { + enum class Notice { SHORT_HEADER, DUPLICATE, RESTARTED, OUT_OF_ORDER } + private class Pending(val total: Int, val bytes: ByteArrayOutputStream, var next: Int = 2) + private var pending: Pending? = null + private var previous: ByteArray? = null + private var previousAt = 0L + + fun reset() { + pending = null + previous = null + previousAt = 0 + } + + fun accept(fragment: ByteArray): ByteArray? { + if (fragment.size < 2) { + notice(Notice.SHORT_HEADER) + return null + } + val timestamp = now() + if (timestamp - previousAt < 1000 && previous?.contentEquals(fragment) == true) { + notice(Notice.DUPLICATE) + return null + } + previous = fragment + previousAt = timestamp + val index = fragment[0].toInt() and 255 + val total = fragment[1].toInt() and 255 + val current = if (index == 1) { + if (pending != null) notice(Notice.RESTARTED) + // Keep the established malformed-header outcome as well as the valid wire format. + val body = fragment.copyOfRange(3, fragment.size) + Pending(total, ByteArrayOutputStream().apply { write(body) }).also { pending = it } + } else { + val active = pending + if (active == null || index != active.next || total != active.total) { + pending = null + notice(Notice.OUT_OF_ORDER) + return null + } + active.bytes.write(fragment.copyOfRange(2, fragment.size)) + active.next++ + active + } + if (current.next <= current.total) return null + pending = null + return current.bytes.toByteArray() + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/PacketSpec.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/PacketSpec.kt new file mode 100644 index 000000000000..885180c96489 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/PacketSpec.kt @@ -0,0 +1,23 @@ +package app.aaps.plugins.eversense.protocol + +import app.aaps.plugins.eversense.enums.EversenseSecurityType +import app.aaps.plugins.eversense.packets.e3.EversenseE3Packets + +/** Immutable wire contract, supplied explicitly rather than discovered through annotations. */ +data class PacketSpec( + val requestId: Byte, + val responseId: Byte, + val typeId: Byte, + val securityType: EversenseSecurityType +) { + internal val responseOffset: Int get() = when (responseId) { + EversenseE3Packets.ReadSingleByteSerialFlashRegisterResponseId, + EversenseE3Packets.ReadTwoByteSerialFlashRegisterResponseId, + EversenseE3Packets.ReadFourByteSerialFlashRegisterResponseId -> 4 + else -> 1 + } + companion object { + fun e3(command: Byte, reply: Byte) = PacketSpec(command, reply, 0, EversenseSecurityType.None) + fun v2(command: Byte, reply: Byte, operation: Byte) = PacketSpec(command, reply, operation, EversenseSecurityType.SecureV2) + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/PacketTime.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/PacketTime.kt new file mode 100644 index 000000000000..c9de49a6a04d --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/PacketTime.kt @@ -0,0 +1,16 @@ +package app.aaps.plugins.eversense.protocol + +import java.time.Clock + +/** A scoped clock lets one command run against a supplied time source without global mutation. */ +internal object PacketTime { + private val clock = ThreadLocal() + fun nowMillis(): Long = clock.get()?.millis() ?: System.currentTimeMillis() + fun withClock(source: Clock, operation: () -> T): T { + val previous = clock.get() + clock.set(source) + return try { operation() } finally { + if (previous == null) clock.remove() else clock.set(previous) + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/SecureV2Cipher.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/SecureV2Cipher.kt new file mode 100644 index 000000000000..ba49bd3d7914 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/SecureV2Cipher.kt @@ -0,0 +1,35 @@ +package app.aaps.plugins.eversense.protocol + +import app.aaps.plugins.eversense.util.EversenseLogger +import java.nio.ByteBuffer +import java.nio.ByteOrder +import org.bouncycastle.crypto.engines.AESEngine +import org.bouncycastle.crypto.modes.CCMBlockCipher +import org.bouncycastle.crypto.params.AEADParameters +import org.bouncycastle.crypto.params.KeyParameter + +/** Stateless authenticated encryption; session identity and sequence ownership stay with the caller. */ +internal object SecureV2Cipher { + fun prefix(sequence: Long): ByteArray = BinaryFields.littleEndian(sequence shl 2, 2) + fun nonce(seed: ByteArray, sequence: Long): ByteArray { + val original = ByteBuffer.wrap(seed).order(ByteOrder.LITTLE_ENDIAN).long + return BinaryFields.littleEndian((original and -16384L) or sequence, 8) + } + fun encrypt(data: ByteArray, key: ByteArray, prefix: ByteArray, nonce: ByteArray): ByteArray? = + transform(data, key, prefix, nonce, true)?.let { prefix + it } + fun decrypt(data: ByteArray, key: ByteArray, prefix: ByteArray, nonce: ByteArray): ByteArray? = + transform(data, key, prefix, nonce, false) + + private fun transform(data: ByteArray, key: ByteArray, prefix: ByteArray, nonce: ByteArray, encrypt: Boolean): ByteArray? = try { + val engine = CCMBlockCipher.newInstance(AESEngine.newInstance()) + engine.init(encrypt, AEADParameters(KeyParameter(key), nonce.size * 8, nonce, prefix)) + val output = ByteArray(engine.getOutputSize(data.size)) + val written = engine.processBytes(data, 0, data.size, output, 0) + engine.doFinal(output, written) + output + } catch (error: Exception) { + EversenseLogger.error("EversenseSecureChannel", "Authenticated encryption failed: $error") + EversenseLogger.debug("EversenseSecureChannel") { error.stackTraceToString() } + null + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/WireEncoding.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/WireEncoding.kt new file mode 100644 index 000000000000..e7adb9ca41ad --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/protocol/WireEncoding.kt @@ -0,0 +1,42 @@ +package app.aaps.plugins.eversense.protocol + +import java.io.ByteArrayOutputStream + +/** Framing is independent of packet payloads and the cryptographic session. */ +internal object WireEncoding { + private val crcTable = IntArray(256) { seed -> + var remainder = seed shl 8 + repeat(8) { + remainder = (remainder shl 1) xor if (remainder and 0x8000 == 0) 0 else 0x1021 + } + remainder and 0xffff + } + + fun crc16(bytes: ByteArray): ByteArray { + val value = bytes.fold(0xffff) { crc, octet -> + ((crc shl 8) xor crcTable[(crc ushr 8) xor (octet.toInt() and 0xff)]) and 0xffff + } + return byteArrayOf(value.toByte(), (value ushr 8).toByte()) + } + + fun e3(command: Byte, payload: ByteArray): ByteArray { + val message = byteArrayOf(command) + payload + return message + crc16(message) + } + + fun v2(message: ByteArray, payloadSize: Int): ByteArray { + val capacity = payloadSize - 2 + val chunks = (message.size + capacity - 1) / capacity + // Preserve the transmitter protocol's existing empty-ciphertext framing. + if (chunks == 0) return byteArrayOf(0) + val output = ByteArrayOutputStream(message.size + 2 * chunks + 1) + for (chunk in 0 until chunks) { + output.write(chunk + 1) + output.write(chunks) + if (chunk == 0) output.write(1) + val offset = chunk * capacity + output.write(message, offset, minOf(capacity, message.size - offset)) + } + return output.toByteArray() + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/storage/EversenseStore.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/storage/EversenseStore.kt new file mode 100644 index 000000000000..71cea4aa4ef5 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/storage/EversenseStore.kt @@ -0,0 +1,28 @@ +package app.aaps.plugins.eversense.storage + +/** Device state storage. The host owns persistence, encryption and settings import rules. */ +interface EversenseStore { + fun getString(key: String, defaultValue: String?): String? + fun getLong(key: String, defaultValue: Long): Long + fun getInt(key: String, defaultValue: Int): Int + fun getBoolean(key: String, defaultValue: Boolean): Boolean + fun contains(key: String): Boolean + fun edit(): Editor + + interface Editor { + fun putString(key: String, value: String?): Editor + fun putLong(key: String, value: Long): Editor + fun putInt(key: String, value: Int): Editor + fun putBoolean(key: String, value: Boolean): Editor + fun remove(key: String): Editor + fun clear(): Editor + fun commit(): Boolean + fun apply() + } +} + +inline fun EversenseStore.edit(commit: Boolean = false, block: EversenseStore.Editor.() -> Unit) { + val editor = edit() + editor.block() + if (commit) editor.commit() else editor.apply() +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/DmsHttpClient.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/DmsHttpClient.kt new file mode 100644 index 000000000000..9f99bf9a4ce8 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/DmsHttpClient.kt @@ -0,0 +1,74 @@ +package app.aaps.plugins.eversense.util + +import app.aaps.plugins.eversense.protocol.PacketTime +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.storage.edit +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder + +/** One transport implementation for E3 and 365, with explicit response-reading policies. */ +internal object DmsHttpClient { + data class Reply(val status: Int, val body: String) + private const val CLIENT_ID = "eversenseMMAAndroid" + private const val CLIENT_SECRET = "6ksPx#]~wQ3U" + + fun passwordGrant(username: String, password: String): String = listOf( + "grant_type=password", "client_id=$CLIENT_ID", "client_secret=$CLIENT_SECRET", + "username=${URLEncoder.encode(username, "UTF-8")}", "password=${URLEncoder.encode(password, "UTF-8")}" + ).joinToString("&") + + fun post(url: String, body: String, token: String? = null, form: Boolean = false, + tolerantBody: Boolean = false, readBody: Boolean = true): Reply = + exchange(url, "POST", body, token, if (form) "application/x-www-form-urlencoded" else "application/json", 30_000, tolerantBody, readBody) + + fun get(url: String, token: String): Reply = exchange(url, "GET", null, token, null, 0, false, true) + + private fun exchange(url: String, method: String, body: String?, token: String?, contentType: String?, + timeout: Int, tolerantBody: Boolean, readBody: Boolean): Reply { + val connection = URL(url).openConnection() as HttpURLConnection + try { + connection.requestMethod = method + connection.connectTimeout = timeout + connection.readTimeout = timeout + if (token != null) connection.setRequestProperty("Authorization", "Bearer $token") + if (contentType != null) connection.setRequestProperty("Content-Type", contentType) + if (body != null) { + connection.doOutput = true + connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)); it.flush() } + } + val status = connection.responseCode + val text = if (!readBody) "" else try { + val stream = if (status >= 400) connection.errorStream else connection.inputStream + stream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() } ?: "" + } catch (error: Exception) { + if (!tolerantBody) throw error + "" + } + return Reply(status, text) + } finally { connection.disconnect() } + } +} + +/** Cache semantics are shared; the model-specific login still selects its own endpoint. */ +internal object DmsAccessTokens { + data class Login(val token: String, val expiresInSeconds: Int) + fun resolve(preferences: EversenseStore, forceRefresh: Boolean = false, login: () -> Login?): String? { + val expiry = preferences.getLong(StorageKeys.ACCESS_TOKEN_EXPIRY, 0) + val cached = preferences.getString(StorageKeys.ACCESS_TOKEN, null) + if (!forceRefresh && cached != null && PacketTime.nowMillis() < expiry - 300_000L) return cached + val session = login() ?: return null + preferences.edit(commit = true) { + putString(StorageKeys.ACCESS_TOKEN, session.token) + putLong(StorageKeys.ACCESS_TOKEN_EXPIRY, PacketTime.nowMillis() + session.expiresInSeconds * 1000L) + } + return session.token + } + + fun clear(preferences: EversenseStore) { + preferences.edit(commit = true) { + remove(StorageKeys.ACCESS_TOKEN) + remove(StorageKeys.ACCESS_TOKEN_EXPIRY) + } + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseCrypto365Util.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseCrypto365Util.kt new file mode 100644 index 000000000000..a93e313a8263 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseCrypto365Util.kt @@ -0,0 +1,245 @@ +package app.aaps.plugins.eversense.util + +import android.security.keystore.KeyProperties +import app.aaps.plugins.eversense.models.EversenseSecureState +import app.aaps.plugins.eversense.packets.e365.utils.toByteArray +import app.aaps.plugins.eversense.packets.e365.utils.toLong +import app.aaps.plugins.eversense.protocol.BinaryFields +import app.aaps.plugins.eversense.protocol.SecureV2Cipher +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.storage.edit +import java.math.BigInteger +import java.security.AlgorithmParameters +import java.security.KeyFactory +import java.security.KeyPair +import java.security.KeyPairGenerator +import java.security.PrivateKey +import java.security.SecureRandom +import java.security.Signature +import java.security.interfaces.ECPrivateKey +import java.security.interfaces.ECPublicKey +import java.security.spec.ECGenParameterSpec +import java.security.spec.ECParameterSpec +import java.security.spec.ECPoint +import java.security.spec.ECPublicKeySpec +import java.security.spec.PKCS8EncodedKeySpec +import javax.crypto.KeyAgreement +import kotlin.collections.toByteArray +import kotlinx.serialization.json.Json +import org.bouncycastle.asn1.ASN1InputStream +import org.bouncycastle.asn1.ASN1Integer +import org.bouncycastle.asn1.DLSequence +import org.bouncycastle.crypto.digests.SHA256Digest +import org.bouncycastle.crypto.generators.HKDFBytesGenerator +import org.bouncycastle.crypto.params.HKDFParameters +import org.bouncycastle.util.BigIntegers + +class EversenseCrypto365Util(val preference: EversenseStore) { + private var ephemPrivate: ECPrivateKey? = null + private var ephemPublic: ECPublicKey? = null + private var ephemSalt: ByteArray? = null + + private var messageSequenceNumber = 1 + private var sessionKey: ByteArray? = null + + fun canUseShortcut(): Boolean { + return getState(preference).canUseShortcut + } + + fun allowUseShortcut() { + val state = getState(preference) + state.canUseShortcut = true + saveState(state, preference) + } + + fun disallowUseShortcut() { + val state = getState(preference) + state.canUseShortcut = false + saveState(state, preference) + } + + fun getClientPublicKey(): ByteArray { + val state = getState(preference) + return state.publicKey.hexToByteArray() + } + + fun generateKeyPairIfNotExists(): Boolean { + val state = getState(preference) + if (state.clientId.isNotEmpty() && state.publicKey.isNotEmpty() && state.privateKey.isNotEmpty()) { + EversenseLogger.debug(TAG) { "Already generated keypair" } + return true + } + + val keyPair = generatePrivateKeyPair() ?: return false + state.clientId = generateRandomBytes(32).toHexString() + state.privateKey = keyPair.private.encoded.toHexString() + state.publicKey = keyPair.public.encoded.toHexString() + + saveState(state, preference) + EversenseLogger.debug(TAG) { "Generated keypair!" } + return true + } + + fun getClientId(): ByteArray { + val state = getState(preference) + return state.clientId.hexToByteArray() + } + + fun getStartSecret(signature: ByteArray): ByteArray { + val public = ephemPublic?.encoded ?: return byteArrayOf() + val salt = ephemSalt ?: return byteArrayOf() + + var secret = byteArrayOf(128.toByte(), 0) + secret += getState(preference).clientId.hexToByteArray() + secret += public.copyOfRange(27, public.count()) + secret += salt + secret += signature + + return secret + } + + fun generateEphem(): ByteArray? { + val keyPair = generatePrivateKeyPair() ?:run { + EversenseLogger.error(TAG, "Failed to generate keypair...") + return null + } + + val privateKey = getState(preference).privateKey.hexToByteArray() + try { + val privateKey = KeyFactory.getInstance("EC").generatePrivate(PKCS8EncodedKeySpec(privateKey)) + val publicKey = keyPair.public.encoded + val v2Salt = generateRandomBytes(8) + + ephemPrivate = keyPair.private as ECPrivateKey + ephemPublic = keyPair.public as ECPublicKey + ephemSalt = v2Salt + + val data = publicKey.copyOfRange(27, publicKey.count()) + v2Salt + return ecdsaSign(privateKey, data) + } catch (e: Exception) { + EversenseLogger.debug(TAG) { e.stackTraceToString() } + EversenseLogger.error(TAG, "Got exception during generateEphem - exception: $e") + return null + } + } + + fun generateSessionKey(encodedPublicKey: ByteArray) { + try { + val salt = ephemSalt ?: return + + val ecPoint = ECPoint( + BigInteger(1, encodedPublicKey.copyOfRange(0, 32)), + BigInteger(1, encodedPublicKey.copyOfRange(32, 64)) + ) + val algorithmParameters = AlgorithmParameters.getInstance(KeyProperties.KEY_ALGORITHM_EC).run { + init(ECGenParameterSpec("secp256r1")) + getParameterSpec(ECParameterSpec::class.java) + } + + val publicKey = KeyFactory.getInstance(KeyProperties.KEY_ALGORITHM_EC).generatePublic( + ECPublicKeySpec(ecPoint, algorithmParameters) + ) + + val sharedSecret = + KeyAgreement.getInstance("ECDH").run { + init(ephemPrivate) + doPhase(publicKey, true) + generateSecret() + } + + val symmetricKey = HKDFBytesGenerator(SHA256Digest()).run { + init(HKDFParameters(sharedSecret, null, salt)) + + val arr = ByteArray(16) + generateBytes(arr, 0, 16) + arr + } + + sessionKey = symmetricKey + } catch (e: Exception) { + EversenseLogger.debug(TAG) { e.stackTraceToString() } + EversenseLogger.error(TAG, "Failed to generate sessionKey: $e") + } + } + + fun encrypt(data: ByteArray): ByteArray { + val seed = ephemSalt ?: return missingMaterial("salt") + val key = sessionKey ?: return missingMaterial("session key") + val index = (messageSequenceNumber and 0x3fff).toLong() + val prefix = SecureV2Cipher.prefix(index) + val nonce = SecureV2Cipher.nonce(seed, index) + messageSequenceNumber++ + return SecureV2Cipher.encrypt(data, key, prefix, nonce) ?: byteArrayOf() + } + + fun decrypt(response: ByteArray): ByteArray { + val seed = ephemSalt ?: return missingMaterial("salt") + val key = sessionKey ?: return missingMaterial("session key") + val ciphertext = response.copyOfRange(2, response.size) + val prefix = response.copyOfRange(0, 2) + val index = (BinaryFields.unsigned(prefix.toUByteArray()) shr 2) and 0x3fff + val nonce = SecureV2Cipher.nonce(seed, index) + return SecureV2Cipher.decrypt(ciphertext, key, prefix, nonce) ?: byteArrayOf() + } + + private fun missingMaterial(name: String): ByteArray { + EversenseLogger.error(TAG, "No $name available") + return byteArrayOf() + } + + companion object { + private const val TAG = "EversenseCrypto365Handler" + private val JSON = Json { ignoreUnknownKeys = true } + + private fun generateRandomBytes(i: Int): ByteArray { + val bArr = ByteArray(i) + SecureRandom().nextBytes(bArr) + return bArr + } + + private fun generatePrivateKeyPair(): KeyPair? { + try { + return KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC).run { + initialize(ECGenParameterSpec("secp256r1")) + generateKeyPair() + } + } catch (e: Exception) { + EversenseLogger.error(TAG, "Error generating key pair: $e") + return null + } + } + + private fun ecdsaSign(privateKey: PrivateKey, data: ByteArray): ByteArray? { + try { + val signature = Signature.getInstance("SHA256withECDSA").run { + initSign(privateKey) + update(data) + sign() + } + + val dLSequence = ASN1InputStream(signature).readObject() as DLSequence + val value1 = (dLSequence.getObjectAt(0) as ASN1Integer).value + val value2 = (dLSequence.getObjectAt(1) as ASN1Integer).value + val bigInt1 = BigIntegers.asUnsignedByteArray(32, value1) + val bigInt2 = BigIntegers.asUnsignedByteArray(32, value2) + + return bigInt1 + bigInt2 + } catch(e: Exception) { + EversenseLogger.error(TAG, "Got exception during ecdsaSign - exception: $e") + return null + } + } + + private fun getState(preference: EversenseStore): EversenseSecureState { + val stateJson = preference.getString(StorageKeys.SECURE_STATE, null) ?: "{}" + return JSON.decodeFromString(stateJson) + } + + private fun saveState(state: EversenseSecureState, preference: EversenseStore) { + preference.edit(commit = true) { + putString(StorageKeys.SECURE_STATE, JSON.encodeToString(state)) + } + } + + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseDmsBinaryCodec.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseDmsBinaryCodec.kt new file mode 100644 index 000000000000..232f1d154d86 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseDmsBinaryCodec.kt @@ -0,0 +1,92 @@ +package app.aaps.plugins.eversense.util + +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.packets.e365.CalibrationHistoryItem +import app.aaps.plugins.eversense.protocol.BinaryFields +import java.io.ByteArrayOutputStream +import java.util.Base64 + +/** DMS record layouts use one writer, including the same UTC fields as the BLE protocol. */ +internal object EversenseDmsBinaryCodec { + private class RecordWriter { + private val output = ByteArrayOutputStream() + fun bytes(vararg octets: Int) { octets.forEach(output::write) } + fun raw(value: ByteArray) { output.write(value) } + fun number(value: Int, width: Int = 2) { raw(BinaryFields.littleEndian(value.toLong(), width)) } + fun timestamp(value: Long) { raw(BinaryFields.date(value)); raw(BinaryFields.time(value)) } + fun zeros(count: Int) { raw(ByteArray(count)) } + fun sensorId(value: String, emptySize: Int = 0) { + if (value.isEmpty()) zeros(emptySize) + else value.chunked(2).forEach { output.write(it.toInt(16)) } + } + fun encoded(): String = Base64.getEncoder().encodeToString(output.toByteArray()) + } + private fun record(body: RecordWriter.() -> Unit): String = RecordWriter().apply(body).encoded() + + fun int16LE(v: Int): ByteArray = BinaryFields.littleEndian(v.toLong(), 2) + fun int24LE(v: Int): ByteArray = BinaryFields.littleEndian(v.toLong(), 3) + fun int32LE(v: Int): ByteArray = BinaryFields.littleEndian(v.toLong(), 4) + fun calcDateBytes(tsMs: Long): ByteArray = BinaryFields.date(tsMs) + fun calcTimeBytes(tsMs: Long): ByteArray = BinaryFields.time(tsMs) + + fun buildSgBytes(readings: List): String = record { + bytes(0x8c, 0, 1, 0, 0) + number(readings.size, 3) + readings.forEachIndexed { index, reading -> + number(index + 1, 3) + timestamp(reading.datetime) + number(reading.glucoseInMgDl) + bytes(0) + sensorId(reading.sensorId, emptySize = 10) + zeros(19) // Unavailable ADC, acceleration and temperature fields. + } + } + fun buildMgBytes(calibrations: List): String = record { + bytes(0x98, 1, 0) + number(calibrations.size) + bytes(0) + calibrations.forEachIndexed { index, calibration -> + number(index + 1) + timestamp(calibration.datetime) + number(calibration.glucoseInMgDl) + zeros(2) + bytes(1, 0, 0, 0) + } + } + fun buildEmptyMgBytes(): String = buildMgBytes(emptyList()) + fun buildEmptyPatientBytes(): String = record { bytes(0x9e, 1, 0); zeros(2) } + + fun buildAlertBytes(sensorId: String, alerts: List = emptyList(), datetime: Long = 0, glucoseInMgDl: Int = 0): String = record { + val supported = alerts.filter { it.code.dmsCode != 255 } + bytes(0x93, 1, 0) + number(supported.size) + sensorId(sensorId) + bytes(0) + supported.forEachIndexed { index, alarm -> + number(index + 1) + timestamp(datetime) + bytes(alarm.code.dmsCode) + number(glucoseInMgDl) + zeros(4) + } + } + + fun signalStrengthOrdinal(percent: Int): Int = when { + percent >= 75 -> 5 + percent >= 48 -> 4 + percent >= 30 -> 3 + percent >= 28 -> 2 + percent >= 25 -> 1 + else -> 0 + } + fun trendOrdinal(trend: EversenseTrendArrow): Int = when (trend) { + EversenseTrendArrow.NONE -> 0 + EversenseTrendArrow.SINGLE_DOWN -> 1 + EversenseTrendArrow.FORTY_FIVE_DOWN -> 2 + EversenseTrendArrow.FLAT -> 3 + EversenseTrendArrow.FORTY_FIVE_UP -> 4 + EversenseTrendArrow.SINGLE_UP -> 5 + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseHttp365Util.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseHttp365Util.kt new file mode 100644 index 000000000000..cf4b3a0021c4 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseHttp365Util.kt @@ -0,0 +1,410 @@ +package app.aaps.plugins.eversense.util + +import android.annotation.SuppressLint +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseSecureState +import app.aaps.plugins.eversense.packets.e365.CalibrationHistoryItem +import app.aaps.plugins.eversense.storage.EversenseStore +import java.text.SimpleDateFormat +import java.util.Base64 +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +class EversenseHttp365Util { + + /** + * Outcome of an upload attempt, detailed enough to diagnose from an exported AAPS log. + * + * Declared on the class rather than inside [Companion] so callers can name it as + * `EversenseHttp365Util.UploadOutcome`. + * + * [EversenseLogger] output never reaches the exported log file - it uses arbitrary string + * tags while the file appender only captures AAPS's LTag loggers - so everything needed to + * diagnose a missing reading has to travel back to the caller, which logs through + * aapsLogger. + */ + data class UploadOutcome( + val success: Boolean, + /** Readings actually serialized and POSTed. Zero is not a success. */ + val sentCount: Int = 0, + /** Readings dropped before sending because they carried no raw BLE data. */ + val skippedNoRawData: Int = 0, + val httpStatus: Int? = null, + /** + * Readings POSTed with an empty SensorId. The portal indexes records by that field, so a + * reading sent without one can be accepted and still never appear. Backfill readings are + * the known source - GlucoseHistoryItem has no sensorId to carry. + */ + val sentWithEmptySensorId: Int = 0, + /** Server reply, truncated - this is what identifies a silent server-side reject. */ + val responseBody: String = "", + val error: String? = null + ) { + + /** One line, safe for the log: no token, no credentials, body clipped. */ + fun describe(): String = + "sent=$sentCount skippedNoRawData=$skippedNoRawData emptySensorId=$sentWithEmptySensorId " + + "status=${httpStatus ?: "-"}" + + (error?.let { " error=$it" } ?: "") + + (if (responseBody.isNotBlank()) " body=${responseBody.take(RESPONSE_BODY_LOG_LIMIT)}" else "") + + private companion object { + + const val RESPONSE_BODY_LOG_LIMIT = 300 + } + } + + companion object { + private val TAG = "EversenseHttp365Util" + private val JSON = Json { ignoreUnknownKeys = true } + + private val CLIENT_NO = 2 + private val CLIENT_TYPE = 128 + + // US endpoints. Overridable for unit tests. Used whenever + // EversenseSecureState.isEuropeanRegion is false (the default) — untouched by the + // EU routing below. + internal var tokenBaseUrl = "https://usiamapi.eversensedms.com/" + internal var uploadBaseUrl = "https://usmobileappmsprod.eversensedms.com/" + internal var careBaseUrl = "https://usapialpha.eversensedms.com/" + internal var vaultBaseUrl = "https://deviceauthorization.eversensedms.com/" + + // EU/OUS endpoints, selected per-call via effectiveTokenBaseUrl/effectiveUploadBaseUrl/ + // effectiveCareBaseUrl when EversenseSecureState.isEuropeanRegion is true. + // euTokenBaseUrl is the exact host EversenseHttpE3Util.kt already uses for E3 (see its + // header comment: confirmed from a decompiled real Eversense EU app, proven working in + // production for real EU E3 transmitters). A first attempt at this guessed + // "ousiamapi.eversensedms.com" (naive "us"->"ous" swap, no "alpha") purely from a CNAME + // match to a distinctly-named AWS load balancer; that host is real infrastructure but + // NOT this API - confirmed live via a real EU 365 user's Eversense.log, which showed + // every login() call returning a bare IIS 404 (Server: Microsoft-HTTPAPI/2.0), not the + // Cloudflare-fronted IdentityServer4 400 the working US host (and this corrected host) + // both return to the same bare GET. euUploadBaseUrl and euCareBaseUrl were independently + // verified live to give the same healthy app-level responses as their US counterparts, so + // they're left as originally set. + internal var euTokenBaseUrl = "https://ousiamapialpha.eversensedms.com/" + internal var euUploadBaseUrl = "https://ousmobileappmsprod.eversensedms.com/" + internal var euCareBaseUrl = "https://ousalphaapiservices.eversensedms.com/" + + // euVaultBaseUrl was initially left unrouted (vaultBaseUrl used for both regions) on the + // theory that fleet/vault cert issuance is shared, account-independent infrastructure - + // wrong: a real EU user's Eversense.log showed getFleetSecretV2() 404ing against + // vaultBaseUrl even after the token-host fix made login() succeed. This "ous"-prefixed + // host is confirmed live: identical response codes to vaultBaseUrl for every request + // tried (401 with no Authorization header, 405 on HEAD), AND both return the exact same + // distinctive error body - "Eversense.Link_expired" - to the same unauthenticated GET, + // which isn't infrastructure coincidence. + internal var euVaultBaseUrl = "https://ousdeviceauthorization.eversensedms.com/" + + private fun effectiveTokenBaseUrl(state: EversenseSecureState) = if (state.isEuropeanRegion) euTokenBaseUrl else tokenBaseUrl + private fun effectiveUploadBaseUrl(state: EversenseSecureState) = if (state.isEuropeanRegion) euUploadBaseUrl else uploadBaseUrl + private fun effectiveCareBaseUrl(state: EversenseSecureState) = if (state.isEuropeanRegion) euCareBaseUrl else careBaseUrl + private fun effectiveVaultBaseUrl(state: EversenseSecureState) = if (state.isEuropeanRegion) euVaultBaseUrl else vaultBaseUrl + + fun login(preference: EversenseStore): LoginResponseModel? { + val state = getState(preference) + return try { + val reply = DmsHttpClient.post("${effectiveTokenBaseUrl(state)}connect/token", DmsHttpClient.passwordGrant(state.username, state.password), form = true) + if (reply.status >= 400) { + EversenseLogger.error(TAG, "Login failed: HTTP ${reply.status}") + null + } else { + EversenseLogger.info(TAG, "Login succeeded: HTTP ${reply.status}") + Json.decodeFromString(LoginResponseModel.serializer(), reply.body) + } + } catch (error: Exception) { + EversenseLogger.error(TAG, "Login failed: $error") + null + } + } + + fun getFleetSecretV2(preferences: EversenseStore, accessToken: String, serialNumber: ByteArray, nonce: ByteArray, flags: Boolean, publicKey: ByteArray): FleetSecretV2ResponseModel? { + try { + val publicKeyStr = Base64.getUrlEncoder().withoutPadding() + .encodeToString(publicKey.copyOfRange(27, publicKey.count())) + val serialNumberStr = + Base64.getUrlEncoder().withoutPadding().encodeToString(serialNumber) + val nonceStr = Base64.getUrlEncoder().withoutPadding().encodeToString(nonce) + val query = listOf( + "tx_flags=$flags", + "txSerialNumber=$serialNumberStr", + "nonce=$nonceStr", + "clientNo=$CLIENT_NO", + "clientType=$CLIENT_TYPE", + "kp_client_unique_id=$publicKeyStr" + ).joinToString("&") + + val reply = DmsHttpClient.get("${effectiveVaultBaseUrl(getState(preferences))}api/vault/GetTxCertificate?$query", accessToken) + if (reply.status >= 400) return null + val dataJson = reply.body + + val response = Json.decodeFromString(FleetSecretV2ResponseModel.serializer(), dataJson) + if (response.Status != "Success" || response.Result.Certificate == null) { + EversenseLogger.error(TAG, "Received invalid tx certificate response - status=${response.Status}") + return null + } + + return response + } catch (e: Exception) { + EversenseLogger.error(TAG, "Failed to get fleetSecretV2 - exception: $e") + return null + } + } + + // SimpleDateFormat is not thread-safe. A ThreadLocal gives each thread its own + // instance, so a scheduled sync and a manual sync running at the same time cannot + // corrupt the formatted timestamp. Output is byte-for-byte identical to before. + private val dateFormatter: ThreadLocal = ThreadLocal.withInitial { + SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US).apply { + timeZone = java.util.TimeZone.getTimeZone("UTC") + } + } + + fun getOrRefreshToken(preferences: EversenseStore): String? = DmsAccessTokens.resolve(preferences) { + login(preferences)?.let { DmsAccessTokens.Login(it.access_token, it.expires_in) } + } + + /** + * Upload glucose readings to the Eversense DMS cloud. + * + * Returns an [UploadOutcome] rather than a Boolean, because a Boolean hid the two things + * that matter when readings go missing from the DMS portal: how many readings were really + * sent (as opposed to how many were handed in), and what the server said. Both response + * bodies used to be read and then discarded, so a server that accepted the request and + * silently dropped the reading looked identical to a genuine success. + */ + fun uploadGlucoseReadings( + preferences: EversenseStore, + readings: List, + transmitterSerialNumber: String, + firmwareVersion: String + ): UploadOutcome { + if (readings.isEmpty()) return UploadOutcome(success = true) + val token = getOrRefreshToken(preferences) ?: run { + EversenseLogger.error(TAG, "Cannot upload glucose — no valid access token") + return UploadOutcome(success = false, error = "no valid access token") + } + val state = getState(preferences) + + return try { + // Only upload readings that have raw BLE data — readings without rawResponseHex are skipped. + val uploadable = readings.filter { it.rawResponseHex.isNotEmpty() } + if (uploadable.isEmpty()) { + EversenseLogger.info(TAG, "No readings with raw BLE data to upload — skipping") + // Deliberately not success: nothing reached the server, and reporting this as a + // send is what made dropped readings look like healthy uploads in the log. + return UploadOutcome( + success = false, + skippedNoRawData = readings.size, + error = "no readings carried raw BLE data" + ) + } + + EversenseLogger.debug(TAG) { "Uploading ${uploadable.size} reading(s) — TransmitterId='$transmitterSerialNumber'" } + + // Counted, not filtered: a reading with no sensorId is still sent, because dropping + // it would trade one silent loss for another. Reported so a portal gap can be tied + // to the empty index key rather than guessed at. + val emptySensorIds = uploadable.count { it.sensorId.isEmpty() } + + // SensorId: the official app stores the first 8 bytes of the raw sensor ID in reversed + // byte order, uppercase — matching what the DMS portal indexes readings by. + // EssentialLog: base64-encoded bytes — the .NET server model uses System.Byte[] which + // JSON-serializes as base64 (despite the Android app sending "0x"+hex, the server rejects it). + // Body must be a bare JSON array — server deserializes directly to List + val jsonBody = uploadable.joinToString(prefix = "[", postfix = "]") { r -> + val portalSensorId = r.sensorId.chunked(2).take(8).reversed().joinToString("").uppercase() + val essentialLog = Base64.getEncoder().encodeToString( + r.rawResponseHex.chunked(2).map { it.toInt(16).toByte() }.toByteArray() + ) + val ts = dateFormatter.get().format(Date(r.datetime)) + EversenseLogger.debug(TAG) { " Reading: glucose=${r.glucoseInMgDl} ts=$ts rawHex=${r.rawResponseHex.length / 2}B" } + """{"SensorId":"$portalSensorId","TransmitterId":"$transmitterSerialNumber","Timestamp":"$ts","CurrentGlucoseValue":${r.glucoseInMgDl},"CurrentGlucoseDateTime":"$ts","FWVersion":"$firmwareVersion","EssentialLog":"$essentialLog"}""" + } + + val reply = DmsHttpClient.post("${effectiveUploadBaseUrl(state)}api/v1.0/DiagnosticLog/PostEssentialLogs", jsonBody, token, tolerantBody = true) + val responseCode = reply.status + if (responseCode >= 400) { + val error = reply.body + EversenseLogger.error(TAG, "Glucose upload failed — status: $responseCode") + EversenseLogger.debug(TAG) { "Cloud response body: $error" } + UploadOutcome( + success = false, + sentCount = 0, + skippedNoRawData = readings.size - uploadable.size, + httpStatus = responseCode, + sentWithEmptySensorId = emptySensorIds, + responseBody = error + ) + } else { + val responseBody = reply.body + EversenseLogger.info(TAG, "Glucose upload success — status: $responseCode, readings: ${uploadable.size}") + EversenseLogger.debug(TAG) { "Cloud response body: $responseBody" } + // Carried out, but the body is what tells us whether the server actually kept + // the reading - a 2xx alone has proven not to mean it landed in the portal. + UploadOutcome( + success = true, + sentCount = uploadable.size, + skippedNoRawData = readings.size - uploadable.size, + httpStatus = responseCode, + sentWithEmptySensorId = emptySensorIds, + responseBody = responseBody + ) + } + } catch (e: Exception) { + EversenseLogger.error(TAG, "Glucose upload exception: $e") + UploadOutcome(success = false, error = e.toString()) + } + } + + /** + * Post current glucose state to the Eversense DMS portal (api/care/PutCurrentValues). + * This updates "Last Sync Date" on the portal and feeds AGP reports. + * Returns true on HTTP 2xx, false on any error. + */ + fun putCurrentValues( + preferences: EversenseStore, + glucose: Int, + timestamp: Long, + trend: EversenseTrendArrow, + signalStrength: Int, + batteryPercentage: Int + ): UploadOutcome { + val token = getOrRefreshToken(preferences) ?: run { + EversenseLogger.error(TAG, "Cannot post current values — no valid access token") + return UploadOutcome(success = false, error = "no valid access token") + } + return try { + val ts = dateFormatter.get().format(Date(timestamp)) + val jsonBody = """{"CurrentGlucose":$glucose,"CGTime":"$ts","GlucoseTrend":${EversenseDmsBinaryCodec.trendOrdinal(trend)},"SignalStrength":${EversenseDmsBinaryCodec.signalStrengthOrdinal(signalStrength)},"BatteryStrength":${batteryPercentage.coerceAtLeast(0)},"IsTransmitterConnected":1}""" + + val reply = DmsHttpClient.post("${effectiveCareBaseUrl(getState(preferences))}api/care/PutCurrentValues", jsonBody, token, tolerantBody = true) + val responseCode = reply.status + if (responseCode >= 400) { + val error = reply.body + EversenseLogger.error(TAG, "PutCurrentValues failed — status: $responseCode") + EversenseLogger.debug(TAG) { "Cloud response body: $error" } + UploadOutcome(success = false, httpStatus = responseCode, responseBody = error) + } else { + val responseBody = reply.body + EversenseLogger.debug(TAG) { "PutCurrentValues success — status: $responseCode, glucose=$glucose" } + EversenseLogger.debug(TAG) { "Cloud response body: $responseBody" } + UploadOutcome(success = true, sentCount = 1, httpStatus = responseCode, responseBody = responseBody) + } + } catch (e: Exception) { + EversenseLogger.error(TAG, "PutCurrentValues exception: $e") + UploadOutcome(success = false, error = e.toString()) + } + } + + /** + * Post device events (sensor glucose readings) to the Eversense DMS portal. + * This is the endpoint that populates the Sensor Glucose history table in the portal. + * Returns true on HTTP 2xx, false on any error. + * + * Binary format reverse-engineered from com.senseonics.util.AccountConstants in the + * decompiled official Eversense app. + */ + fun putDeviceEvents( + preferences: EversenseStore, + readings: List, + transmitterSerialNumber: String, + calibrations: List = emptyList(), + alerts: List = emptyList() + ): UploadOutcome { + if (readings.isEmpty()) return UploadOutcome(success = true) + val token = getOrRefreshToken(preferences) ?: run { + EversenseLogger.error(TAG, "Cannot post device events — no valid access token") + return UploadOutcome(success = false, error = "no valid access token") + } + return try { + val rawSensorId = readings.firstOrNull { it.sensorId.isNotEmpty() }?.sensorId ?: getEversenseState(preferences).sensorId + val sensorId = if (rawSensorId.length >= 16) rawSensorId.chunked(2).take(8).reversed().joinToString("").uppercase() else rawSensorId + val tzOffsetSec = TimeZone.getDefault().getOffset(Date().time) / 1000 + val offsetBytes = Base64.getEncoder().encodeToString(EversenseDmsBinaryCodec.int32LE(tzOffsetSec)) + val sgBytes = EversenseDmsBinaryCodec.buildSgBytes(readings) + val mgBytes = if (calibrations.isNotEmpty()) EversenseDmsBinaryCodec.buildMgBytes(calibrations) else EversenseDmsBinaryCodec.buildEmptyMgBytes() + val patientBytes = EversenseDmsBinaryCodec.buildEmptyPatientBytes() + val alertBytes = EversenseDmsBinaryCodec.buildAlertBytes(sensorId, alerts, readings.lastOrNull()?.datetime ?: System.currentTimeMillis(), readings.lastOrNull()?.glucoseInMgDl ?: 0) + + EversenseLogger.debug(TAG) { "PutDeviceEvents: ${readings.size} reading(s), ${calibrations.size} calibration(s), txId='$transmitterSerialNumber', sensorId='$sensorId'" } + calibrations.forEach { c -> + EversenseLogger.debug(TAG) { " Calibration: glucose=${c.glucoseInMgDl} ts=${dateFormatter.get().format(Date(c.datetime))}" } + } + + val jsonBody = """{"deviceType":"SMSIMeter","deviceName":"Smart Transmitter (Android)","deviceID":"$transmitterSerialNumber","offsetBytes":"$offsetBytes","sgBytes":"$sgBytes","mgBytes":"$mgBytes","patientBytes":"$patientBytes","alertBytes":"$alertBytes","algorithmVersion":"10"}""" + + val reply = DmsHttpClient.post("${effectiveCareBaseUrl(getState(preferences))}api/care/PutDeviceEvents", jsonBody, token, tolerantBody = true) + val responseCode = reply.status + val responseBody = reply.body + val isRejected = responseBody.contains("[-1") || responseBody.contains("-1,") + if (responseCode >= 400 || isRejected) { + if (responseCode == 401) DmsAccessTokens.clear(preferences) + val error = if (isRejected) "eDMS rejected device events ($responseBody)" else responseBody + EversenseLogger.error(TAG, "PutDeviceEvents failed — status: $responseCode, error: $error") + UploadOutcome(success = false, httpStatus = responseCode, responseBody = responseBody, error = error) + } else { + EversenseLogger.info(TAG, "PutDeviceEvents success — status: $responseCode, readings: ${readings.size}") + EversenseLogger.debug(TAG) { "Cloud response body: $responseBody" } + UploadOutcome( + success = true, + sentCount = readings.size, + sentWithEmptySensorId = readings.count { it.sensorId.isEmpty() }, + httpStatus = responseCode, + responseBody = responseBody + ) + } + } catch (e: Exception) { + EversenseLogger.error(TAG, "PutDeviceEvents exception: $e") + UploadOutcome(success = false, error = e.toString()) + } + } + + private fun getState(preference: EversenseStore): EversenseSecureState { + val stateJson = preference.getString(StorageKeys.SECURE_STATE, null) ?: "{}" + return JSON.decodeFromString(stateJson) + } + + private fun getEversenseState(preference: EversenseStore): app.aaps.plugins.eversense.models.EversenseState { + val stateJson = preference.getString(StorageKeys.STATE, null) ?: "{}" + return try { JSON.decodeFromString(stateJson) } catch (_: Exception) { app.aaps.plugins.eversense.models.EversenseState() } + } + } + + + @Serializable + @SuppressLint("UnsafeOptInUsageError") + data class LoginResponseModel( + val access_token: String, + val expires_in: Int, + val token_type: String, + val expires: String, + val lastLogin: String + ) + + @Serializable + @SuppressLint("UnsafeOptInUsageError") + data class FleetSecretV2ResponseModel( + val Status: String, + val StatusCode: Int, + val Result: FleetSecretV2Result + ) + + @Serializable + @SuppressLint("UnsafeOptInUsageError") + data class FleetSecretV2Result( + val Certificate: String? = null, + val Digital_Signature: String? = null, + val IsKeyAvailable: Boolean, + val KpAuthKey: String? = null, + val KpTxId: String? = null, + val KpTxUniqueId: String? = null, + val tx_flag: Boolean? = null, + val TxFleetKey: String? = null, + val TxKeyVersion: String? = null + ) +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseHttpE3Util.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseHttpE3Util.kt new file mode 100644 index 000000000000..689cbe86dddb --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseHttpE3Util.kt @@ -0,0 +1,172 @@ +package app.aaps.plugins.eversense.util + +import android.annotation.SuppressLint +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseSecureState +import app.aaps.plugins.eversense.packets.e365.CalibrationHistoryItem +import app.aaps.plugins.eversense.storage.EversenseStore +import java.text.SimpleDateFormat +import java.util.Base64 +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** + * DMS cloud upload for Eversense E3 (EU/OUS) transmitters. + * + * Endpoints confirmed from decompiled Eversense EU app v7.1.1: + * Token : https://ousiamapialpha.eversensedms.com/ + * Care : https://ousalphaapiservices.eversensedms.com/ + * + * Note: E3 does not use the diagnostic-log upload endpoint (PostEssentialLogs) + * because it does not expose raw BLE response bytes. Only PutCurrentValues and + * PutDeviceEvents are supported. + */ +class EversenseHttpE3Util { + companion object { + private const val TAG = "EversenseHttpE3Util" + private val JSON = Json { ignoreUnknownKeys = true } + + + // EU/OUS endpoints � confirmed from decompiled Eversense EU app v7.1.1 + internal var tokenBaseUrl = "https://ousiamapialpha.eversensedms.com/" + internal var careBaseUrl = "https://ousalphaapiservices.eversensedms.com/" + + // SimpleDateFormat is not thread-safe. A ThreadLocal gives each thread its own + // instance, so a scheduled sync and a manual sync running at the same time cannot + // corrupt the formatted timestamp. Output is byte-for-byte identical to before. + private val dateFormatter: ThreadLocal = ThreadLocal.withInitial { + SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US).apply { + timeZone = TimeZone.getTimeZone("UTC") + } + } + + // -- Auth -------------------------------------------------------------- + + fun login(preferences: EversenseStore): LoginResponseModel? { + val state = getState(preferences) + return try { + val reply = DmsHttpClient.post("${tokenBaseUrl}connect/token", DmsHttpClient.passwordGrant(state.username, state.password), form = true) + if (reply.status >= 400) { + EversenseLogger.error(TAG, "Login failed: HTTP ${reply.status}") + null + } else { + EversenseLogger.info(TAG, "Login succeeded: HTTP ${reply.status}") + Json.decodeFromString(LoginResponseModel.serializer(), reply.body) + } + } catch (error: Exception) { + EversenseLogger.error(TAG, "Login failed: $error") + null + } + } + + fun getOrRefreshToken(preferences: EversenseStore): String? = DmsAccessTokens.resolve(preferences) { + login(preferences)?.let { DmsAccessTokens.Login(it.access_token, it.expires_in) } + } + + // -- Portal sync ------------------------------------------------------- + + /** + * POST api/care/PutCurrentValues � updates Last Sync Date on portal and feeds AGP reports. + */ + fun putCurrentValues( + preferences: EversenseStore, + glucose: Int, + timestamp: Long, + trend: EversenseTrendArrow, + signalStrength: Int, + batteryPercentage: Int + ): Boolean { + val token = getOrRefreshToken(preferences) ?: run { + EversenseLogger.error(TAG, "E3 putCurrentValues � no valid token") + return false + } + return try { + val ts = dateFormatter.get().format(Date(timestamp)) + val body = """{"CurrentGlucose":$glucose,"CGTime":"$ts","GlucoseTrend":${EversenseDmsBinaryCodec.trendOrdinal(trend)},"SignalStrength":${EversenseDmsBinaryCodec.signalStrengthOrdinal(signalStrength)},"BatteryStrength":${batteryPercentage.coerceAtLeast(0)},"IsTransmitterConnected":1}""" + + val reply = DmsHttpClient.post("${careBaseUrl}api/care/PutCurrentValues", body, token, readBody = false) + val code = reply.status + if (code >= 400) { + val err = reply.body + EversenseLogger.error(TAG, "E3 PutCurrentValues failed � status: $code") + false + } else { + EversenseLogger.debug(TAG) { "E3 PutCurrentValues ok � status: $code, glucose=$glucose" } + true + } + } catch (e: Exception) { + EversenseLogger.error(TAG, "E3 PutCurrentValues exception: $e") + false + } + } + + /** + * POST api/care/PutDeviceEvents � populates Sensor Glucose history table on portal. + */ + fun putDeviceEvents( + preferences: EversenseStore, + readings: List, + transmitterSerialNumber: String, + calibrations: List = emptyList(), + alerts: List = emptyList() + ): Boolean { + if (readings.isEmpty()) return true + val token = getOrRefreshToken(preferences) ?: run { + EversenseLogger.error(TAG, "E3 putDeviceEvents � no valid token") + return false + } + return try { + val rawSensorId = readings.firstOrNull { it.sensorId.isNotEmpty() }?.sensorId ?: getEversenseState(preferences).sensorId + val sensorId = if (rawSensorId.length >= 16) rawSensorId.chunked(2).take(8).reversed().joinToString("").uppercase() else rawSensorId + val tzOffsetSec = TimeZone.getDefault().getOffset(Date().time) / 1000 + val offsetBytes = Base64.getEncoder().encodeToString(EversenseDmsBinaryCodec.int32LE(tzOffsetSec)) + val sgBytes = EversenseDmsBinaryCodec.buildSgBytes(readings) + val mgBytes = if (calibrations.isNotEmpty()) EversenseDmsBinaryCodec.buildMgBytes(calibrations) else EversenseDmsBinaryCodec.buildEmptyMgBytes() + val patientBytes = EversenseDmsBinaryCodec.buildEmptyPatientBytes() + val alertBytes = EversenseDmsBinaryCodec.buildAlertBytes(sensorId, alerts, readings.lastOrNull()?.datetime ?: System.currentTimeMillis(), readings.lastOrNull()?.glucoseInMgDl ?: 0) + + EversenseLogger.debug(TAG) { "E3 PutDeviceEvents: ${readings.size} reading(s), txId='$transmitterSerialNumber'" } + + val body = """{"deviceType":"SMSIMeter","deviceName":"Smart Transmitter (Android)","deviceID":"$transmitterSerialNumber","offsetBytes":"$offsetBytes","sgBytes":"$sgBytes","mgBytes":"$mgBytes","patientBytes":"$patientBytes","alertBytes":"$alertBytes","algorithmVersion":"10"}""" + + val reply = DmsHttpClient.post("${careBaseUrl}api/care/PutDeviceEvents", body, token, readBody = false) + val code = reply.status + if (code >= 400) { + val err = reply.body + EversenseLogger.error(TAG, "E3 PutDeviceEvents failed � status: $code") + false + } else { + EversenseLogger.info(TAG, "E3 PutDeviceEvents ok � status: $code, readings: ${readings.size}") + true + } + } catch (e: Exception) { + EversenseLogger.error(TAG, "E3 PutDeviceEvents exception: $e") + false + } + } + + private fun getState(preferences: EversenseStore): EversenseSecureState { + val json = preferences.getString(StorageKeys.SECURE_STATE, null) ?: "{}" + return JSON.decodeFromString(json) + } + + private fun getEversenseState(preferences: EversenseStore): app.aaps.plugins.eversense.models.EversenseState { + val json = preferences.getString(StorageKeys.STATE, null) ?: "{}" + return try { JSON.decodeFromString(json) } catch (_: Exception) { app.aaps.plugins.eversense.models.EversenseState() } + } + } + + @Serializable + @SuppressLint("UnsafeOptInUsageError") + data class LoginResponseModel( + val access_token: String, + val expires_in: Int, + val token_type: String, + val expires: String, + val lastLogin: String + ) +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseLogger.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseLogger.kt new file mode 100644 index 000000000000..dce1edf151a2 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseLogger.kt @@ -0,0 +1,137 @@ +package app.aaps.plugins.eversense.util + +import ch.qos.logback.classic.LoggerContext +import ch.qos.logback.classic.joran.JoranConfigurator +import ch.qos.logback.core.joran.spi.JoranException +import java.io.ByteArrayInputStream +import java.io.InputStream + +class EversenseLogger private constructor(logDir: String) { + private val lc = LoggerContext() + + init { + val config = JoranConfigurator() + config.setContext(lc) + // Set before doConfigure() so ${EXT_FILES_DIR} in LOGBACK_XML resolves to this directory - + // Joran checks context properties during variable substitution even though LOGBACK_XML + // itself declares no element for it. + lc.putProperty("EXT_FILES_DIR", logDir) + + val stream: InputStream = ByteArrayInputStream(LOGBACK_XML.toByteArray()) + try { + config.doConfigure(stream) + lc.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME).level = + if (isDiagnosticLoggingEnabled) ch.qos.logback.classic.Level.DEBUG else ch.qos.logback.classic.Level.INFO + } catch (e: JoranException) { + android.util.Log.e("EversenseLogger", "Could not configure logging: ${e.javaClass.simpleName}") + } + } + + private fun debug(tag: String, message: String) { + lc.getLogger(tag).debug(message) + } + + private fun info(tag: String, message: String) { lc.getLogger(tag).info(message) } + private fun warning(tag: String, message: String) { lc.getLogger(tag).warn(message) } + private fun error(tag: String, message: String) { lc.getLogger(tag).error(message) } + + companion object { + // Fallback if configure() is never called before the first log call (e.g. a unit test, or + // some log call racing plugin construction) - matches this class's original, always-hardcoded + // behavior, so nothing regresses in that case; it just won't be reachable by the app's log + // export on modern Android (see configure()'s doc below). + private const val DEFAULT_LOG_DIR = "/sdcard/AndroidAPS/eversense" + + @Volatile private var configuredInstance: EversenseLogger? = null + + private val instance: EversenseLogger + get() = configuredInstance ?: synchronized(this) { + configuredInstance ?: EversenseLogger(DEFAULT_LOG_DIR).also { configuredInstance = it } + } + + /** + * Points Eversense's log file at [logDir] instead of [DEFAULT_LOG_DIR]. Call once, as early + * as possible - Logback is configured on first use of [instance], and later calls are a + * no-op once that has happened. See EversenseCGMPlugin, the sole caller: it passes the + * app's own scoped external-files directory - the same one AndroidAPS.log itself uses - + * because [DEFAULT_LOG_DIR] is a raw top-level /sdcard path, and writing there is silently + * blocked by scoped storage on modern Android without the MANAGE_EXTERNAL_STORAGE + * permission AAPS doesn't otherwise need. That silently produced zero Eversense.log entries + * in every log export a user ever sent while diagnosing this. + */ + fun configure(logDir: String) { + synchronized(this) { + if (configuredInstance == null) configuredInstance = EversenseLogger(logDir) + } + } + + @Volatile var isDiagnosticLoggingEnabled: Boolean = false + private set + + fun setDiagnosticLogging(enabled: Boolean) = synchronized(this) { + isDiagnosticLoggingEnabled = enabled + configuredInstance?.lc?.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME)?.level = + if (enabled) ch.qos.logback.classic.Level.DEBUG else ch.qos.logback.classic.Level.INFO + } + + fun debug(tag: String, message: () -> String) { + if (isDiagnosticLoggingEnabled) instance.debug(tag, message()) + } + + inline fun diagnostic(block: () -> Unit) { + if (isDiagnosticLoggingEnabled) block() + } + + fun info(tag: String, message: String) { + instance.info(tag, message) + } + + fun warning(tag: String, message: String) { + instance.warning(tag, message) + } + + fun error(tag: String, message: String) { + instance.error(tag, message) + } + + private const val LOGBACK_XML: String = "\n" + + " \n" + + " \n" + + " \${EXT_FILES_DIR}/Eversense.log\n" + + " \n" + + " \n" + + " \${EXT_FILES_DIR}/Eversense._%d{yyyy-MM-dd}_%d{HH-mm-ss, aux}_.%i.zip\n" + + " \n" + + "\n" + + " \n" + + " 5MB\n" + + " \n" + + " \n" + + " 120\n" + + " \n" + + " \n" + + " [%d{HH:mm:ss.SSS} %.-1level/%logger %msg%n\n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " %logger{0}\n" + + " \n" + + " \n" + + " [%d{HH:mm:ss.SSS} %msg%n\n" + + " \n" + + " \n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + "" + + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseScanner.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseScanner.kt new file mode 100644 index 000000000000..0f4c598637bd --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/EversenseScanner.kt @@ -0,0 +1,35 @@ +package app.aaps.plugins.eversense.util + +import android.annotation.SuppressLint +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanResult +import app.aaps.plugins.eversense.callbacks.EversenseScanCallback +import app.aaps.plugins.eversense.models.EversenseScanResult + +class EversenseScanner(private val callback: EversenseScanCallback): ScanCallback() { + + @SuppressLint("MissingPermission") + override fun onScanResult(callbackType: Int, scanRecord: ScanResult) { + // Allow devices with null names — use address as fallback label. + // Some Eversense transmitters may advertise without a device name. + val deviceName = scanRecord.device?.name ?: scanRecord.device?.address ?: return + + // Filter to only show Eversense transmitters. + // E3 transmitters advertise as "T" followed by a serial number (e.g. "T0214389", "T3xxxxxx"). + // E365 transmitters advertise starting with "365". + if (!deviceName.startsWith("T") && !deviceName.startsWith("365") && !deviceName.contains("versense", ignoreCase = true)) { + return + } + + EversenseLogger.debug(TAG) { "Found Eversense device: $deviceName (address: ${scanRecord.device?.address})" } + callback.onResult(EversenseScanResult(deviceName, scanRecord.rssi, scanRecord.device)) + } + + override fun onScanFailed(errorCode: Int) { + EversenseLogger.error(TAG, "BLE scan failed with error code: $errorCode") + } + + companion object { + private const val TAG = "EversenseScanner" + } +} \ No newline at end of file diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/MessageCoder.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/MessageCoder.kt new file mode 100644 index 000000000000..8e482ee256b1 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/MessageCoder.kt @@ -0,0 +1,114 @@ +package app.aaps.plugins.eversense.util + +import app.aaps.plugins.eversense.enums.EversenseAlarm + +object MessageCoder { + + fun messageCodeForGlucoseLevelAlarmFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.LOW_GLUCOSE + 2 -> EversenseAlarm.HIGH_GLUCOSE + else -> null + } + + fun messageCodeForGlucoseLevelAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.LOW_GLUCOSE + 2 -> EversenseAlarm.HIGH_GLUCOSE + else -> null + } + + fun messageCodeForRateAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.RATE_FALLING + 2 -> EversenseAlarm.RATE_RISING + else -> null + } + + fun messageCodeForPredictiveAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.PREDICTIVE_LOW + 4 -> EversenseAlarm.PREDICTIVE_HIGH + else -> null + } + + fun messageCodeForSensorHardwareAndAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.UNKNOWN + 2 -> EversenseAlarm.SENSOR_AWOL + 4 -> EversenseAlarm.UNKNOWN + 8 -> EversenseAlarm.UNKNOWN + 16 -> EversenseAlarm.UNKNOWN + 32 -> EversenseAlarm.UNKNOWN + 64 -> EversenseAlarm.UNKNOWN + 128 -> EversenseAlarm.UNKNOWN + else -> null + } + + fun messageCodeForSensorReadAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.SERIOUSLY_HIGH + 2 -> EversenseAlarm.SERIOUSLY_LOW + 4 -> EversenseAlarm.UNKNOWN + 8 -> EversenseAlarm.UNKNOWN + 16 -> EversenseAlarm.SENSOR_TEMPERATURE + 32 -> EversenseAlarm.SENSOR_LOW_TEMPERATURE + 64 -> EversenseAlarm.READER_TEMPERATURE + 128 -> EversenseAlarm.MSP_ALARM + else -> null + } + + fun messageCodeForSensorReplacementFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.SENSOR_RETIRED + 2 -> EversenseAlarm.SENSOR_RETIRING_SOON_1 + 4 -> EversenseAlarm.SENSOR_RETIRING_SOON_1 + 8 -> EversenseAlarm.SENSOR_RETIRING_SOON_3 + 16 -> EversenseAlarm.SENSOR_RETIRING_SOON_4 + 32 -> EversenseAlarm.SENSOR_RETIRING_SOON_5 + 64 -> EversenseAlarm.SENSOR_RETIRING_SOON_6 + 128 -> EversenseAlarm.UNKNOWN + else -> null + } + + fun messageCodeForSensorCalibrationFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.CALIBRATION_GRACE_PERIOD + 2 -> EversenseAlarm.CALIBRATION_EXPIRED + 4 -> EversenseAlarm.CALIBRATION_GRACE_PERIOD + 16 -> EversenseAlarm.CALIBRATION_GRACE_PERIOD + 32 -> EversenseAlarm.CALIBRATION_GRACE_PERIOD + 64 -> EversenseAlarm.CALIBRATION_GRACE_PERIOD + 128 -> EversenseAlarm.CALIBRATION_GRACE_PERIOD + else -> null + } + + fun messageCodeForTransmitterStatusAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.CRITICAL_FAULT + 4 -> EversenseAlarm.INVALID_SENSOR + 8 -> EversenseAlarm.INVALID_CLOCK + 32 -> EversenseAlarm.VIBRATION_CURRENT + 64 -> EversenseAlarm.UNKNOWN + 128 -> EversenseAlarm.UNKNOWN + else -> null + } + + fun messageCodeForTransmitterBatteryAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.EMPTY_BATTERY + 2 -> EversenseAlarm.VERY_LOW_BATTERY + 4 -> EversenseAlarm.EMPTY_BATTERY + 8 -> EversenseAlarm.BATTERY_ERROR + else -> null + } + + fun messageCodeForTransmitterEOLAlertFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.TRANSMITTER_EOL_396 + 2 -> EversenseAlarm.TRANSMITTER_EOL_366 + 4 -> EversenseAlarm.TRANSMITTER_EOL_330 + 8 -> EversenseAlarm.TRANSMITTER_EOL_395 + else -> null + } + + fun messageCodeForSensorReplacementFlags2(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.SENSOR_RETIRING_SOON_7 + else -> null + } + + fun messageCodeForCalibrationSwitchFlags(value: Int): EversenseAlarm? = when (value) { + 1 -> EversenseAlarm.ONE_CAL + 2 -> EversenseAlarm.TWO_CAL + else -> null + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/RangeCalculator.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/RangeCalculator.kt new file mode 100644 index 000000000000..b76a13c082a6 --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/RangeCalculator.kt @@ -0,0 +1,21 @@ +package app.aaps.plugins.eversense.util + +import kotlin.math.min + +data class RangeCalculation(val from: Int, val to: Int) + +object RangeCalculator { + fun calculateGlucoseRange(rangeFrom: Int, rangeTo: Int, lastGlucoseTimestampMs: Long): RangeCalculation { + val timeDiffMs = System.currentTimeMillis() - lastGlucoseTimestampMs + val fiveMinMs = 5 * 60 * 1000L + val pageCount = min(((timeDiffMs / fiveMinMs) + 2).toInt(), 20) + val from = maxOf(rangeTo - pageCount, rangeFrom) + return RangeCalculation(from = from, to = rangeTo) + } + + fun calculateRange(rangeFrom: Int, rangeTo: Int): RangeCalculation { + val count = min(rangeTo - rangeFrom, 20) + val from = maxOf(rangeTo - count, rangeFrom) + return RangeCalculation(from = from, to = rangeTo) + } +} diff --git a/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/StorageKeys.kt b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/StorageKeys.kt new file mode 100644 index 000000000000..716b83fd3b2c --- /dev/null +++ b/plugins/eversense/src/androidMain/kotlin/app/aaps/plugins/eversense/util/StorageKeys.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.eversense.util + +class StorageKeys { + companion object { + const val REMOTE_DEVICE_KEY = "eversense_remote_device" + const val STATE = "eversense_state" + const val SECURE_STATE = "eversense_state_secure" + const val CLOUD_QUEUE = "eversense_cloud_queue" + const val CLOUD_LAST_ATTEMPT = "eversense_cloud_last_attempt" + const val ACCESS_TOKEN = "eversense_access_token" + const val ACCESS_TOKEN_EXPIRY = "eversense_access_token_expiry" + } +} \ No newline at end of file diff --git a/plugins/source/build.gradle.kts b/plugins/source/build.gradle.kts index 905d6c2c946c..8edcbac363f2 100644 --- a/plugins/source/build.gradle.kts +++ b/plugins/source/build.gradle.kts @@ -1,5 +1,6 @@ plugins { id("kmp-android-library") + id("kotlinx-serialization") alias(libs.plugins.compose.compiler) alias(libs.plugins.compose.multiplatform) alias(libs.plugins.metro) @@ -42,6 +43,8 @@ kotlin { androidMain { dependencies { + api(project(":plugins:eversense")) + implementation(libs.androidx.appcompat) implementation(project.dependencies.platform(libs.androidx.compose.bom)) implementation(libs.androidx.compose.material3) implementation(libs.androidx.compose.runtime) diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/NotificationReaderPluginTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/NotificationReaderPluginTest.kt index 26a38c3203ac..e12e9ea4828d 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/NotificationReaderPluginTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/NotificationReaderPluginTest.kt @@ -1,15 +1,31 @@ package app.aaps.plugins.source +import android.content.res.AssetManager +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.keys.StringNonKey import app.aaps.shared.tests.TestBaseWithProfile import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever class NotificationReaderPluginTest : TestBaseWithProfile() { private lateinit var notificationReaderPlugin: NotificationReaderPlugin + private val bundledDefinitions = """ + { + "version": 3, + "packages": [ + {"package":"com.senseonics.eversense365.us","sensor":"Eversense","intervalMinutes":5}, + {"package":"com.senseonics.eversense365.ous","sensor":"Eversense","intervalMinutes":5} + ] + } + """.trimIndent() + @BeforeEach fun setup() { // construction runs loadPackageConfig() (falls back to an empty config when the asset/pref is absent) @@ -30,4 +46,38 @@ class NotificationReaderPluginTest : TestBaseWithProfile() { assertThat(permissions.flatMap { it.permissions }) .contains(NotificationReaderPlugin.PERMISSION_NOTIFICATION_LISTENER) } + + @Test + fun `new bundled definitions add both Eversense365 packages after an app update`() { + val stored = """{"version":2,"packages":[{"package":"com.senseonics.eversense365.us","sensor":"Eversense"}]}""" + whenever(preferences.get(StringNonKey.NotificationReaderPackages)).thenReturn(stored) + val assets = mock() + whenever(context.assets).thenReturn(assets) + whenever(assets.open("notification_reader_packages.json")).thenReturn(bundledDefinitions.byteInputStream()) + + val plugin = NotificationReaderPlugin(rh, aapsLogger, preferences, config, context, mock()) + + assertThat(plugin.packageConfig.version).isEqualTo(3) + for (pkg in listOf("com.senseonics.eversense365.us", "com.senseonics.eversense365.ous")) { + assertThat(plugin.packageConfig.isSupportedPackage(pkg)).isTrue() + assertThat(plugin.packageConfig.sensorForPackage(pkg)).isEqualTo(SourceSensor.EVERSENSE) + assertThat(plugin.packageConfig.intervalForPackage(pkg, 0L)).isEqualTo(300_000L) + } + verify(preferences).put(StringNonKey.NotificationReaderPackages, bundledDefinitions) + } + + @Test + fun `newer cached definitions are preserved when bundled definitions are older`() { + val stored = """{"version":4,"packages":[{"package":"com.senseonics.eversense365.ous","sensor":"Eversense"}]}""" + whenever(preferences.get(StringNonKey.NotificationReaderPackages)).thenReturn(stored) + val assets = mock() + whenever(context.assets).thenReturn(assets) + whenever(assets.open("notification_reader_packages.json")).thenReturn(bundledDefinitions.byteInputStream()) + + val plugin = NotificationReaderPlugin(rh, aapsLogger, preferences, config, context, mock()) + + assertThat(plugin.packageConfig.version).isEqualTo(4) + assertThat(plugin.packageConfig.isSupportedPackage("com.senseonics.eversense365.ous")).isTrue() + verify(preferences, never()).put(StringNonKey.NotificationReaderPackages, bundledDefinitions) + } } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseCloudUploaderTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseCloudUploaderTest.kt new file mode 100644 index 000000000000..c4c1e36ec218 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseCloudUploaderTest.kt @@ -0,0 +1,161 @@ +package app.aaps.plugins.source.eversense + +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.util.StorageKeys +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import org.mockito.kotlin.* + +@OptIn(ExperimentalCoroutinesApi::class) +class EversenseCloudUploaderTest { + private val prefs: EversenseStore = mock() + private val values = mutableMapOf() + private var online = true + private var enabled = true + private var wall = 1_800_000_000_000L + private var monotonic = 0L + private var success = true + private val uploads = mutableListOf() + private val errors = mutableListOf() + private val state = EversenseState().apply { transmitterSerialNumber = "T123" } + init { + whenever(prefs.getString(any(), anyOrNull())).thenAnswer { values[it.getArgument(0)] as? String ?: it.getArgument(1) } + whenever(prefs.getLong(any(), any())).thenAnswer { values[it.getArgument(0)] as? Long ?: it.getArgument(1) } + whenever(prefs.contains(any())).thenAnswer { values.containsKey(it.getArgument(0)) } + whenever(prefs.edit()).thenAnswer { + object : EversenseStore.Editor { + val changes = mutableMapOf() + override fun putString(key: String, value: String?) = apply { changes[key] = value } + override fun putLong(key: String, value: Long) = apply { changes[key] = value } + override fun putInt(key: String, value: Int) = apply { changes[key] = value } + override fun putBoolean(key: String, value: Boolean) = apply { changes[key] = value } + override fun remove(key: String) = apply { changes[key] = null } + override fun clear() = apply { values.clear() } + override fun commit(): Boolean { changes.forEach { (k,v) -> if(v == null) values.remove(k) else values[k] = v }; return true } + override fun apply() { commit() } + } + } + } + private fun TestScope.uploader(upload: suspend (EversenseStore, EversenseCloudUploader.PendingUpload) -> Boolean = { _, batch -> uploads.add(batch); success }) = + EversenseCloudUploader({ backgroundScope }, { prefs }, { enabled }, { online }, { wall }, { monotonic }, upload, errors::add) + private fun reading(minute: Int) = EversenseCGMResult(100 + minute, wall + minute * 60_000L, EversenseTrendArrow.FLAT, "sensor", "0102") + private fun pending() = Json.decodeFromString>(values[StorageKeys.CLOUD_QUEUE] as? String ?: "[]") + private fun hour() { wall += EversenseCloudUploader.HOUR_MS; monotonic += EversenseCloudUploader.HOUR_MS } + + @Test fun offlineReadingsAreRetainedAndUploadedTogetherAfterInternetReturns() = runTest { + online = false + val uploader = uploader() + for (i in 0..11) { uploader.enqueue(EversenseType.EVERSENSE_365, listOf(reading(i)), state); runCurrent() } + assertTrue(uploads.isEmpty()) + assertEquals(12, pending().single().readings.size) + assertFalse(values.containsKey(StorageKeys.CLOUD_LAST_ATTEMPT)) + online = true + uploader.flush() + runCurrent() + assertEquals(12, uploads.single().readings.size) + assertTrue(pending().isEmpty()) + } + @Test fun hourlyBatchContainsAllIntermediateReadingsAndUsesLatestReadingForPortal() = runTest { + val uploader = uploader() + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + for (i in 1..11) { uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(i)), state); runCurrent() } + assertEquals(1, uploads.size) + hour() + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + assertEquals(2, uploads.size) + assertEquals(12, uploads.last().readings.size) + } + @Test fun failedUploadIsRetainedAndDoesNotRetryWithinTheHourEvenAfterRestart() = runTest { + success = false + var uploader = uploader() + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + assertEquals(1, uploads.size) + uploader = uploader() + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(5)), state) + runCurrent() + assertEquals(1, uploads.size) + assertEquals(2, pending().single().readings.size) + hour() + success = true + uploader.flush() + runCurrent() + assertEquals(2, uploads.size) + assertTrue(pending().isEmpty()) + } + @Test fun slowNetworkDoesNotBlockQueuingNewReadingsOrLoseThemOnAcknowledgment() = runTest { + val release = CompletableDeferred() + val uploader = uploader { _, batch -> uploads.add(batch); release.await(); true } + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(5)), state) + runCurrent() + assertEquals(1, uploads.size) + release.complete(Unit) + runCurrent() + assertEquals(listOf(reading(5)), pending().single().readings) + } + @Test fun uploadExceptionKeepsPendingDataAndReleasesWorkerForNextHour() = runTest { + val uploader = uploader { _, _ -> throw IllegalStateException("network unavailable") } + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + assertEquals(1, errors.size) + assertEquals(1, pending().single().readings.size) + hour() + uploader.flush() + runCurrent() + assertEquals(2, errors.size) + } + @Test fun duplicateReadingsAreDeduplicatedAndDisabledUploadDoesNotQueue() = runTest { + online = false + val uploader = uploader() + uploader.enqueue(EversenseType.EVERSENSE_365, listOf(reading(0), reading(0)), state) + runCurrent() + assertEquals(1, pending().single().readings.size) + enabled = false + uploader.enqueue(EversenseType.EVERSENSE_365, listOf(reading(5)), state) + runCurrent() + assertEquals(1, pending().single().readings.size) + assertTrue(uploads.isEmpty()) + } + @Test fun historyWithoutRaw365PayloadDoesNotBlockUploadQueue() = runTest { + val uploader = uploader() + uploader.enqueue(EversenseType.EVERSENSE_365, listOf(reading(0).copy(rawResponseHex = "")), state) + runCurrent() + assertTrue(uploads.isEmpty()) + assertTrue(pending().isEmpty()) + } + @Test fun wallClockJumpCannotCauseAnotherUploadInSameElapsedHour() = runTest { + val uploader = uploader() + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + wall += 24 * EversenseCloudUploader.HOUR_MS + uploader.enqueue(EversenseType.EVERSENSE_E3, listOf(reading(0)), state) + runCurrent() + assertEquals(1, uploads.size) + } + @Test fun queueHasSevenDayAnd2016ReadingLimit() = runTest { + online = false + val uploader = uploader() + val samples = (0..2100).map { reading(it).copy(datetime = wall - it * 5 * 60_000L) } + uploader.enqueue(EversenseType.EVERSENSE_E3, samples, state) + runCurrent() + assertEquals(2016, pending().single().readings.size) + wall += 8 * 24 * EversenseCloudUploader.HOUR_MS + uploader.enqueue(EversenseType.EVERSENSE_E3, emptyList(), state) + runCurrent() + assertTrue(pending().isEmpty()) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseNavigationTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseNavigationTest.kt new file mode 100644 index 000000000000..8fb0c2bee947 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseNavigationTest.kt @@ -0,0 +1,114 @@ +package app.aaps.plugins.source.eversense + +import android.app.Application +import androidx.compose.material3.ColorScheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.SideEffect +import androidx.compose.ui.graphics.toPixelMap +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.captureToImage +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithContentDescription +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.AapsTheme +import app.aaps.core.ui.compose.LocalPreferences +import app.aaps.plugins.source.R +import app.aaps.plugins.source.activities.EversensePage +import app.aaps.plugins.source.activities.EversensePlacementContent +import app.aaps.plugins.source.activities.EversenseStatusContent +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode +import app.aaps.core.ui.R as CoreR + +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35], application = Application::class) +class EversenseNavigationTest { + @get:Rule val compose = createComposeRule() + private val preferences: Preferences = mock() + private val mode = MutableStateFlow("dark") + + private fun show(connected: Boolean = true, onBack: () -> Unit = {}, onConnect: () -> Unit = {}, onDays: (Int) -> Unit = {}, colors: (ColorScheme) -> Unit = {}) { + whenever(preferences.observe(StringKey.GeneralDarkMode)).thenReturn(mode) + compose.setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + val scheme = MaterialTheme.colorScheme + SideEffect { colors(scheme) } + EversensePage(R.string.eversense_status_title, onBack) { + EversenseStatusContent(listOf("Status example"), connected, 14, onConnect, {}, {}, onDays) + } + } + } + } + } + + @Test fun statusUsesCentralThemeAndUpdatesWhenThemeChanges() { + var colors: ColorScheme? = null + show(colors = { colors = it }) + compose.waitForIdle() + val darkImage = compose.onRoot().captureToImage() + val darkBackground = darkImage.toPixelMap()[0, darkImage.height / 2] + assertEquals(colors!!.background, darkBackground) + compose.onNodeWithText("Status example").assertIsDisplayed() + compose.runOnIdle { mode.value = "light" } + compose.waitForIdle() + val lightImage = compose.onRoot().captureToImage() + val lightBackground = lightImage.toPixelMap()[0, lightImage.height / 2] + assertEquals(colors!!.background, lightBackground) + assertNotEquals(darkBackground, lightBackground) + } + + @Test fun backArrowInvokesNavigationAndDisconnectedSyncIsDisabled() { + var back = false + var connect = false + show(connected = false, onBack = { back = true }, onConnect = { connect = true }) + val context = RuntimeEnvironment.getApplication() + compose.onNodeWithContentDescription(context.getString(CoreR.string.back)).performClick() + compose.runOnIdle { assertEquals(true, back) } + compose.onNodeWithText(context.getString(R.string.eversense_information_last_sync)).assertIsNotEnabled() + compose.onNodeWithText(context.getString(R.string.eversense_status_connect)).performClick() + compose.runOnIdle { assertEquals(true, connect) } + } + + @Test fun syncDaysSelectionKeepsExistingChoicesAndCallback() { + var selected = 0 + show(onDays = { selected = it }) + compose.onNodeWithText("14").performClick() + compose.onNodeWithText("30").performClick() + compose.runOnIdle { assertEquals(30, selected) } + } + + @Test fun placementShowsLiveValuesAndInstructionsInsideTheSamePage() { + whenever(preferences.observe(StringKey.GeneralDarkMode)).thenReturn(mode) + compose.setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + EversensePage(R.string.eversense_placement_title, {}) { + EversensePlacementContent("Good", "60%", "Keep position", "Updated now", 4) + } + } + } + } + compose.onNodeWithText("Good").assertIsDisplayed() + compose.onNodeWithText("60%").assertIsDisplayed() + compose.onNodeWithText("Keep position").performScrollTo().assertIsDisplayed() + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversensePluginTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversensePluginTest.kt new file mode 100644 index 000000000000..67b5f09cf9da --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversensePluginTest.kt @@ -0,0 +1,157 @@ +package app.aaps.plugins.source.eversense + +import app.aaps.core.data.plugin.PluginType +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.keys.PreferenceType +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.ue.Sources +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.keys.LongNonKey +import app.aaps.plugins.eversense.EversenseCGMPlugin +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.enums.EversenseTrendArrow +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.never +import org.mockito.kotlin.whenever +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.preference.PreferenceSubScreenDef +import app.aaps.plugins.source.EversensePlugin +import app.aaps.plugins.source.keys.EversenseBooleanKey +import app.aaps.plugins.source.keys.EversenseRuntimeKey +import app.aaps.plugins.source.keys.EversenseIntentKey +import app.aaps.plugins.source.keys.EversenseStringKey as CredentialsKey +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify + +class EversensePluginTest { + @Test fun registersCredentialsAndCloudSettingsAndProvidesDeviceActions() { + val preferences: Preferences = mock() + val plugin = EversensePlugin(mock(), mock(), mock(), preferences, mock(), mock(), mock(), mock()) + verify(preferences).registerPreferences(CredentialsKey.entries + EversenseBooleanKey.entries + EversenseIntentKey.entries + EversenseStringKey.entries + EversenseRuntimeKey.entries) + assertThat(plugin.pluginDescription.mainType).isEqualTo(PluginType.BGSOURCE) + assertThat(plugin.pluginDescription.composeContentProvider).isNotNull() + assertThat(plugin.pluginDescription.defaultPlugin).isFalse() + val screen = plugin.getPreferenceScreenContent() + assertThat(screen.items).contains(EversenseBooleanKey.EversenseCloudUploadEnabled) + assertThat(screen.items).contains(EversenseBooleanKey.EversenseDiagnosticLogging) + assertThat(EversenseBooleanKey.EversenseDiagnosticLogging.defaultValue).isFalse() + assertThat(EversenseBooleanKey.EversenseDiagnosticLogging.exportable).isFalse() + assertThat(EversenseBooleanKey.entries.all { it.preferenceType == PreferenceType.SWITCH }).isTrue() + val credentials = screen.items.filterIsInstance().single() + assertThat(credentials.items).containsAtLeast(CredentialsKey.EversenseUsername, CredentialsKey.EversensePassword) + } + @Test fun successfulCalibrationUpdatesCountdownAndRequestsSync() = runBlocking { + val preferences: Preferences = mock() + val backend: EversenseCGMPlugin = mock() + whenever(backend.isConnected()).thenReturn(true) + whenever(backend.sendCalibration(any(), any())).thenReturn(true) + val plugin = EversensePlugin(mock(), mock(), mock(), preferences, mock(), mock(), { backend }, mock()) + assertThat(plugin.calibrate(100)).isTrue() + verify(backend).sendCalibration(eq(100), any()) + verify(backend).triggerFullSync(force = true) + verify(preferences).put(eq(LongNonKey.EversenseLastCalibrationSubmittedAt), any()) + } + + @Test fun failedCalibrationDoesNotStartCountdown() = runBlocking { + val preferences: Preferences = mock() + val backend: EversenseCGMPlugin = mock() + whenever(backend.isConnected()).thenReturn(true) + whenever(backend.sendCalibration(any(), any())).thenReturn(false) + val plugin = EversensePlugin(mock(), mock(), mock(), preferences, mock(), mock(), { backend }, mock()) + assertThat(plugin.calibrate(100)).isFalse() + verify(preferences, never()).put(eq(LongNonKey.EversenseLastCalibrationSubmittedAt), any()) + verify(backend, never()).triggerFullSync(any()) + } + + @Test fun readingsKeepValuesTimestampsTrendsAndModelWhenPassedToPersistence() = runBlocking { + for ((type, sensor) in listOf(EversenseType.EVERSENSE_E3 to SourceSensor.EVERSENSE_E3, EversenseType.EVERSENSE_365 to SourceSensor.EVERSENSE_365)) { + val backend: EversenseCGMPlugin = mock() + whenever(backend.getCurrentState()).thenReturn(EversenseState()) + val persistence: PersistenceLayer = mock() + val received = CompletableDeferred>() + whenever(persistence.insertCgmSourceData(any(), any(), any(), anyOrNull())).thenAnswer { + received.complete(it.getArgument(1)) + PersistenceLayer.TransactionResult() + } + val plugin = EversensePlugin(mock(), mock(), mock(), mock(), mock(), mock(), { backend }, persistence) + plugin.onCGMRead(type, listOf(EversenseCGMResult(123, 1_700_000_000_000L, EversenseTrendArrow.FLAT))) + val values = withTimeout(5_000) { received.await() } + assertThat(values.single().value).isEqualTo(123.0) + assertThat(values.single().timestamp).isEqualTo(1_700_000_000_000L) + assertThat(values.single().sourceSensor).isEqualTo(sensor) + assertThat(values.single().trendArrow).isEqualTo(TrendArrow.FLAT) + verify(persistence).insertCgmSourceData(Sources.Eversense, values, emptyList(), null) + plugin.onStop() + } + } + + @Test fun settingsImportHooksDoNotRewindLiveDeviceState() { + val preferences: Preferences = mock() + val plugin = EversensePlugin(mock(), mock(), mock(), preferences, mock(), mock(), { error("Bluetooth must stay closed") }, mock()) + plugin.beforeImport() + plugin.afterImport() + verify(preferences, never()).put(eq(EversenseRuntimeKey.DeviceState), any()) + } + + @Test fun signingOutClearsTypedCredentialsAndStopsBackendSession() { + val preferences: Preferences = mock() + val backend: EversenseCGMPlugin = mock() + val plugin = EversensePlugin(mock(), mock(), mock(), preferences, mock(), mock(), { backend }, mock()) + val screen = plugin.getPreferenceScreenContent() + assertThat(screen.items.filterIsInstance() + .any { it.key == EversenseIntentKey.EversenseSignOut.key }).isFalse() + val action = screen.items.filterIsInstance().single().items + .filterIsInstance() + .single { it.key == EversenseIntentKey.EversenseSignOut.key } + assertThat(action.confirmationMessage).isNotNull() + assertThat(CredentialsKey.EversensePassword.requiresPasswordConfirmation).isFalse() + action.onClick?.invoke() + verify(preferences).put(CredentialsKey.EversenseUsername, "") + verify(preferences).put(CredentialsKey.EversensePassword, "") + verify(backend).clearCredentials() + } + + @Test fun stoppingSourceAlsoStopsBackendAndRemovesWatcher() = runBlocking { + val backend: EversenseCGMPlugin = mock() + val plugin = EversensePlugin(mock(), mock(), mock(), mock(), mock(), mock(), { backend }, mock()) + plugin.onStop() + verify(backend).removeWatcher(plugin) + verify(backend).stop() + } + + @Test fun localGlucosePersistenceContinuesWhenCloudQueueFails() = runBlocking { + val backend: EversenseCGMPlugin = mock() + val preferences: Preferences = mock() + whenever(backend.getCurrentState()).thenReturn(EversenseState()) + whenever(preferences.get(EversenseBooleanKey.EversenseCloudUploadEnabled)).thenReturn(true) + val cloudFailed = CompletableDeferred() + whenever(backend.cloudStore()).thenAnswer { cloudFailed.complete(Unit); throw IllegalStateException("cloud unavailable") } + val persistence: PersistenceLayer = mock() + val received = kotlinx.coroutines.channels.Channel>(2) + whenever(persistence.insertCgmSourceData(any(), any(), any(), anyOrNull())).thenAnswer { + received.trySend(it.getArgument(1)) + PersistenceLayer.TransactionResult() + } + val plugin = EversensePlugin(mock(), mock(), mock(), preferences, mock(), mock(), { backend }, persistence) + try { + plugin.onCGMRead(EversenseType.EVERSENSE_365, listOf(EversenseCGMResult(123, 1_800_000_000_000L, EversenseTrendArrow.FLAT))) + assertThat(withTimeout(5_000) { received.receive() }.single().value).isEqualTo(123.0) + withTimeout(5_000) { cloudFailed.await() } + plugin.onCGMRead(EversenseType.EVERSENSE_365, listOf(EversenseCGMResult(124, 1_800_000_300_000L, EversenseTrendArrow.FLAT))) + assertThat(withTimeout(5_000) { received.receive() }.single().value).isEqualTo(124.0) + verify(backend, never()).forceReconnect() + verify(backend, never()).disconnect() + } finally { plugin.onStop() } + } + +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseStateStoreTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseStateStoreTest.kt new file mode 100644 index 000000000000..c247fa8c98ab --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/EversenseStateStoreTest.kt @@ -0,0 +1,74 @@ +package app.aaps.plugins.source.eversense + +import android.content.Context +import android.content.SharedPreferences +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.eversense.storage.edit +import app.aaps.plugins.source.keys.EversenseRuntimeKey +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class EversenseStateStoreTest { + private val context: Context = mock() + private val preferences: Preferences = mock() + private val legacy: SharedPreferences = mock() + private var stored: String? = null + + @BeforeEach fun setup() { + whenever(context.getSharedPreferences("EversenseCGMManager", Context.MODE_PRIVATE)).thenReturn(legacy) + whenever(legacy.all).thenReturn(emptyMap()) + whenever(preferences.getIfExists(EversenseRuntimeKey.DeviceState)).thenAnswer { stored } + whenever(preferences.get(EversenseRuntimeKey.DeviceState)).thenAnswer { stored ?: "{}" } + doAnswer { stored = it.getArgument(1); null }.whenever(preferences).put(eq(EversenseRuntimeKey.DeviceState), any()) + } + + @Test fun importsLegacyTypesAndDoesNotReadOldStateAgain() { + whenever(legacy.all).thenReturn(mapOf("state" to "{\"serial\":\"test\"}", "expiry" to 9_000_000_000L, "days" to 14, "dismissed" to true)) + val store = EversenseStateStore(context, preferences) + assertThat(store.getString("state", null)).isEqualTo("{\"serial\":\"test\"}") + assertThat(store.getLong("expiry", 0)).isEqualTo(9_000_000_000L) + assertThat(store.getInt("days", 0)).isEqualTo(14) + assertThat(store.getBoolean("dismissed", false)).isTrue() + EversenseStateStore(context, preferences) + verify(context).getSharedPreferences("EversenseCGMManager", Context.MODE_PRIVATE) + assertThat(EversenseRuntimeKey.DeviceState.exportable).isFalse() + } + + @Test fun independentlyCreatedEditorsMergeAndNullRemovesAValue() { + val store = EversenseStateStore(context, preferences) + val first = store.edit().putString("device", "test") + val second = store.edit().putLong("sequence", 5L) + first.commit() + second.apply() + assertThat(store.getString("device", null)).isEqualTo("test") + assertThat(store.getLong("sequence", 0L)).isEqualTo(5L) + store.edit(commit = true) { putString("device", null) } + assertThat(store.contains("device")).isFalse() + assertThat(store.getString("device", "fallback")).isEqualTo("fallback") + assertThat(store.getLong("sequence", 0L)).isEqualTo(5L) + } + + @Test fun clearKeepsOnlyValuesFromTheCurrentEdit() { + val store = EversenseStateStore(context, preferences) + store.edit { putInt("old", 1) } + store.edit { clear(); putBoolean("new", true) } + assertThat(store.contains("old")).isFalse() + assertThat(store.getBoolean("new", false)).isTrue() + } + @Test fun cloudQueueUsesSeparateNonExportablePreference() { + val store = EversenseStateStore(context, preferences) + val before = stored + store.edit { putString(app.aaps.plugins.eversense.util.StorageKeys.CLOUD_QUEUE, "[]") } + verify(preferences).put(EversenseRuntimeKey.CloudQueue, "[]") + assertThat(stored).isEqualTo(before) + assertThat(EversenseRuntimeKey.CloudQueue.exportable).isFalse() + } + +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/PositioningSessionTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/PositioningSessionTest.kt new file mode 100644 index 000000000000..421548a12fcf --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/eversense/PositioningSessionTest.kt @@ -0,0 +1,61 @@ +package app.aaps.plugins.source.eversense + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.* +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test +import kotlinx.coroutines.ExperimentalCoroutinesApi + +@OptIn(ExperimentalCoroutinesApi::class) +class PositioningSessionTest { + @Test fun leavingBeforeDelayedStartDoesNotEnterDiagnosticMode() = runTest { + val events = mutableListOf() + val session = PositioningSession(backgroundScope, { events.add("enter") }, { events.add("read") }, { events.add("exit") }) + session.resume() + runCurrent() + advanceTimeBy(499) + session.pause() + runCurrent() + advanceTimeBy(10_000) + assertTrue(events.isEmpty()) + } + @Test fun pauseStopsPollingAndExitsDiagnosticMode() = runTest { + val events = mutableListOf() + val session = PositioningSession(backgroundScope, { events.add("enter") }, { events.add("read") }, { events.add("exit") }) + session.resume() + advanceTimeBy(501) + assertEquals(listOf("enter", "read"), events) + session.pause() + runCurrent() + advanceTimeBy(5_000) + assertEquals(listOf("enter", "read", "exit"), events) + } + @Test fun rapidResumeWaitsForPreviousExitBeforeEnteringAgain() = runTest { + val events = mutableListOf() + val session = PositioningSession(backgroundScope, + { events.add("enter") }, { events.add("read") }, + { events.add("exit-start"); delay(1_000); events.add("exit-end") }) + session.resume() + advanceTimeBy(501) + session.pause() + session.resume() + advanceTimeBy(1_001) + assertEquals(listOf("enter", "read", "exit-start", "exit-end"), events) + advanceTimeBy(500) + assertEquals("enter", events[4]) + session.pause() + advanceTimeBy(1_001) + } + @Test fun cancellationDuringEntryStillExitsDiagnosticMode() = runTest { + val entered = CompletableDeferred() + var exits = 0 + val session = PositioningSession(backgroundScope, { entered.complete(Unit); delay(10_000) }, {}, { exits++ }) + session.resume() + advanceTimeBy(501) + assertTrue(entered.isCompleted) + session.pause() + runCurrent() + assertEquals(1, exits) + } +} diff --git a/plugins/source/src/androidMain/AndroidManifest.xml b/plugins/source/src/androidMain/AndroidManifest.xml index 607a2dbf65df..ce06414a0a6f 100644 --- a/plugins/source/src/androidMain/AndroidManifest.xml +++ b/plugins/source/src/androidMain/AndroidManifest.xml @@ -4,6 +4,11 @@ + + + + + ()) +@ContributesBinding(AppScope::class, binding = binding()) +@MetroIntKey(415) +@SingleIn(AppScope::class) +@Inject +class EversensePlugin( + override val rh: ResourceHelper, + private val context: Context, + aapsLogger: AAPSLogger, + preferences: Preferences, + config: Config, + notificationManager: NotificationManager, + private val eversenseProvider: () -> EversenseCGMPlugin, + private val persistenceLayer: PersistenceLayer +) : AbstractBgSourcePlugin( + PluginDescription() + .mainType(PluginType.BGSOURCE) + .composeContent { _ -> + BgSourceComposeContent( + title = rh.gs(R.string.source_eversense) + ) + } + .icon(IcPluginEversense) + .pluginName(TextRef.AndroidRes(R.string.source_eversense)) + .preferencesVisibleInSimpleMode(false) + .description(TextRef.AndroidRes(R.string.description_source_eversense)), + ownPreferences = EversenseStringKey.entries + EversenseBooleanKey.entries + EversenseIntentKey.entries + LegacyEversenseStringKey.entries + EversenseRuntimeKey.entries, + aapsLogger, rh, preferences, config, notificationManager +), BgSource, EversenseWatcher, EversenseCalibrationSource { + + private val eversense get() = eversenseProvider() + + companion object { + + // See onAlarmReceived()'s isSpuriousPostExitUnknown comment: the transmitter's unrecognized + // post-exit status push arrives ~1-2s after exitPositioningMode() per device logs; this is a + // generous margin over that without being wide enough to risk masking an unrelated + // genuinely-unrecognized alarm that happens to follow shortly after someone closes the + // placement guide. + private const val POST_EXIT_UNKNOWN_ALARM_SUPPRESS_WINDOW_MS = 5000L + } + + + override var sensorBatteryLevel = -1 + + private val mainHandler = Handler(Looper.getMainLooper()) + private var ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + // Android can omit the disconnect callback while Bluetooth is off. Reopen the client when + // the radio returns, respecting manual pause and the source's stopped state. + private val bluetoothStateReceiver = object : BroadcastReceiver() { + override fun onReceive(ctx: Context, intent: Intent) { + if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) == BluetoothAdapter.STATE_ON) { + aapsLogger.info(LTag.BGSOURCE, "Bluetooth turned back on — forcing Eversense reconnect") + ioScope.launch { + eversense.onBluetoothAvailable() + } + } + } + } + private val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) + private val json = Json { ignoreUnknownKeys = true } + + private val securePrefs: EversenseStore get() = eversense.preferences + + private fun cloudUploadEnabled() = preferences.get(EversenseBooleanKey.EversenseCloudUploadEnabled) + + private val lastNotifiedFirmwareVersion: String get() = securePrefs.getString("last_notified_firmware_version", "") ?: "" + private fun setLastNotifiedFirmwareVersion(version: String) = securePrefs.edit(commit = true) { putString("last_notified_firmware_version", version) } + private fun isSensorExpiryDismissed(insertionDate: Long, days: Int): Boolean = + securePrefs.getBoolean("eversense_expiry_dismissed_${insertionDate}_${days}", false) + private fun setSensorExpiryDismissed(insertionDate: Long, days: Int) = + securePrefs.edit(commit = true) { putBoolean("eversense_expiry_dismissed_${insertionDate}_${days}", true) } + private fun isCalibrationDueDismissed(nextCalibrationDate: Long): Boolean = + securePrefs.getBoolean("eversense_cal_due_dismissed_${nextCalibrationDate}", false) + private fun setCalibrationDueDismissed(nextCalibrationDate: Long) = + securePrefs.edit(commit = true) { putBoolean("eversense_cal_due_dismissed_${nextCalibrationDate}", true) } + private fun isBatteryLowDismissed(): Boolean = + securePrefs.getBoolean("eversense_battery_low_dismissed", false) + private fun setBatteryLowDismissed() = + securePrefs.edit(commit = true) { putBoolean("eversense_battery_low_dismissed", true) } + private var consecutiveNoSignalReadings: Int = 0 + private val NO_SIGNAL_WARNING_THRESHOLD = 3 + private val CALIBRATION_RECONNECT_TIMEOUT_MS = 30_000L + + @Volatile private var placementNotificationSnoozed: Boolean = false + + override suspend fun onStart() { + super.onStart() + ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + EversenseLogger.setDiagnosticLogging(preferences.get(EversenseBooleanKey.EversenseDiagnosticLogging)) + preferences.observe(EversenseBooleanKey.EversenseDiagnosticLogging) + .onEach { EversenseLogger.setDiagnosticLogging(it) } + .launchIn(ioScope) + eversense.addWatcher(this) + context.registerReceiver(bluetoothStateReceiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)) + if (!hasBluetoothPermissions()) { + aapsLogger.warn(LTag.BGSOURCE, "Bluetooth permissions not granted — requesting permissions") + requestBluetoothPermissions() + } + // Always sync credentials on startup — eversense.is365() is false until first connect + // so we must set username/password unconditionally for new phone first-boot + checkCredentialsNotification() + eversense.start() + combine( + preferences.observe(EversenseStringKey.EversenseUsername), + preferences.observe(EversenseStringKey.EversensePassword), + preferences.observe(EversenseBooleanKey.EversenseEuropeanRegion) + ) { user, password, region -> Triple(user, password, region) } + .onEach { checkCredentialsNotification() } + .launchIn(ioScope) + } + + override suspend fun onStop() { + super.onStop() + ioScope.cancel() + mainHandler.removeCallbacksAndMessages(null) + eversense.removeWatcher(this) + eversense.stop() + EversenseLogger.setDiagnosticLogging(false) + try { + context.unregisterReceiver(bluetoothStateReceiver) + } catch (e: IllegalArgumentException) { + // Not registered (e.g. onStart never completed registration) — safe to ignore + } + } + + private fun requestBluetoothPermissions() { + val intent = Intent(context, app.aaps.plugins.source.activities.RequestEversensePermissionActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } + + private fun hasBluetoothPermissions(): Boolean { + return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { + ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED && + ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED + } else { + ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED + } + } + + fun syncCredentialsIfNeeded() = checkCredentialsNotification() + + // ── EversenseCalibrationSource ── isEnabled() is inherited from PluginBase (true when + // Eversense is the currently active BG source), matching the XDripSource/DexcomBoyda pattern. + + override fun isConnected(): Boolean = eversense.isConnected() + + override suspend fun calibrate(bgMgDl: Int): Boolean = withContext(Dispatchers.IO) { + if (!eversense.isConnected()) { + aapsLogger.info(LTag.BGSOURCE, "Eversense calibration: not connected — reconnecting first") + val reconnected = withTimeoutOrNull(CALIBRATION_RECONNECT_TIMEOUT_MS) { awaitTransmitterReady() } + if (reconnected == null) { + aapsLogger.warn(LTag.BGSOURCE, "Eversense calibration: reconnect timed out") + return@withContext false + } + } + val success = eversense.sendCalibration(bgMgDl) + aapsLogger.info(LTag.BGSOURCE, "Eversense calibration result: $success") + if (success) { + eversense.triggerFullSync(force = true) + // Drives the home-screen "Calibration in progress" countdown banner. + preferences.put(LongNonKey.EversenseLastCalibrationSubmittedAt, System.currentTimeMillis()) + } + success + } + + // Bridges EversenseWatcher's callback-based "connected" signal into a single-shot coroutine + // wait, cancelled (and its watcher cleaned up) automatically by the caller's withTimeoutOrNull. + private suspend fun awaitTransmitterReady(): Boolean = suspendCancellableCoroutine { cont -> + lateinit var watcher: EversenseWatcher + watcher = object : EversenseWatcher { + override fun onTransmitterReady() { + if (cont.isActive) { + eversense.removeWatcher(watcher) + cont.resume(true) + } + } + override fun onConnectionChanged(connected: Boolean) {} + override fun onStateChanged(state: EversenseState) {} + override fun onCGMRead(type: EversenseType, readings: List) {} + override fun onAlarmReceived(alarm: ActiveAlarm) {} + override fun onTransmitterNotPlaced() {} + } + eversense.addWatcher(watcher) + cont.invokeOnCancellation { eversense.removeWatcher(watcher) } + eversense.connect(null) + } + + @Synchronized + private fun checkCredentialsNotification() { + val username = preferences.get(EversenseStringKey.EversenseUsername) + val password = preferences.get(EversenseStringKey.EversensePassword) + if (username.isEmpty() || password.isEmpty()) { + eversense.clearCredentials() + notificationManager.post( + NotificationId.EVERSENSE_CREDENTIALS, + rh.gs(R.string.eversense_credentials_missing), + level = NotificationLevel.URGENT + ) + } else { + eversense.setCredentials(username, password, preferences.get(EversenseBooleanKey.EversenseEuropeanRegion)) + notificationManager.dismiss(NotificationId.EVERSENSE_CREDENTIALS) + } + } + + private fun triggerManualCloudUpload() { + if (!cloudUploadEnabled()) { + notificationManager.post(NotificationId.EVERSENSE_CREDENTIALS, rh.gs(R.string.eversense_cloud_upload_enabled) + " is disabled", level = NotificationLevel.URGENT) + return + } + ioScope.launch { + if (!eversense.hasInternet()) { + notificationManager.post(NotificationId.EVERSENSE_CREDENTIALS, rh.gs(R.string.eversense_cloud_upload_failed), level = NotificationLevel.URGENT) + return@launch + } + // Flush all pending readings accumulated in the queue since the last successful upload + cloudUploader.flush(force = true) + + notificationManager.post( + NotificationId.EVERSENSE_CREDENTIALS, + "Upload eDMS avviato per le letture in sospeso", + level = NotificationLevel.INFO + ) + } + } + + override fun getPreferenceScreenContent() = PreferenceSubScreenDef( + key = "eversense_settings", + title = TextRef.AndroidRes(R.string.source_eversense), + items = listOf( + EversenseIntentKey.EversenseStatus.withClick { openActivity(EversenseStatusActivity::class.java) }, + EversenseBooleanKey.EversenseCloudUploadEnabled, + EversenseIntentKey.EversenseForceCloudUpload.withClick { triggerManualCloudUpload() }, + EversenseBooleanKey.EversenseDiagnosticLogging, + PreferenceSubScreenDef( + key = "eversense_credentials_screen", + title = TextRef.AndroidRes(R.string.eversense_credentials_title), + items = listOf( + EversenseStringKey.EversenseUsername, + EversenseStringKey.EversensePassword, + EversenseBooleanKey.EversenseEuropeanRegion, + EversenseIntentKey.EversenseSignOut.withClick { + synchronized(this) { + preferences.put(EversenseStringKey.EversenseUsername, "") + preferences.put(EversenseStringKey.EversensePassword, "") + eversense.clearCredentials() + } + } + ) + ), + EversenseIntentKey.EversenseDocumentation.withClick { + val intent = Intent( + Intent.ACTION_VIEW, + "https://github.com/BernhardRo/AndroidAPS/blob/master/plugins/eversense/README.md".toUri() + ) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + }, + EversenseIntentKey.EversenseCalibration.withClick { openActivity(EversenseCalibrationActivity::class.java) }, + EversenseIntentKey.EversensePlacement.withClick { openActivity(EversensePlacementActivity::class.java) } + ), + icon = pluginDescription.icon + ) + + private fun openActivity(activity: Class<*>) { + context.startActivity(Intent(context, activity).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + + private fun signalToLabel(strength: Int): String = when { + strength >= 75 -> rh.gs(R.string.eversense_signal_excellent) + strength >= 48 -> rh.gs(R.string.eversense_signal_good) + strength >= 30 -> rh.gs(R.string.eversense_signal_fair) + strength >= 25 -> rh.gs(R.string.eversense_signal_weak) + strength > 0 -> rh.gs(R.string.eversense_signal_poor) + else -> rh.gs(R.string.eversense_not_connected) + } + + override fun onStateChanged(state: EversenseState) { + EversenseLogger.diagnostic { aapsLogger.info(LTag.BGSOURCE, "New state received: ${Json.encodeToString(state)}") } + + // Update sensor battery level for Overview status lights + sensorBatteryLevel = if (state.batteryPercentage >= 0) state.batteryPercentage else -1 + + // Keep SENSOR_CHANGE therapy event in sync with transmitter insertion date. + // Disabled for E3: the forced overwrite every BT cycle injected raw transmitter + // uptime (subject to deep-sleep pauses), causing the home screen timer to drift. + // E365 is unaffected and retains the original sync behavior. + if (state.insertionDate > 0 && eversense.is365()) { + ioScope.launch { + persistenceLayer.insertCgmSourceData(Sources.Eversense, emptyList(), emptyList(), state.insertionDate) + EversenseLogger.diagnostic { aapsLogger.info(LTag.BGSOURCE, "Updated SENSOR_CHANGE event to insertionDate: ${state.insertionDate}") } + } + } + + // Sync SAGE color thresholds to match Eversense sensor lifetime and notification days + if (state.insertionDate > 0) { + val lifetimeDays = if (eversense.is365()) 365 else 180 + val warnHours = (lifetimeDays - 30) * 24 // orange when 30 days remaining + val urgentHours = (lifetimeDays - 10) * 24 // red when 10 days remaining + preferences.put(IntKey.OverviewSageWarning, warnHours) + preferences.put(IntKey.OverviewSageCritical, urgentHours) + } + + // Check for persistent no-signal — indicates transmitter not placed over sensor + if (state.sensorSignalStrength == 0) { + consecutiveNoSignalReadings++ + aapsLogger.warn(LTag.BGSOURCE, "No signal reading $consecutiveNoSignalReadings of $NO_SIGNAL_WARNING_THRESHOLD") + if (consecutiveNoSignalReadings >= NO_SIGNAL_WARNING_THRESHOLD) { + if (!placementNotificationSnoozed) { + onTransmitterNotPlaced() + } + consecutiveNoSignalReadings = 0 + } + } else { + consecutiveNoSignalReadings = 0 + placementNotificationSnoozed = false + notificationManager.dismiss(NotificationId.EVERSENSE_PLACEMENT) + } + + // Show sensor expiry notifications at 60, 30, and 10 days remaining — once each, at noon, keyed to insertionDate + if (state.insertionDate > 0) { + val sensorLifetimeMs = if (eversense.is365()) 365L * 24 * 60 * 60 * 1000 else 180L * 24 * 60 * 60 * 1000 + val expiryMs = state.insertionDate + sensorLifetimeMs + val daysRemaining = ((expiryMs - System.currentTimeMillis()) / (24 * 60 * 60 * 1000)).toInt() + val isAfterNoon = java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY) >= 12 + + if (isAfterNoon && daysRemaining in 31..60 && !isSensorExpiryDismissed(state.insertionDate, 60)) { + setSensorExpiryDismissed(state.insertionDate, 60) + notificationManager.post( + NotificationId.EVERSENSE_ALARM, + rh.gs(R.string.eversense_sensor_expiry_plan, daysRemaining), + level = NotificationLevel.INFO + ) + } else if (isAfterNoon && daysRemaining in 11..30 && !isSensorExpiryDismissed(state.insertionDate, 30)) { + setSensorExpiryDismissed(state.insertionDate, 30) + notificationManager.post( + NotificationId.EVERSENSE_ALARM, + rh.gs(R.string.eversense_sensor_expiry_soon, daysRemaining), + level = NotificationLevel.NORMAL + ) + } else if (isAfterNoon && daysRemaining in 1..10 && !isSensorExpiryDismissed(state.insertionDate, daysRemaining)) { + setSensorExpiryDismissed(state.insertionDate, daysRemaining) + notificationManager.post( + NotificationId.EVERSENSE_ALARM, + rh.gs(R.string.eversense_sensor_expiry_urgent, daysRemaining), + level = NotificationLevel.URGENT + ) + } + } + + // Battery low notification — fires once at noon when battery < 11% + val isAfterNoonBattery = java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY) >= 12 + if (isAfterNoonBattery && state.batteryPercentage in 1..10 && !isBatteryLowDismissed()) { + setBatteryLowDismissed() + notificationManager.post( + NotificationId.EVERSENSE_ALARM, + rh.gs(R.string.eversense_battery_low, state.batteryPercentage), + level = NotificationLevel.NORMAL + ) + } + + // Calibration due notification — fires once per calibration day + // Round to day boundary so clock drift doesn't cause duplicate notifications + val calDueDay = (state.nextCalibrationDate / 86400000L) * 86400000L + if (state.nextCalibrationDate > 0 + && System.currentTimeMillis() >= state.nextCalibrationDate + && !isCalibrationDueDismissed(calDueDay)) { + setCalibrationDueDismissed(calDueDay) + notificationManager.post( + NotificationId.EVERSENSE_ALARM, + rh.gs(R.string.eversense_calibration_due), + level = NotificationLevel.NORMAL + ) + } + + // Show firmware notification only once per unique firmware version + if (state.firmwareVersion.isNotEmpty() && state.firmwareVersion != lastNotifiedFirmwareVersion) { + setLastNotifiedFirmwareVersion(state.firmwareVersion) + aapsLogger.info(LTag.BGSOURCE, "Transmitter firmware: ${state.firmwareVersion}") + notificationManager.post( + NotificationId.EVERSENSE_FIRMWARE, + rh.gs(R.string.eversense_firmware_update, state.firmwareVersion), + level = NotificationLevel.INFO + ) + } + } + + override fun onTransmitterNotPlaced() { + aapsLogger.warn(LTag.BGSOURCE, "Transmitter not placed — firing placement warning notification") + mainHandler.post { + notificationManager.post( + NotificationId.EVERSENSE_PLACEMENT, + rh.gs(R.string.eversense_transmitter_not_placed), + level = NotificationLevel.URGENT + ) + } + } + + override fun onConnectionChanged(connected: Boolean) { + aapsLogger.info(LTag.BGSOURCE, "Connection changed — connected: $connected") + } + + override fun onTransmitterReady() { + aapsLogger.info(LTag.BGSOURCE, "Transmitter ready — triggering fullSync") + // A fresh connection counts as liveness even before the first reading arrives. + eversense.submitToExecutorAndSync(force = true) + } + + + override fun onAlarmReceived(alarm: ActiveAlarm) { + aapsLogger.info(LTag.BGSOURCE, "Eversense alarm received: ${alarm.code.title}") + // CRITICAL_FAULT (code 0) is sent for both hardware faults and calibration-overdue events. + // If the stored next calibration date has already passed, treat it as a calibration alarm. + val title = if (alarm.code == EversenseAlarm.CRITICAL_FAULT) { + val stateJson = securePrefs.getString(StorageKeys.STATE, null) + val state = stateJson?.let { json.decodeFromString(it) } + if (state != null && state.nextCalibrationDate > 0 && state.nextCalibrationDate < System.currentTimeMillis()) { + rh.gs(R.string.eversense_calibration_due_now) + } else { + alarm.code.title + } + } else { + alarm.code.title + } + // The transmitter pushes an alarm code with no EversenseAlarm mapping (-> UNKNOWN) within + // ~1-2s of us exiting diagnostic/positioning mode (confirmed from device logs: signal/ + // battery/calibration all healthy at the time - this is a mode-transition status push, not + // a real fault). Only suppress within that narrow window, so a genuinely unrecognized alarm + // arriving at any other time still surfaces as "Unknown Error" rather than being silently + // dropped. + val isSpuriousPostExitUnknown = alarm.code == EversenseAlarm.UNKNOWN && + System.currentTimeMillis() - eversense.lastPositioningModeExitAt <= POST_EXIT_UNKNOWN_ALARM_SUPPRESS_WINDOW_MS + if (isSpuriousPostExitUnknown) { + aapsLogger.info(LTag.BGSOURCE, "Suppressing unrecognized alarm (code ${alarm.codeRaw}) received shortly after exiting positioning mode") + return + } + val level = when { + alarm.code.isWarning -> NotificationLevel.NORMAL + alarm.code.isInfo -> NotificationLevel.INFO + else -> NotificationLevel.URGENT + } + mainHandler.post { + notificationManager.post( + NotificationId.EVERSENSE_ALARM, + title, + level = level + ) + } + } + + override fun onCGMRead(type: EversenseType, readings: List) { + // The transmitter is alive — reset the liveness watchdog. + // Log what the BLE layer actually produced, per reading, before anything downstream can + // filter or reshape it. The DMS uploader drops readings with no rawResponseHex and keys + // the portal record on sensorId, and neither field is visible anywhere else in an exported + // log - the Eversense packet classes log through EversenseLogger, which only reaches + // logcat. Without this, a reading that never makes it to the portal cannot be told apart + // from one the server discarded. + // + // Backfill readings are the ones to watch: GlucoseHistoryItem carries no sensorId at all, + // so anything reconstructed from the transmitter's log arrives here with sensorId empty. + EversenseLogger.diagnostic { + readings.forEach { r -> + aapsLogger.info( + LTag.BGSOURCE, + "Eversense CGM read: ts=${r.datetime} glucose=${r.glucoseInMgDl} " + + "rawHexBytes=${r.rawResponseHex.length / 2} sensorId=${if (r.sensorId.isEmpty()) "EMPTY" else r.sensorId}" + ) + } + } + val glucoseValues = readings.map { reading -> + GV( + timestamp = reading.datetime, + value = reading.glucoseInMgDl.toDouble(), + noise = null, + raw = null, + trendArrow = TrendArrow.fromString(reading.trend.type), + sourceSensor = when (type) { + EversenseType.EVERSENSE_365 -> SourceSensor.EVERSENSE_365 + EversenseType.EVERSENSE_E3 -> SourceSensor.EVERSENSE_E3 + } + ) + } + + ioScope.launch { + val state = eversense.getCurrentState() + val insertionDate = state.insertionDate.takeIf { it > 0 } + val result = persistenceLayer.insertCgmSourceData( + Sources.Eversense, + glucoseValues, + listOf(), + insertionDate + ) + EversenseLogger.diagnostic { aapsLogger.info(LTag.BGSOURCE, "CGM insert complete — inserted: ${result.inserted}, updated: ${result.updated}") } + + if (cloudUploadEnabled()) { + try { + cloudUploader.enqueue(type, readings, state) + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + logCloudError("Eversense cloud queue failed; local readings are stored", e) + } + } + } + } + + private val cloudUploader by lazy { + app.aaps.plugins.source.eversense.EversenseCloudUploader( + scope = { ioScope }, + store = { eversense.cloudStore() }, + enabled = ::cloudUploadEnabled, + online = { eversense.hasInternet() }, + now = System::currentTimeMillis, + elapsed = android.os.SystemClock::elapsedRealtime, + upload = ::uploadCloudBatch, + onError = { logCloudError("Eversense cloud upload failed; local readings are stored", it) } + ) + } + + private fun logCloudError(message: String, error: Exception) { + aapsLogger.error(LTag.BGSOURCE, "$message (${error.javaClass.simpleName})") + EversenseLogger.diagnostic { aapsLogger.error(LTag.BGSOURCE, message, error) } + } + + private suspend fun uploadCloudBatch(prefs: EversenseStore, batch: app.aaps.plugins.source.eversense.EversenseCloudUploader.PendingUpload): Boolean { + val state = batch.state + val rawReadings = batch.readings + if (rawReadings.isEmpty()) return true + + val liveState = eversense.getCurrentState() + val activeSensorId = liveState.sensorId.ifEmpty { state.sensorId } + val readings = rawReadings.map { r -> + if (r.sensorId.isEmpty() && activeSensorId.isNotEmpty()) r.copy(sensorId = activeSensorId) else r + } + + val latest = readings.maxByOrNull { it.datetime } ?: return true + val rawCalibrations = liveState.calibrationHistory.ifEmpty { state.calibrationHistory } + val calibrations = rawCalibrations.sortedBy { it.datetime } + .fold(mutableListOf()) { acc, item -> + if (acc.isEmpty() || (item.datetime - acc.last().datetime) >= 20 * 60_000L) { + acc.add(item) + } + acc + } + + return if (batch.type == EversenseType.EVERSENSE_365) { + val glucose = app.aaps.plugins.eversense.util.EversenseHttp365Util.uploadGlucoseReadings( + prefs, readings, state.transmitterName.ifEmpty { state.transmitterSerialNumber }, state.firmwareVersion) + aapsLogger.info(LTag.BGSOURCE, "Eversense batch upload (365 essential logs): success=${glucose.success} sent=${glucose.sentCount} status=${glucose.httpStatus}") + EversenseLogger.diagnostic { aapsLogger.info(LTag.BGSOURCE, "Eversense batch upload details: ${glucose.describe()}") } + + val portal = app.aaps.plugins.eversense.util.EversenseHttp365Util.putCurrentValues( + prefs, latest.glucoseInMgDl, latest.datetime, latest.trend, state.sensorSignalStrength, state.batteryPercentage) + if (!portal.success) return false + + val txId = state.transmitterName.ifEmpty { state.transmitterSerialNumber } + val dmsReadings = readings.map { r -> + if (r.sensorId.length >= 16) { + val rev = r.sensorId.chunked(2).take(8).reversed().joinToString("").uppercase() + r.copy(sensorId = rev) + } else r + } + val deviceEvents = app.aaps.plugins.eversense.util.EversenseHttp365Util.putDeviceEvents( + prefs, dmsReadings, txId, calibrations, state.activeAlarms) + aapsLogger.info(LTag.BGSOURCE, "Eversense batch upload (365 device events): success=${deviceEvents.success} sent=${deviceEvents.sentCount} status=${deviceEvents.httpStatus}") + + deviceEvents.success && (glucose.success || (glucose.httpStatus ?: 0) < 400) + } else { + val txId = state.transmitterName.ifEmpty { state.transmitterSerialNumber } + val portal = app.aaps.plugins.eversense.util.EversenseHttpE3Util.putCurrentValues( + prefs, latest.glucoseInMgDl, latest.datetime, latest.trend, state.sensorSignalStrength, state.batteryPercentage) + if (!portal) return false + + val dmsReadings = readings.map { r -> + if (r.sensorId.length >= 16) { + val rev = r.sensorId.chunked(2).take(8).reversed().joinToString("").uppercase() + r.copy(sensorId = rev) + } else r + } + val deviceEvents = app.aaps.plugins.eversense.util.EversenseHttpE3Util.putDeviceEvents( + prefs, dmsReadings, txId, calibrations, state.activeAlarms) + aapsLogger.info(LTag.BGSOURCE, "Eversense batch upload (E3 device events): success=$deviceEvents") + deviceEvents + } + } +} \ No newline at end of file diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/NotificationReaderPlugin.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/NotificationReaderPlugin.kt index 5532ceaaf719..a9d64d21af4c 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/NotificationReaderPlugin.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/NotificationReaderPlugin.kt @@ -74,14 +74,20 @@ class NotificationReaderPlugin( private fun loadPackageConfig(): PackageConfig { return try { val stored = preferences.get(StringNonKey.NotificationReaderPackages) - val json = if (stored.isNotEmpty()) { - stored + val storedConfig = stored.takeIf { it.isNotEmpty() }?.let { PackageConfig.fromJson(it) } + val asset = try { + context.assets.open(PACKAGE_CONFIG_ASSET).bufferedReader().use { it.readText() } + } catch (e: Exception) { + if (storedConfig != null) return storedConfig + throw e + } + val assetConfig = PackageConfig.fromJson(asset) + if (storedConfig != null && storedConfig.version >= assetConfig.version) { + storedConfig } else { - val asset = context.assets.open(PACKAGE_CONFIG_ASSET).bufferedReader().use { it.readText() } preferences.put(StringNonKey.NotificationReaderPackages, asset) - asset + assetConfig } - PackageConfig.fromJson(json) } catch (e: Exception) { aapsLogger.error(LTag.BGSOURCE, "Failed to load package config", e) PackageConfig(0, emptySet(), emptyMap(), emptyMap()) diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseCalibrationActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseCalibrationActivity.kt new file mode 100644 index 000000000000..e95bd35013c6 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseCalibrationActivity.kt @@ -0,0 +1,167 @@ +package app.aaps.plugins.source.activities + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.Button +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import app.aaps.ui.compose.eversenseCalibrationDialog.EversenseCalibrationDynamics +import app.aaps.ui.compose.eversenseCalibrationDialog.EversenseCalibrationDynamicsWarning +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.widget.Toast +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.keys.LongNonKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.plugins.source.R +import app.aaps.plugins.eversense.EversenseCGMPlugin +import app.aaps.plugins.eversense.callbacks.EversenseWatcher +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.eversense.util.EversenseLogger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch +import dev.zacsweers.metro.Inject + +class EversenseCalibrationActivity : MetroAppCompatActivity() { + + @Inject lateinit var profileUtil: ProfileUtil + @Inject lateinit var eversenseCGM: EversenseCGMPlugin + @Inject lateinit var preferences: Preferences + @Inject lateinit var dynamics: EversenseCalibrationDynamics + + private var submitting by mutableStateOf(false) + + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + companion object { + private const val TAG = "EversenseCalibration" + private const val RECONNECT_TIMEOUT_MS = 30000L + } + + private val mainHandler = Handler(Looper.getMainLooper()) + private var connectionWatcher: EversenseWatcher? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setEversenseContent(R.string.eversense_calibration_action, preferences) { + var input by rememberSaveable { mutableStateOf("") } + EversenseCalibrationDynamicsWarning(dynamics) + EversenseCard { + OutlinedTextField( + value = input, onValueChange = { input = it }, + label = { Text(stringResource(R.string.eversense_calibration_bg_value)) }, + suffix = { Text(profileUtil.units.displayLabel) }, + enabled = !submitting, singleLine = true, modifier = Modifier.fillMaxWidth(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal, imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { submitCalibration(input) }) + ) + Button(onClick = { submitCalibration(input) }, enabled = !submitting, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.eversense_calibration_submit)) + } + } + } + } + + private fun submitCalibration(rawInput: String) { + if (submitting) return + val bgValue = rawInput.toDoubleOrNull() + if (bgValue == null || !bgValue.isFinite() || bgValue <= 0) { + Toast.makeText(this, getString(R.string.eversense_calibration_invalid_value), Toast.LENGTH_SHORT).show() + return + } + val bgMgDl = profileUtil.convertToMgdl(bgValue, profileUtil.units).toInt() + submitting = true + if (eversenseCGM.isConnected()) sendCalibration(bgMgDl) + else reconnectThenCalibrate(bgMgDl) + } + + private fun reconnectThenCalibrate(bgMgDl: Int) { + var reconnected = false + + val watcher = object : EversenseWatcher { + override fun onTransmitterReady() { + if (!reconnected) { + reconnected = true + EversenseLogger.info(TAG, "Transmitter ready — proceeding with calibration") + sendCalibration(bgMgDl) + } + } + override fun onConnectionChanged(connected: Boolean) {} + override fun onStateChanged(state: EversenseState) {} + override fun onCGMRead(type: EversenseType, readings: List) {} + override fun onAlarmReceived(alarm: ActiveAlarm) {} + override fun onTransmitterNotPlaced() {} + } + + connectionWatcher = watcher + eversenseCGM.addWatcher(watcher) + eversenseCGM.connect(null) + + mainHandler.postDelayed({ + if (!reconnected) { + EversenseLogger.warning(TAG, "Reconnect timed out — calibration aborted") + eversenseCGM.removeWatcher(watcher) + connectionWatcher = null + mainHandler.post { + submitting = false + Toast.makeText(this, getString(R.string.eversense_calibration_failed), Toast.LENGTH_LONG).show() + } + } + }, RECONNECT_TIMEOUT_MS) + } + + private fun sendCalibration(bgMgDl: Int) { + ioScope.launch { + connectionWatcher?.let { + eversenseCGM.removeWatcher(it) + connectionWatcher = null + } + EversenseLogger.info(TAG, "Calibration coroutine started — sending $bgMgDl mg/dL to transmitter") + val success = eversenseCGM.sendCalibration(bgMgDl) + EversenseLogger.info(TAG, "Calibration result — success: $success") + if (success) { + EversenseLogger.info(TAG, "Triggering fullSync after successful calibration") + eversenseCGM.triggerFullSync(force = true) + // Drives the home-screen "Calibration in progress" countdown banner. + preferences.put(LongNonKey.EversenseLastCalibrationSubmittedAt, System.currentTimeMillis()) + } + runOnUiThread { + if (success) { + Toast.makeText(this@EversenseCalibrationActivity, getString(R.string.eversense_calibration_success), Toast.LENGTH_SHORT).show() + finish() + } else { + submitting = false + Toast.makeText(this@EversenseCalibrationActivity, getString(R.string.eversense_calibration_failed), Toast.LENGTH_LONG).show() + } + } + } + } + + override fun onDestroy() { + super.onDestroy() + ioScope.cancel() + mainHandler.removeCallbacksAndMessages(null) + connectionWatcher?.let { + eversenseCGM.removeWatcher(it) + connectionWatcher = null + } + } + +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversensePlacementActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversensePlacementActivity.kt new file mode 100644 index 000000000000..148ded142df6 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversensePlacementActivity.kt @@ -0,0 +1,146 @@ +package app.aaps.plugins.source.activities + +import app.aaps.core.keys.interfaces.Preferences +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.plugins.source.R +import app.aaps.plugins.eversense.EversenseCGMPlugin +import app.aaps.plugins.eversense.callbacks.EversenseWatcher +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runInterruptible +import app.aaps.plugins.source.eversense.PositioningSession +import java.text.DateFormat +import java.util.Date +import dev.zacsweers.metro.Inject + +class EversensePlacementActivity : MetroAppCompatActivity(), EversenseWatcher { + + @Inject lateinit var preferences: Preferences + @Inject lateinit var eversense: EversenseCGMPlugin + + private val mainHandler = Handler(Looper.getMainLooper()) + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + private var signalLabel by mutableStateOf("") + private var signalValue by mutableStateOf("") + private var instructionText by mutableStateOf("") + private var lastUpdateText by mutableStateOf("") + private var signalBars by mutableIntStateOf(0) + + private val timeFormatter: DateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM) + + private var resumed = false + private val positioning by lazy { + PositioningSession(ioScope, + enter = { runInterruptible { eversense.enterPositioningMode() } }, + read = { runInterruptible { if (eversense.isConnected()) eversense.readSignalStrength() } }, + exit = { runInterruptible { eversense.exitPositioningMode() } } + ) + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setEversenseContent(R.string.eversense_placement_title, preferences) { + EversensePlacementContent(signalLabel, signalValue, instructionText, lastUpdateText, signalBars) + } + + val state = eversense.getCurrentState() + if (state.sensorSignalStrength > 0) { + updateSignalUI(state.sensorSignalStrength) + } else if (!eversense.isConnected()) { + showNotConnected() + } else { + showWaiting() + } + } + + override fun onResume() { + super.onResume() + resumed = true + eversense.addWatcher(this) + positioning.resume() + } + + override fun onPause() { + resumed = false + positioning.pause() + eversense.removeWatcher(this) + mainHandler.removeCallbacksAndMessages(null) + super.onPause() + } + + override fun onDestroy() { + super.onDestroy() + ioScope.cancel() + eversense.removeWatcher(this) + } + + override fun onStateChanged(state: EversenseState) { + mainHandler.post { + if (!resumed) return@post + if (state.sensorSignalStrength > 0) { + updateSignalUI(state.sensorSignalStrength) + lastUpdateText = getString(R.string.eversense_placement_last_update, timeFormatter.format(Date())) + } else { + showWaiting() + } + } + } + + override fun onConnectionChanged(connected: Boolean) { + mainHandler.post { if (resumed && !connected) showNotConnected() } + } + + override fun onCGMRead(type: EversenseType, readings: List) {} + + private fun updateSignalUI(strength: Int) { + signalBars = strengthToBars(strength) + val (label, instruction) = when { + strength >= 75 -> Pair(getString(R.string.eversense_signal_excellent), getString(R.string.eversense_placement_instruction_excellent)) + strength >= 48 -> Pair(getString(R.string.eversense_signal_good), getString(R.string.eversense_placement_instruction_good)) + strength >= 30 -> Pair(getString(R.string.eversense_signal_fair), getString(R.string.eversense_placement_instruction_fair)) + strength >= 28 -> Pair(getString(R.string.eversense_signal_weak), getString(R.string.eversense_placement_instruction_weak)) + strength >= 25 -> Pair(getString(R.string.eversense_signal_poor), getString(R.string.eversense_placement_instruction_poor)) + else -> Pair(getString(R.string.eversense_not_connected), getString(R.string.eversense_placement_instruction_not_connected)) + } + signalLabel = label + signalValue = "$strength%" + instructionText = instruction + } + + private fun showNotConnected() { + signalBars = 0 + signalLabel = getString(R.string.eversense_not_connected) + signalValue = "" + lastUpdateText = "" + instructionText = getString(R.string.eversense_placement_instruction_not_connected) + } + + private fun showWaiting() { + signalBars = 0 + signalLabel = getString(R.string.eversense_placement_reading) + signalValue = "" + instructionText = "" + } + + private fun strengthToBars(strength: Int): Int = when { + strength >= 75 -> 5 + strength >= 48 -> 4 + strength >= 30 -> 3 + strength >= 28 -> 2 + strength >= 25 -> 1 + else -> 0 + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseScreens.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseScreens.kt new file mode 100644 index 000000000000..9c87a6b96be6 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseScreens.kt @@ -0,0 +1,133 @@ +package app.aaps.plugins.source.activities + +import androidx.activity.compose.setContent +import androidx.annotation.StringRes +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.AapsTheme +import app.aaps.core.ui.compose.AapsTopAppBar +import app.aaps.core.ui.compose.LocalPreferences +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.plugins.source.R +import app.aaps.core.ui.R as CoreR + +/** The same theme, app bar and surface colors used by the AAPS settings. */ +internal fun MetroAppCompatActivity.setEversenseContent( + @StringRes title: Int, + preferences: Preferences, + content: @Composable () -> Unit +) { + setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + EversensePage(title, { finish() }, content) + } + } + } +} + +@Composable +internal fun EversensePage(@StringRes title: Int, onBack: () -> Unit, content: @Composable () -> Unit) { + Scaffold( + containerColor = MaterialTheme.colorScheme.background, + topBar = { + AapsTopAppBar( + title = { Text(stringResource(title)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(CoreR.string.back)) + } + } + ) + } + ) { padding -> + Column(Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()).padding(AapsSpacing.extraLarge), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium)) { content() } + } +} + +@Composable +internal fun EversenseCard(content: @Composable ColumnScope.() -> Unit) { + Card(Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer)) { + Column(Modifier.padding(AapsSpacing.extraLarge), verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), content = content) + } +} + +@Composable +internal fun EversenseStatusContent( + labels: List, connected: Boolean, syncDays: Int, + onConnect: () -> Unit, onChange: () -> Unit, onSync: () -> Unit, onDays: (Int) -> Unit +) { + EversenseCard { labels.forEach { Text(it, style = MaterialTheme.typography.bodyLarge) } } + Button(onConnect, Modifier.fillMaxWidth()) { + Text(stringResource(if (connected) R.string.eversense_status_disconnect else R.string.eversense_status_connect)) + } + OutlinedButton(onChange, Modifier.fillMaxWidth()) { Text(stringResource(R.string.eversense_change_transmitter)) } + var expanded by remember { mutableStateOf(false) } + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { + Text(stringResource(R.string.eversense_default_sync_days_label), Modifier.weight(1f)) + Box { + OutlinedButton({ expanded = true }) { Text(syncDays.toString()) } + DropdownMenu(expanded, onDismissRequest = { expanded = false }) { + for (days in listOf(1, 3, 7, 14, 30)) { + DropdownMenuItem(text = { Text(days.toString()) }, onClick = { expanded = false; onDays(days) }) + } + } + } + } + Button(onSync, Modifier.fillMaxWidth(), enabled = connected) { Text(stringResource(R.string.eversense_information_last_sync)) } +} + +@Composable +internal fun EversensePlacementContent(label: String, value: String, instruction: String, lastUpdate: String, bars: Int) { + EversenseCard { + Text(stringResource(R.string.eversense_placement_guide_heading), style = MaterialTheme.typography.titleLarge) + Text(stringResource(R.string.eversense_placement_guide_subtitle), color = MaterialTheme.colorScheme.onSurfaceVariant) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium, Alignment.CenterHorizontally), verticalAlignment = Alignment.Bottom) { + repeat(5) { index -> + Box(Modifier.width(AapsSpacing.xxLarge).height(AapsSpacing.xxLarge * (index + 1)) + .background(if (index < bars) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceContainerHighest, + MaterialTheme.shapes.small)) + } + } + Text(label, style = MaterialTheme.typography.headlineSmall) + if (value.isNotEmpty()) Text(value) + if (lastUpdate.isNotEmpty()) Text(lastUpdate, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (instruction.isNotEmpty()) Text(instruction) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseStatusActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseStatusActivity.kt new file mode 100644 index 000000000000..98f9efaf4572 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/EversenseStatusActivity.kt @@ -0,0 +1,216 @@ +package app.aaps.plugins.source.activities + +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.plugins.eversense.EversenseCGMPlugin +import app.aaps.plugins.eversense.callbacks.EversenseScanCallback +import app.aaps.plugins.eversense.callbacks.EversenseWatcher +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.ActiveAlarm +import app.aaps.plugins.eversense.models.EversenseScanResult +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.source.R +import dev.zacsweers.metro.Inject +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch + +class EversenseStatusActivity : MetroAppCompatActivity(), EversenseWatcher { + @Inject lateinit var preferences: Preferences + @Inject lateinit var eversense: EversenseCGMPlugin + + private enum class Dialog { NONE, DISCONNECT, CHANGE, SCANNING, RESULTS } + private var dialog by mutableStateOf(Dialog.NONE) + private val foundDevices = mutableStateListOf() + private var labels by mutableStateOf(emptyList()) + private var connected by mutableStateOf(false) + private var syncDays by mutableIntStateOf(14) + private var scanSession: AutoCloseable? = null + private var scanGeneration = 0L + private var resumed = false + private val mainHandler = Handler(Looper.getMainLooper()) + private val ioScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + syncDays = eversense.preferences.getInt("eversense_sync_days", 14) + updateStatus() + setEversenseContent(R.string.eversense_status_title, preferences) { + EversenseStatusContent(labels, connected, syncDays, + onConnect = ::handleConnectTap, onChange = { dialog = Dialog.CHANGE }, + onSync = { if (eversense.isConnected()) { + ioScope.launch { eversense.triggerFullSync(force = true) } + mainHandler.postDelayed({ updateStatus() }, 5000) + } }, + onDays = { syncDays = it; eversense.preferences.edit().putInt("eversense_sync_days", it).apply() }) + DeviceDialog() + } + } + + override fun onResume() { + super.onResume() + resumed = true + eversense.addWatcher(this) + updateStatus() + } + + override fun onPause() { + resumed = false + dismissDialog() + mainHandler.removeCallbacksAndMessages(null) + eversense.removeWatcher(this) + super.onPause() + } + + override fun onConnectionChanged(connected: Boolean) { mainHandler.post { if (resumed) updateStatus() } } + override fun onStateChanged(state: EversenseState) { mainHandler.post { if (resumed) updateStatus() } } + + // isConnected() is connected && transmitterReady. onConnectionChanged(true) fires as soon as + // the raw BLE link comes up, before the auth handshake finishes - at that point isConnected() + // is still false, so updateStatus() draws the red X. transmitterReady only flips true later, + // once auth completes, and that transition notifies watchers via onTransmitterReady() instead + // of onConnectionChanged() again. Without refreshing here too, the screen never learns the + // handshake finished and is stuck showing the red X until it's reopened. + override fun onTransmitterReady() { mainHandler.post { if (resumed) updateStatus() } } + override fun onTransmitterNotPlaced() {} + override fun onAlarmReceived(alarm: ActiveAlarm) {} + override fun onCGMRead(type: EversenseType, readings: List) {} + + + private fun updateStatus() { + val state = eversense.getCurrentState() + val never = getString(R.string.eversense_status_never) + fun date(value: Long) = if (value > 0) dateFormatter.format(Date(value)) else never + connected = eversense.isConnected() + labels = listOf( + getString(R.string.eversense_status_connected_label, if (connected) "✅" else "❌"), + getString(R.string.eversense_status_battery_label, state.batteryPercentage), + getString(R.string.eversense_status_insertion_label, date(state.insertionDate)), + getString(R.string.eversense_status_last_sync_label, date(state.lastSync)), + getString(R.string.eversense_status_signal_label, signalToLabel(state.sensorSignalStrength)), + getString(R.string.eversense_status_phase_label, state.calibrationPhase.name), + getString(R.string.eversense_status_last_cal_label, date(state.lastCalibrationDate)), + getString(R.string.eversense_status_next_cal_label, date(state.nextCalibrationDate)) + ) + } + + private fun handleConnectTap() { + if (eversense.isConnected()) dialog = Dialog.DISCONNECT + else if (eversense.preferences.getString("eversense_remote_device", null) != null) { + ioScope.launch { eversense.forceReconnect() } + mainHandler.postDelayed({ updateStatus() }, 3000) + } else showDeviceSelectionDialog() + } + + private fun dismissDialog() { + scanGeneration++ + scanSession?.close() + scanSession = null + dialog = Dialog.NONE + } + + private fun showDeviceSelectionDialog() { + dismissDialog() + foundDevices.clear() + dialog = Dialog.SCANNING + val generation = scanGeneration + val lease = eversense.startScan(object : EversenseScanCallback { + override fun onResult(item: EversenseScanResult) { + mainHandler.post { + if (resumed && generation == scanGeneration && dialog == Dialog.SCANNING && item.name.matches(Regex("T\\d+.*")) && foundDevices.none { it.name == item.name }) + foundDevices.add(item) + } + } + }) + scanSession = lease + mainHandler.postDelayed({ + if (!resumed || dialog != Dialog.SCANNING || scanSession !== lease) return@postDelayed + lease.close() + scanSession = null + dialog = Dialog.RESULTS + }, 10000) + } + + @Composable + private fun DeviceDialog() { + val current = dialog + if (current == Dialog.NONE) return + val message = when (current) { + Dialog.DISCONNECT -> R.string.eversense_disconnect_confirm + Dialog.CHANGE -> R.string.eversense_change_transmitter_confirm + Dialog.SCANNING -> R.string.eversense_scan_in_progress + else -> R.string.eversense_no_transmitters_found + } + AlertDialog( + onDismissRequest = ::dismissDialog, + title = { Text(stringResource(if (current == Dialog.CHANGE) R.string.eversense_change_transmitter else R.string.eversense_scan_title)) }, + text = { + if (current == Dialog.RESULTS && foundDevices.isNotEmpty()) { + Column(Modifier.verticalScroll(rememberScrollState())) { + foundDevices.forEach { item -> + TextButton(onClick = { + dismissDialog() + ioScope.launch { eversense.connect(item.device) } + mainHandler.postDelayed({ updateStatus() }, 3000) + }) { Text(item.name) } + } + } + } else Text(stringResource(message)) + }, + confirmButton = { + when (current) { + Dialog.DISCONNECT -> TextButton(onClick = { + dismissDialog(); eversense.disconnect(); mainHandler.postDelayed({ updateStatus() }, 500) + }) { Text(stringResource(R.string.eversense_status_disconnect)) } + Dialog.CHANGE -> TextButton(onClick = { + dismissDialog(); eversense.clearStoredDevice(); updateStatus(); showDeviceSelectionDialog() + }) { Text(stringResource(R.string.eversense_change_transmitter)) } + Dialog.RESULTS -> if (foundDevices.isEmpty()) TextButton(onClick = ::dismissDialog) { Text(stringResource(android.R.string.ok)) } + else -> Unit + } + }, + dismissButton = { TextButton(onClick = ::dismissDialog) { Text(stringResource(R.string.eversense_scan_cancel)) } } + ) + } + + private fun signalToLabel(strength: Int): String = getString(when { + strength >= 75 -> R.string.eversense_signal_excellent + strength >= 48 -> R.string.eversense_signal_good + strength >= 30 -> R.string.eversense_signal_fair + strength >= 25 -> R.string.eversense_signal_weak + strength > 0 -> R.string.eversense_signal_poor + else -> R.string.eversense_not_connected + }) + + override fun onDestroy() { + mainHandler.removeCallbacksAndMessages(null) + scanSession?.close() + ioScope.cancel() + eversense.removeWatcher(this) + super.onDestroy() + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/RequestEversensePermissionActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/RequestEversensePermissionActivity.kt new file mode 100644 index 000000000000..cd9f748414f4 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/RequestEversensePermissionActivity.kt @@ -0,0 +1,40 @@ +package app.aaps.plugins.source.activities + +import android.Manifest +import android.os.Build +import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity + +class RequestEversensePermissionActivity : AppCompatActivity() { + + private val requestCode = "EversenseBLE".map { it.code }.sum() + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // BLUETOOTH_CONNECT and BLUETOOTH_SCAN are runtime permissions on Android 12+ (API 31+). + // On older versions BLUETOOTH is sufficient and is a normal (auto-granted) permission. + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + requestPermissions( + arrayOf( + Manifest.permission.BLUETOOTH_CONNECT, + Manifest.permission.BLUETOOTH_SCAN + ), + requestCode + ) + } else { + requestPermissions( + arrayOf(Manifest.permission.BLUETOOTH), + requestCode + ) + } + } + + override fun onRequestPermissionsResult( + requestCode: Int, + permissions: Array, + grantResults: IntArray + ) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + finish() + } +} \ No newline at end of file diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/EversenseBindings.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/EversenseBindings.kt new file mode 100644 index 000000000000..26d98c036fb5 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/EversenseBindings.kt @@ -0,0 +1,23 @@ +package app.aaps.plugins.source.di + +import android.bluetooth.BluetoothManager +import android.content.Context +import app.aaps.plugins.eversense.EversenseCGMPlugin +import app.aaps.plugins.source.eversense.EversenseStateStore +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides +import dev.zacsweers.metro.SingleIn + +@ContributesTo(AppScope::class) +@BindingContainer +object EversenseBindings { + @Provides + @SingleIn(AppScope::class) + fun provideEversense(context: Context, store: EversenseStateStore): EversenseCGMPlugin { + val appContext = context.applicationContext + val manager = appContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + return EversenseCGMPlugin(appContext, manager, store) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMetroGraph.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMetroGraph.kt index b1d545399e59..2934d6baf42e 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMetroGraph.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMetroGraph.kt @@ -1,5 +1,8 @@ package app.aaps.plugins.source.di +import app.aaps.plugins.source.activities.EversenseCalibrationActivity +import app.aaps.plugins.source.activities.EversenseStatusActivity +import app.aaps.plugins.source.activities.EversensePlacementActivity import androidx.work.ListenableWorker import app.aaps.core.objects.workflow.MetroWorkerCreator import app.aaps.core.objects.workflow.WorkerKey @@ -90,4 +93,13 @@ interface SourceMetroGraph { fun bindNotificationCollectorService( injector: MembersInjector ): MembersInjector<*> = injector + @Provides @IntoMap @ClassKey(EversenseCalibrationActivity::class) + fun bindEversenseCalibrationActivity(injector: MembersInjector): MembersInjector<*> = injector + + @Provides @IntoMap @ClassKey(EversenseStatusActivity::class) + fun bindEversenseStatusActivity(injector: MembersInjector): MembersInjector<*> = injector + + @Provides @IntoMap @ClassKey(EversensePlacementActivity::class) + fun bindEversensePlacementActivity(injector: MembersInjector): MembersInjector<*> = injector + } diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseCloudUploader.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseCloudUploader.kt new file mode 100644 index 000000000000..b9b0eb978ce8 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseCloudUploader.kt @@ -0,0 +1,122 @@ +package app.aaps.plugins.source.eversense + +import app.aaps.plugins.eversense.enums.EversenseType +import app.aaps.plugins.eversense.models.EversenseCGMResult +import app.aaps.plugins.eversense.models.EversenseState +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.eversense.storage.edit +import app.aaps.plugins.eversense.util.StorageKeys +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** Optional cloud delivery. Local glucose persistence never waits for network IO. */ +internal class EversenseCloudUploader( + private val scope: () -> CoroutineScope, + private val store: () -> EversenseStore?, + private val enabled: () -> Boolean, + private val online: () -> Boolean, + private val now: () -> Long, + private val elapsed: () -> Long, + private val upload: suspend (EversenseStore, PendingUpload) -> Boolean, + private val onError: (Exception) -> Unit +) { + @Serializable + data class PendingUpload(val type: EversenseType, val state: EversenseState, val readings: List) + + private val json = Json { ignoreUnknownKeys = true } + private val mutex = Mutex() + private val busy = AtomicBoolean(false) + private var lastAttemptElapsed: Long? = null + + suspend fun enqueue(type: EversenseType, readings: List, state: EversenseState) { + if (!enabled()) return + mutex.withLock { + val prefs = store() ?: return + val batches = read(prefs).toMutableList() + val index = batches.indexOfFirst { it.type == type && it.state.transmitterSerialNumber == state.transmitterSerialNumber } + val old = batches.getOrNull(index)?.readings.orEmpty() + val merged = (old + readings).groupBy { it.datetime to it.sensorId } + .values.map { duplicates -> duplicates.maxBy { it.rawResponseHex.length } } + if (index >= 0) batches.removeAt(index) + if (merged.isNotEmpty()) batches.add(PendingUpload(type, state, merged)) + save(prefs, bounded(batches)) + } + flush() + } + + fun flush(force: Boolean = false) { + if (!busy.compareAndSet(false, true)) return + val job = scope().launch { + try { + val reservation = mutex.withLock { + if (!enabled() || !online()) return@launch + val prefs = store() ?: return@launch + val batches = bounded(read(prefs)) + if (batches.isEmpty()) return@launch + val wall = now() + val last = prefs.getLong(StorageKeys.CLOUD_LAST_ATTEMPT, 0) + val previousElapsed = lastAttemptElapsed + if (!force) { + if (previousElapsed != null && elapsed() - previousElapsed < HOUR_MS) return@launch + if (last > wall) { + prefs.edit(commit = true) { putLong(StorageKeys.CLOUD_LAST_ATTEMPT, wall) } + return@launch + } + if (prefs.contains(StorageKeys.CLOUD_LAST_ATTEMPT) && wall - last < HOUR_MS) return@launch + } + // Reserve before IO, including failed attempts, and retain across process restarts. + prefs.edit(commit = true) { putLong(StorageKeys.CLOUD_LAST_ATTEMPT, wall) } + lastAttemptElapsed = elapsed() + prefs to batches + } + val (prefs, batches) = reservation + for (batch in batches) { + if (!enabled() || !online()) break + if (!upload(prefs, batch)) break + mutex.withLock { + val remaining = read(prefs).map { current -> + if (current.type == batch.type && current.state.transmitterSerialNumber == batch.state.transmitterSerialNumber) + current.copy(readings = current.readings.filterNot { it in batch.readings }) + else current + }.filter { it.readings.isNotEmpty() } + save(prefs, remaining) + } + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + onError(e) + } + } + job.invokeOnCompletion { busy.set(false) } + } + + private fun read(prefs: EversenseStore): List = + json.decodeFromString(prefs.getString(StorageKeys.CLOUD_QUEUE, null) ?: "[]") + + private fun save(prefs: EversenseStore, batches: List) { + prefs.edit(commit = true) { putString(StorageKeys.CLOUD_QUEUE, json.encodeToString(batches)) } + } + + private fun bounded(batches: List): List { + val cutoff = now() - RETENTION_MS + var budget = MAX_READINGS + return batches.asReversed().mapNotNull { batch -> + val kept = batch.readings.filter { it.datetime >= cutoff }.sortedByDescending { it.datetime }.take(budget) + budget -= kept.size + if (kept.isEmpty()) null else batch.copy(readings = kept.sortedBy { it.datetime }) + }.asReversed() + } + + companion object { + const val HOUR_MS = 60 * 60_000L + private const val RETENTION_MS = 7 * 24 * HOUR_MS + private const val MAX_READINGS = 2016 + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStateStore.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStateStore.kt new file mode 100644 index 000000000000..86ae8cb46102 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStateStore.kt @@ -0,0 +1,86 @@ +package app.aaps.plugins.source.eversense + +import android.content.Context +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.eversense.util.StorageKeys +import app.aaps.plugins.eversense.storage.EversenseStore +import app.aaps.plugins.source.keys.EversenseRuntimeKey +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull + +/** Imports the whole legacy driver store once. New writes go through registered AAPS preferences. */ +@SingleIn(AppScope::class) +@Inject +class EversenseStateStore(context: Context, private val preferences: Preferences) : EversenseStore { + private val lock = Any() + + init { + preferences.registerPreferences(EversenseRuntimeKey.entries) + if (preferences.getIfExists(EversenseRuntimeKey.DeviceState) == null) { + val legacy = context.getSharedPreferences("EversenseCGMManager", Context.MODE_PRIVATE).all + val imported = legacy.mapValues { (_, value) -> + when (value) { + is String -> JsonPrimitive(value) + is Number -> JsonPrimitive(value) + is Boolean -> JsonPrimitive(value) + is Set<*> -> JsonArray(value.map { JsonPrimitive(it?.toString()) }) + else -> JsonNull + } + } + preferences.put(EversenseRuntimeKey.DeviceState, JsonObject(imported).toString()) + } + } + + private fun read(): JsonObject = Json.parseToJsonElement(preferences.get(EversenseRuntimeKey.DeviceState)).jsonObject + override fun getString(key: String, defaultValue: String?): String? = synchronized(lock) { + if (key == StorageKeys.CLOUD_QUEUE) preferences.getIfExists(EversenseRuntimeKey.CloudQueue) ?: defaultValue + else read()[key]?.jsonPrimitive?.contentOrNull ?: defaultValue + } + override fun getLong(key: String, defaultValue: Long): Long = synchronized(lock) { read()[key]?.jsonPrimitive?.longOrNull ?: defaultValue } + override fun getInt(key: String, defaultValue: Int): Int = synchronized(lock) { read()[key]?.jsonPrimitive?.intOrNull ?: defaultValue } + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = synchronized(lock) { read()[key]?.jsonPrimitive?.booleanOrNull ?: defaultValue } + override fun contains(key: String): Boolean = synchronized(lock) { + if (key == StorageKeys.CLOUD_QUEUE) preferences.getIfExists(EversenseRuntimeKey.CloudQueue) != null else key in read() + } + + override fun edit(): EversenseStore.Editor = object : EversenseStore.Editor { + private val changes = mutableMapOf() + private var clearAll = false + override fun putString(key: String, value: String?) = apply { changes[key] = value?.let { JsonPrimitive(it) } } + override fun putLong(key: String, value: Long) = apply { changes[key] = JsonPrimitive(value) } + override fun putInt(key: String, value: Int) = apply { changes[key] = JsonPrimitive(value) } + override fun putBoolean(key: String, value: Boolean) = apply { changes[key] = JsonPrimitive(value) } + override fun remove(key: String) = apply { changes[key] = null } + override fun clear() = apply { clearAll = true } + override fun commit(): Boolean { + synchronized(lock) { + if (clearAll || changes.keys.any { it != StorageKeys.CLOUD_QUEUE }) { + val updated = if (clearAll) mutableMapOf() else read().toMutableMap() + changes.filterKeys { it != StorageKeys.CLOUD_QUEUE }.forEach { (key, value) -> + if (value == null) updated.remove(key) else updated[key] = value + } + preferences.put(EversenseRuntimeKey.DeviceState, JsonObject(updated).toString()) + } + if (clearAll || StorageKeys.CLOUD_QUEUE in changes) { + preferences.put(EversenseRuntimeKey.CloudQueue, + changes[StorageKeys.CLOUD_QUEUE]?.jsonPrimitive?.contentOrNull ?: "[]") + } + } + return true + } + override fun apply() { commit() } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStringKey.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStringKey.kt new file mode 100644 index 000000000000..fb7c33b00b4a --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/EversenseStringKey.kt @@ -0,0 +1,22 @@ +package app.aaps.plugins.source.eversense + +import app.aaps.core.keys.interfaces.StringPreferenceKey +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.source.R + +/** Preserve PR #191's keys, string storage, mmol/L values and defaults. */ +enum class EversenseStringKey( + override val key: String, + override val defaultValue: String, + titleRes: Int +) : StringPreferenceKey { + TargetHigh("eversense_target_high", "7.8", R.string.eversense_target_high), + TargetLow("eversense_target_low", "4.4", R.string.eversense_target_low), + AlertHigh("eversense_alert_high", "11.1", R.string.eversense_alert_high), + AlertLow("eversense_alert_low", "3.9", R.string.eversense_alert_low); + + override val title = TextRef.AndroidRes(titleRes) + override val summary = TextRef.AndroidRes(R.string.eversense_mmol_unit) + override val isPassword = false + override val isPin = false +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/PositioningSession.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/PositioningSession.kt new file mode 100644 index 000000000000..7686d401d052 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/eversense/PositioningSession.kt @@ -0,0 +1,49 @@ +package app.aaps.plugins.source.eversense + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** A new screen session waits until the previous session has left diagnostic mode. */ +internal class PositioningSession( + private val scope: CoroutineScope, + private val enter: suspend () -> Unit, + private val read: suspend () -> Unit, + private val exit: suspend () -> Unit +) { + private val mutex = Mutex() + private var job: Job? = null + + fun resume() { + pause() + job = scope.launch { + mutex.withLock { + var entering = false + try { + delay(500) + ensureActive() + entering = true + enter() + while (isActive) { + read() + delay(500) + } + } finally { + if (entering) withContext(NonCancellable) { exit() } + } + } + } + } + + fun pause() { + job?.cancel() + job = null + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseBooleanKey.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseBooleanKey.kt new file mode 100644 index 000000000000..a755543e43e9 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseBooleanKey.kt @@ -0,0 +1,23 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.PreferenceType +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.source.R + +enum class EversenseBooleanKey( + override val key: String, + override val defaultValue: Boolean, + titleRes: Int, + summaryRes: Int? = null, + override val exportable: Boolean = true +) : BooleanPreferenceKey { + EversenseDiagnosticLogging("eversense_diagnostic_logging", false, R.string.eversense_diagnostic_logging, R.string.eversense_diagnostic_logging_summary, exportable = false), + EversenseCloudUploadEnabled("eversense_cloud_upload_enabled", true, R.string.eversense_cloud_upload_enabled), + EversenseCloudUploadToast("eversense_notif_cloud_upload_toast", false, R.string.eversense_cloud_upload_toast), + EversenseEuropeanRegion("eversense_european_region", false, R.string.eversense_european_region, R.string.eversense_european_region_summary); + + override val preferenceType = PreferenceType.SWITCH + override val title = TextRef.AndroidRes(titleRes) + override val summary = summaryRes?.let { TextRef.AndroidRes(it) } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseIntentKey.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseIntentKey.kt new file mode 100644 index 000000000000..dd5035fe62ff --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseIntentKey.kt @@ -0,0 +1,62 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.PreferenceType +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntentPreferenceKey +import app.aaps.plugins.source.R +import app.aaps.core.keys.interfaces.TextRef + +enum class EversenseIntentKey( + override val key: String, + val titleResId: Int, + val summaryResId: Int? = null, + override val preferenceType: PreferenceType = PreferenceType.ACTIVITY, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false +) : IntentPreferenceKey { + EversenseStatus( + key = "eversense_status", + titleResId = R.string.eversense_status_title + ), + EversenseCalibration( + key = "eversense_calibration_launch", + titleResId = R.string.eversense_calibration_action + ), + EversensePlacement( + key = "eversense_placement_launch", + titleResId = R.string.eversense_placement_title + ), + EversenseSignOut( + key = "eversense_sign_out", + titleResId = R.string.eversense_sign_out, + preferenceType = PreferenceType.CLICK + ), + EversenseDocumentation( + key = "eversense_documentation", + titleResId = R.string.eversense_documentation, + preferenceType = PreferenceType.CLICK + ), + EversenseForceCloudUpload( + key = "eversense_force_cloud_upload", + titleResId = R.string.eversense_force_cloud_upload_title, + summaryResId = R.string.eversense_force_cloud_upload_summary, + preferenceType = PreferenceType.CLICK, + dependency = EversenseBooleanKey.EversenseCloudUploadEnabled + ); + + override val confirmationMessage get() = if (this == EversenseSignOut) + TextRef.AndroidRes(R.string.eversense_sign_out_confirmation) else null + + override val title get() = TextRef.AndroidRes(titleResId) + override val summary get() = summaryResId?.let { TextRef.AndroidRes(it) } + +} + + + + diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseRuntimeKey.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseRuntimeKey.kt new file mode 100644 index 000000000000..fdfc3dc9efd5 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseRuntimeKey.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +enum class EversenseRuntimeKey( + override val key: String, + override val defaultValue: String +) : StringNonPreferenceKey { + DeviceState("eversense_device_state_json", "{}"), + CloudQueue("eversense_cloud_queue_json", "[]"); + + override val exportable = false +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseStringKey.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseStringKey.kt new file mode 100644 index 000000000000..c8a7927ade12 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/keys/EversenseStringKey.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.source.keys +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.StringPreferenceKey +import app.aaps.plugins.source.R +import app.aaps.core.keys.interfaces.TextRef +enum class EversenseStringKey( + override val key: String, + override val defaultValue: String, + val titleResId: Int, + val summaryResId: Int? = null, + override val isPassword: Boolean = false, + override val isPin: Boolean = false, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false +) : StringPreferenceKey { + EversenseUsername( + key = "eversense_credentials_username", + defaultValue = "", + titleResId = R.string.eversense_credentials_username, + summaryResId = R.string.eversense_credentials_not_set, + exportable = true + ), + EversensePassword( + key = "eversense_credentials_password", + defaultValue = "", + titleResId = R.string.eversense_credentials_password, + summaryResId = R.string.eversense_credentials_not_set, + isPassword = true, + exportable = true + ); + + override val title get() = TextRef.AndroidRes(titleResId) + override val summary get() = summaryResId?.let { TextRef.AndroidRes(it) } + override val requiresPasswordConfirmation get() = this != EversensePassword + +} diff --git a/plugins/source/src/androidMain/res/drawable/eversense_signal_bar.xml b/plugins/source/src/androidMain/res/drawable/eversense_signal_bar.xml new file mode 100644 index 000000000000..02abad050c1d --- /dev/null +++ b/plugins/source/src/androidMain/res/drawable/eversense_signal_bar.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/plugins/source/src/androidMain/res/values-de-rDE/strings.xml b/plugins/source/src/androidMain/res/values-de-rDE/strings.xml index 0d1ecd577741..90d0390f0ef4 100644 --- a/plugins/source/src/androidMain/res/values-de-rDE/strings.xml +++ b/plugins/source/src/androidMain/res/values-de-rDE/strings.xml @@ -27,4 +27,66 @@ + Diagnoseprotokollierung + Ausführliche Bluetooth- und Sensordaten protokollieren. Nach der Fehlersuche wieder ausschalten. + + Status und Verbindung + Cloud-Upload aktivieren + Eversense-DMS-Zugangsdaten + Benutzername + Passwort + Nicht festgelegt + Europäischer Sender (365) + Verwendet für Anmeldung und Cloud-Synchronisierung europäische statt US-Server. Bei einem US-Sender ausgeschaltet lassen. + Abmelden + Dokumentation und Einrichtung + Sender kalibrieren + Senderpositionierung + Ergebnis des Cloud-Uploads anzeigen + Blutzuckerwert eingeben + Blutzuckerwert + Kalibrierung senden + Kalibrierung wird gesendet… + Kalibrierung erfolgreich gesendet + Kalibrierung konnte nicht gesendet werden. Prüfe, ob der Sender verbunden und bereit ist. + Bitte einen gültigen Blutzuckerwert eingeben + Sender wechseln + Diesen Sender vergessen und nach einem neuen suchen? Wähle anschließend den neuen Sender aus den Suchergebnissen aus. + Verbindung zum Sender trennen? + Standardzeitraum der Synchronisierung (Tage) + Verbunden + SYNCHRONISIEREN + Nicht verbunden + Keine Sender gefunden. Stelle sicher, dass sich der Sender in der Nähe befindet, und versuche es erneut. + Sender auswählen + Abbrechen + Suche nach Sendern (10 Sekunden)… + Verbindung wird wiederhergestellt… + Anleitung zur Senderpositionierung + Passe die Senderposition an,\num die Signalstärke zu verbessern + Sehr gute Position! Belasse den Sender an dieser Stelle. + Gute Position. Das Signal ist stark. + Das Signal ist ausreichend. Verschiebe den Sender leicht, um den Empfang zu verbessern. + Schwaches Signal. Positioniere den Sender näher am Sensor. + Schlechter Empfang. Stelle sicher, dass der Sender direkt über der Sensorstelle liegt. + Verbinde dich mit dem Sender, um die Signalstärke anzuzeigen. + Letzte Aktualisierung: %1$s + Signal wird gelesen… + Sehr gut + Gut + Ausreichend + Schwach + Schlecht + Verbunden: %1$s + Akku: %1$d%% + Einsetzdatum: %1$s + Letzte Synchronisierung: %1$s + Positionierungssignal: %1$s + Kalibrierungsphase: %1$s + Letzte Kalibrierung: %1$s + Nächste Kalibrierung: %1$s + Nie + Verbinden + Trennen + Beim Abmelden werden der gespeicherte DMS-Benutzername und das Passwort gelöscht. Möchtest du fortfahren? diff --git a/plugins/source/src/androidMain/res/values-es-rES/strings.xml b/plugins/source/src/androidMain/res/values-es-rES/strings.xml index d11d9b4fb0d5..2972a5db8474 100644 --- a/plugins/source/src/androidMain/res/values-es-rES/strings.xml +++ b/plugins/source/src/androidMain/res/values-es-rES/strings.xml @@ -52,4 +52,66 @@ Reemplazo de sensor requerido. Por favor, cámbialo por un nuevo sensor lo antes posible Señal del sensor perdida. Por favor, comprueba la conexión lectura duplicada + + Estado y conexión + Activar la carga en la nube + Credenciales de Eversense DMS + Nombre de usuario + Contraseña + Sin configurar + Transmisor europeo (365) + Usa servidores europeos en lugar de estadounidenses para iniciar sesión y sincronizar con la nube. Déjalo desactivado para un transmisor estadounidense. + Cerrar sesión + Documentación y configuración + Calibrar transmisor + Colocación del transmisor + Registro de diagnóstico + Registra datos detallados de Bluetooth y del sensor. Desactívalo al terminar el diagnóstico. + Mostrar el resultado de la carga en la nube + Introducir glucemia + Valor de glucemia + Enviar calibración + Enviando calibración… + Calibración enviada correctamente + No se pudo enviar la calibración. Comprueba que el transmisor esté conectado y listo. + Introduce un valor de glucemia válido + Cambiar transmisor + ¿Olvidar este transmisor y buscar uno nuevo? Tendrás que seleccionar el nuevo transmisor en los resultados. + ¿Desconectar del transmisor? + Periodo de sincronización predeterminado (días) + Conectado + SINCRONIZAR + Sin conexión + No se encontraron transmisores. Asegúrate de que el transmisor esté cerca e inténtalo de nuevo. + Seleccionar transmisor + Cancelar + Buscando transmisores (10 segundos)… + Reconectando… + Guía de colocación del transmisor + Ajusta la posición del transmisor\npara mejorar la señal + ¡Excelente colocación! Mantén el transmisor en esta posición. + Buena colocación. La señal es fuerte. + La señal es aceptable. Prueba a mover ligeramente el transmisor para mejorar la recepción. + Señal débil. Acerca el transmisor al sensor. + Mala recepción. Asegúrate de que el transmisor esté directamente sobre el lugar del sensor. + Conecta el transmisor para ver la intensidad de la señal. + Última actualización: %1$s + Leyendo señal… + Excelente + Buena + Aceptable + Débil + Mala + Conectado: %1$s + Batería: %1$d%% + Fecha de inserción: %1$s + Última sincronización: %1$s + Señal de colocación: %1$s + Fase de calibración: %1$s + Última calibración: %1$s + Próxima calibración: %1$s + Nunca + Conectar + Desconectar + Al cerrar sesión se eliminarán el nombre de usuario y la contraseña de DMS guardados. ¿Quieres continuar? diff --git a/plugins/source/src/androidMain/res/values-fr-rFR/strings.xml b/plugins/source/src/androidMain/res/values-fr-rFR/strings.xml index 2e7f9b410acb..f18193fac82e 100644 --- a/plugins/source/src/androidMain/res/values-fr-rFR/strings.xml +++ b/plugins/source/src/androidMain/res/values-fr-rFR/strings.xml @@ -52,4 +52,66 @@ Remplacement du capteur requis, veuillez le remplacer par un nouveau capteur dès que possible Signal capteur perdu, veuillez vérifier la connexion lecture en double + + État et connexion + Activer l’envoi vers le cloud + Identifiants Eversense DMS + Nom d’utilisateur + Mot de passe + Non défini + Émetteur européen (365) + Utilise les serveurs européens plutôt qu’américains pour la connexion et la synchronisation cloud. Laisser désactivé pour un émetteur américain. + Se déconnecter + Documentation et configuration + Calibrer l’émetteur + Positionnement de l’émetteur + Journalisation de diagnostic + Enregistre les données Bluetooth et du capteur en détail. Désactiver après le dépannage. + Afficher le résultat de l’envoi au cloud + Saisir la glycémie + Valeur de glycémie + Envoyer la calibration + Envoi de la calibration… + Calibration envoyée + Échec de l’envoi de la calibration. Vérifiez que l’émetteur est connecté et prêt. + Saisissez une valeur de glycémie valide + Changer d’émetteur + Oublier cet émetteur et en rechercher un nouveau ? Vous devrez sélectionner le nouvel émetteur dans les résultats. + Se déconnecter de l’émetteur ? + Période de synchronisation par défaut (jours) + Connecté + SYNCHRONISER + Non connecté + Aucun émetteur trouvé. Assurez-vous que l’émetteur est à proximité, puis réessayez. + Sélectionner l’émetteur + Annuler + Recherche d’émetteurs (10 secondes)… + Reconnexion… + Guide de positionnement de l’émetteur + Ajustez la position de l’émetteur\npour améliorer le signal + Excellent positionnement ! Gardez l’émetteur dans cette position. + Bon positionnement. Le signal est fort. + Le signal est acceptable. Déplacez légèrement l’émetteur pour améliorer la réception. + Signal faible. Rapprochez l’émetteur du capteur. + Mauvaise réception. Placez l’émetteur directement au-dessus du site du capteur. + Connectez-vous à l’émetteur pour afficher la puissance du signal. + Dernière mise à jour : %1$s + Lecture du signal… + Excellent + Bon + Acceptable + Faible + Mauvais + Connecté : %1$s + Batterie : %1$d%% + Date d’insertion : %1$s + Dernière synchronisation : %1$s + Signal de positionnement : %1$s + Phase de calibration : %1$s + Dernière calibration : %1$s + Prochaine calibration : %1$s + Jamais + Connecter + Déconnecter + La déconnexion supprimera le nom d’utilisateur et le mot de passe DMS enregistrés. Voulez-vous continuer ? diff --git a/plugins/source/src/androidMain/res/values-it-rIT/strings.xml b/plugins/source/src/androidMain/res/values-it-rIT/strings.xml index cdef1f4e1123..6bc917a11cb7 100644 --- a/plugins/source/src/androidMain/res/values-it-rIT/strings.xml +++ b/plugins/source/src/androidMain/res/values-it-rIT/strings.xml @@ -52,4 +52,68 @@ Sostituzione del sensore necessaria, sostituiscilo con un nuovo sensore il prima possibile Segnale sensore perso, controlla la connessione lettura duplicata + + Stato e connessione + Attiva l’invio al cloud + Carica ora i dati nel cloud + Forza l’invio immediato dei dati a Eversense DMS + Credenziali Eversense DMS + Nome utente + Password + Non impostato + Trasmettitore europeo (365) + Usa i server europei anziché quelli statunitensi per l’accesso e la sincronizzazione cloud. Lascia disattivato per un trasmettitore statunitense. + Esci + Documentazione e configurazione + Calibra trasmettitore + Posizionamento del trasmettitore + Registrazione diagnostica + Registra dati dettagliati di Bluetooth e del sensore. Disattiva dopo la risoluzione dei problemi. + Mostra l’esito dell’invio al cloud + Inserisci glicemia + Valore della glicemia + Invia calibrazione + Invio della calibrazione… + Calibrazione inviata correttamente + Invio della calibrazione non riuscito. Verifica che il trasmettitore sia connesso e pronto. + Inserisci un valore glicemico valido + Cambia trasmettitore + Dimenticare questo trasmettitore e cercarne uno nuovo? Dovrai selezionare il nuovo trasmettitore nei risultati. + Disconnettere il trasmettitore? + Periodo di sincronizzazione predefinito (giorni) + Connesso + SINCRONIZZA + Non connesso + Nessun trasmettitore trovato. Assicurati che sia nelle vicinanze e riprova. + Seleziona trasmettitore + Annulla + Ricerca trasmettitori (10 secondi)… + Riconnessione… + Guida al posizionamento del trasmettitore + Regola la posizione del trasmettitore\nper migliorare il segnale + Ottimo posizionamento! Mantieni il trasmettitore in questa posizione. + Buon posizionamento. Il segnale è forte. + Il segnale è accettabile. Prova a spostare leggermente il trasmettitore per migliorare la ricezione. + Segnale debole. Avvicina il trasmettitore al sensore. + Ricezione scarsa. Assicurati che il trasmettitore sia direttamente sopra il sito del sensore. + Connetti il trasmettitore per visualizzare l’intensità del segnale. + Ultimo aggiornamento: %1$s + Lettura del segnale… + Ottimo + Buono + Accettabile + Debole + Scarso + Connesso: %1$s + Batteria: %1$d%% + Data di inserimento: %1$s + Ultima sincronizzazione: %1$s + Segnale di posizionamento: %1$s + Fase di calibrazione: %1$s + Ultima calibrazione: %1$s + Prossima calibrazione: %1$s + Mai + Connetti + Disconnetti + La disconnessione eliminerà il nome utente e la password DMS salvati. Vuoi continuare? diff --git a/plugins/source/src/androidMain/res/values-nl-rNL/strings.xml b/plugins/source/src/androidMain/res/values-nl-rNL/strings.xml index 9a2abf6b48b5..1642a58b09c3 100644 --- a/plugins/source/src/androidMain/res/values-nl-rNL/strings.xml +++ b/plugins/source/src/androidMain/res/values-nl-rNL/strings.xml @@ -52,4 +52,66 @@ De Sensor moet vervangen worden, plaats zo spoedig mogelijk een nieuwe sensor Sensor signaal verloren, controleer de verbinding dubbele waarde + + Status en verbinding + Uploaden naar de cloud inschakelen + Eversense DMS-inloggegevens + Gebruikersnaam + Wachtwoord + Niet ingesteld + Europese zender (365) + Gebruikt Europese in plaats van Amerikaanse servers voor aanmelden en cloudsynchronisatie. Laat uitgeschakeld voor een Amerikaanse zender. + Afmelden + Documentatie en installatie + Zender kalibreren + Plaatsing van de zender + Diagnoselogboek + Registreert gedetailleerde Bluetooth- en sensorgegevens. Schakel uit na het oplossen van problemen. + Resultaat van cloudupload tonen + Bloedglucosewaarde invoeren + Bloedglucosewaarde + Kalibratie verzenden + Kalibratie wordt verzonden… + Kalibratie verzonden + Kalibratie verzenden mislukt. Controleer of de zender verbonden en gereed is. + Voer een geldige bloedglucosewaarde in + Zender wijzigen + Deze zender vergeten en een nieuwe zoeken? Selecteer daarna de nieuwe zender in de zoekresultaten. + Verbinding met de zender verbreken? + Standaard synchronisatieperiode (dagen) + Verbonden + SYNCHRONISEREN + Niet verbonden + Geen zenders gevonden. Zorg dat de zender in de buurt is en probeer opnieuw. + Zender selecteren + Annuleren + Zenders zoeken (10 seconden)… + Opnieuw verbinden… + Handleiding voor zenderplaatsing + Pas de positie van de zender aan\nom het signaal te verbeteren + Uitstekende plaatsing! Houd de zender op deze positie. + Goede plaatsing. Het signaal is sterk. + Het signaal is voldoende. Verplaats de zender een beetje voor een betere ontvangst. + Zwak signaal. Plaats de zender dichter bij de sensor. + Slechte ontvangst. Zorg dat de zender direct boven de sensorplaats zit. + Verbind met de zender om de signaalsterkte te bekijken. + Laatst bijgewerkt: %1$s + Signaal lezen… + Uitstekend + Goed + Voldoende + Zwak + Slecht + Verbonden: %1$s + Batterij: %1$d%% + Plaatsingsdatum: %1$s + Laatste synchronisatie: %1$s + Plaatsingssignaal: %1$s + Kalibratiefase: %1$s + Laatste kalibratie: %1$s + Volgende kalibratie: %1$s + Nooit + Verbinden + Verbinding verbreken + Bij het afmelden worden de opgeslagen DMS-gebruikersnaam en het wachtwoord verwijderd. Wil je doorgaan? diff --git a/plugins/source/src/androidMain/res/values-pl-rPL/strings.xml b/plugins/source/src/androidMain/res/values-pl-rPL/strings.xml index b488b82f32c6..029d6b12893d 100644 --- a/plugins/source/src/androidMain/res/values-pl-rPL/strings.xml +++ b/plugins/source/src/androidMain/res/values-pl-rPL/strings.xml @@ -52,4 +52,66 @@ Wymagana wymiana sensora, wymień go na nowy jak najszybciej. Utracono sygnał z sensora, sprawdź połączenie. Duplikat odczytu + + Stan i połączenie + Włącz przesyłanie do chmury + Dane logowania do Eversense DMS + Nazwa użytkownika + Hasło + Nie ustawiono + Nadajnik europejski (365) + Używa serwerów europejskich zamiast amerykańskich do logowania i synchronizacji z chmurą. Pozostaw wyłączone dla nadajnika z USA. + Wyloguj się + Dokumentacja i konfiguracja + Kalibruj nadajnik + Umiejscowienie nadajnika + Rejestrowanie diagnostyczne + Zapisuje szczegółowe dane Bluetooth i czujnika. Wyłącz po zakończeniu diagnostyki. + Pokaż wynik przesyłania do chmury + Wpisz wartość glikemii + Wartość glikemii + Wyślij kalibrację + Wysyłanie kalibracji… + Kalibracja została wysłana + Nie udało się wysłać kalibracji. Sprawdź, czy nadajnik jest połączony i gotowy. + Wpisz prawidłową wartość glikemii + Zmień nadajnik + Zapomnieć ten nadajnik i wyszukać nowy? Następnie wybierz nowy nadajnik z wyników wyszukiwania. + Rozłączyć nadajnik? + Domyślny okres synchronizacji (dni) + Połączono + SYNCHRONIZUJ + Nie połączono + Nie znaleziono nadajników. Upewnij się, że nadajnik jest w pobliżu, i spróbuj ponownie. + Wybierz nadajnik + Anuluj + Wyszukiwanie nadajników (10 sekund)… + Ponowne łączenie… + Instrukcja umiejscowienia nadajnika + Dostosuj położenie nadajnika,\naby poprawić siłę sygnału + Doskonałe położenie! Pozostaw nadajnik w tej pozycji. + Dobre położenie. Sygnał jest silny. + Sygnał jest wystarczający. Spróbuj lekko przesunąć nadajnik, aby poprawić odbiór. + Słaby sygnał. Umieść nadajnik bliżej czujnika. + Słaby odbiór. Upewnij się, że nadajnik znajduje się bezpośrednio nad miejscem wszczepienia czujnika. + Połącz nadajnik, aby wyświetlić siłę sygnału. + Ostatnia aktualizacja: %1$s + Odczytywanie sygnału… + Doskonały + Dobry + Wystarczający + Słaby + Bardzo słaby + Połączono: %1$s + Bateria: %1$d%% + Data wszczepienia: %1$s + Ostatnia synchronizacja: %1$s + Sygnał położenia: %1$s + Faza kalibracji: %1$s + Ostatnia kalibracja: %1$s + Następna kalibracja: %1$s + Nigdy + Połącz + Rozłącz + Wylogowanie usunie zapisaną nazwę użytkownika i hasło DMS. Czy chcesz kontynuować? diff --git a/plugins/source/src/androidMain/res/values-pt-rBR/strings.xml b/plugins/source/src/androidMain/res/values-pt-rBR/strings.xml index 0c44a00bcfbc..6936f70a2718 100644 --- a/plugins/source/src/androidMain/res/values-pt-rBR/strings.xml +++ b/plugins/source/src/androidMain/res/values-pt-rBR/strings.xml @@ -52,4 +52,66 @@ É necessário substituir o sensor; substitua-o por um sensor novo assim que possível Sinal do sensor perdido; verifique a conexão leitura duplicada + + Status e conexão + Ativar envio para a nuvem + Credenciais do Eversense DMS + Nome de usuário + Senha + Não definido + Transmissor europeu (365) + Usa servidores europeus em vez dos norte-americanos para iniciar sessão e sincronizar com a nuvem. Manter desativado para um transmissor dos EUA. + Sair + Documentação e configuração + Calibrar transmissor + Posicionamento do transmissor + Registro de diagnóstico + Registra dados detalhados de Bluetooth e do sensor. Desative após a solução de problemas. + Mostrar o resultado do envio para a nuvem + Introduzir glicemia + Valor de glicemia + Enviar calibração + A enviar calibração… + Calibração enviada com sucesso + Não foi possível enviar a calibração. Verifique se o transmissor está ligado e pronto. + Introduza um valor de glicemia válido + Mudar de transmissor + Esquecer este transmissor e procurar um novo? Terá de selecionar o novo transmissor nos resultados da pesquisa. + Desconectar do transmissor? + Período padrão de sincronização (dias) + Conectado + SINCRONIZAR + Não conectado + Não foram encontrados transmissores. Verifique se o transmissor está próximo e tente novamente. + Selecionar transmissor + Cancelar + A procurar transmissores (10 segundos)… + A restabelecer a ligação… + Guia de posicionamento do transmissor + Ajuste a posição do transmissor\npara melhorar o sinal + Excelente posicionamento! Mantenha o transmissor nesta posição. + Bom posicionamento. O sinal é forte. + O sinal é aceitável. Tente mover ligeiramente o transmissor para melhorar a recepção. + Sinal fraco. Aproxime o transmissor do sensor. + Recepção ruim. Verifique se o transmissor está diretamente sobre o local do sensor. + Conecte o transmissor para ver a intensidade do sinal. + Última atualização: %1$s + A ler o sinal… + Excelente + Bom + Aceitável + Fraco + Mau + Conectado: %1$s + Bateria: %1$d%% + Data de inserção: %1$s + Última sincronização: %1$s + Sinal de posicionamento: %1$s + Fase de calibração: %1$s + Última calibração: %1$s + Próxima calibração: %1$s + Nunca + Conectar + Desconectar + Ao sair, o nome de usuário e a senha DMS salvos serão excluídos. Deseja continuar? diff --git a/plugins/source/src/androidMain/res/values-pt-rPT/strings.xml b/plugins/source/src/androidMain/res/values-pt-rPT/strings.xml index 18ce1ec76ddb..404bede1d3ef 100644 --- a/plugins/source/src/androidMain/res/values-pt-rPT/strings.xml +++ b/plugins/source/src/androidMain/res/values-pt-rPT/strings.xml @@ -52,4 +52,66 @@ É necessário substituir o sensor, substitua-o por um sensor novo o mais cedo possível Sinal do sensor perdido, verifique a ligação leitura duplicada + + Estado e ligação + Ativar envio para a nuvem + Credenciais do Eversense DMS + Nome de utilizador + Palavra-passe + Não definido + Transmissor europeu (365) + Usa servidores europeus em vez dos norte-americanos para iniciar sessão e sincronizar com a nuvem. Manter desativado para um transmissor dos EUA. + Terminar sessão + Documentação e configuração + Calibrar transmissor + Posicionamento do transmissor + Registo de diagnóstico + Regista dados detalhados de Bluetooth e do sensor. Desativar após a resolução de problemas. + Mostrar o resultado do envio para a nuvem + Introduzir glicemia + Valor de glicemia + Enviar calibração + A enviar calibração… + Calibração enviada com sucesso + Não foi possível enviar a calibração. Verifique se o transmissor está ligado e pronto. + Introduza um valor de glicemia válido + Mudar de transmissor + Esquecer este transmissor e procurar um novo? Terá de selecionar o novo transmissor nos resultados da pesquisa. + Desligar do transmissor? + Período de sincronização predefinido (dias) + Ligado + SINCRONIZAR + Não ligado + Não foram encontrados transmissores. Verifique se o transmissor está próximo e tente novamente. + Selecionar transmissor + Cancelar + A procurar transmissores (10 segundos)… + A restabelecer a ligação… + Guia de posicionamento do transmissor + Ajuste a posição do transmissor\npara melhorar o sinal + Excelente posicionamento! Mantenha o transmissor nesta posição. + Bom posicionamento. O sinal é forte. + O sinal é aceitável. Tente deslocar ligeiramente o transmissor para melhorar a receção. + Sinal fraco. Aproxime o transmissor do sensor. + Má receção. Verifique se o transmissor está diretamente sobre o local do sensor. + Ligue ao transmissor para ver a intensidade do sinal. + Última atualização: %1$s + A ler o sinal… + Excelente + Bom + Aceitável + Fraco + Mau + Ligado: %1$s + Bateria: %1$d%% + Data de inserção: %1$s + Última sincronização: %1$s + Sinal de posicionamento: %1$s + Fase de calibração: %1$s + Última calibração: %1$s + Próxima calibração: %1$s + Nunca + Ligar + Desligar + Ao terminar a sessão, o nome de utilizador e a palavra-passe DMS guardados serão eliminados. Pretende continuar? diff --git a/plugins/source/src/androidMain/res/values/colors.xml b/plugins/source/src/androidMain/res/values/colors.xml new file mode 100644 index 000000000000..4cd50c04212f --- /dev/null +++ b/plugins/source/src/androidMain/res/values/colors.xml @@ -0,0 +1,8 @@ + + + #4CAF50 + #8BC34A + #FFC107 + #F44336 + #CCCCCC + \ No newline at end of file diff --git a/plugins/source/src/androidMain/res/values/strings.xml b/plugins/source/src/androidMain/res/values/strings.xml index 49cf66020a55..21016665aa99 100644 --- a/plugins/source/src/androidMain/res/values/strings.xml +++ b/plugins/source/src/androidMain/res/values/strings.xml @@ -1,5 +1,5 @@ - + NSClient BG Downloads BG data from Nightscout @@ -59,4 +59,231 @@ Sensor signal lost, please check the connection duplicate reading - \ No newline at end of file + Eversense + Eversense E3/365 driver + My Glucose + Calibrate + Enter blood glucose value + Alert History + Device + Connect + Pair with Smart Transmitter + Configuration + Glucose settings + Glucose Target Levels + Glucose Alert Levels + High Target + Low Target + High Alert + Low Alert + mmol/L + Opening Calibration Interface + Scanning for Smart Transmitter + Connection, calibration and alert history are not implemented yet. +Information + +Connected + +Battery percentage + +Insertion date + +START SYNC + +Calibration + +Phase + +Last calibration + +Next calibration + +Calibrate transmitter + +Too soon — calibration already done in the past 2 hours + +Sign out + +Documentation & Setup Guide + +Eversense 365: credentials not set — please sign in to enable cloud sync and readings + +Status & Connection + +Enable cloud upload +Upload data now +Force immediate cloud upload to Eversense DMS + +Show cloud upload result + +Eversense cloud upload failed — check credentials and internet + + +Not connected + +Eversense DMS credentials + +Username + +Password + +Not set + +Set (hidden) + + +Select Eversense transmitter + +Cancel + +Unknown device + +Change Transmitter + +Forget this transmitter and scan for a new one? You\'ll need to select the new transmitter from the scan results. + +Scanning for Eversense devices (10 seconds)… + + +Ready to calibrate + +Calibration status + +Blood glucose value + +Enter BG value + +Submit calibration + +Please enter a valid blood glucose value + +Calibration submission is not yet supported by the Eversense SDK + +Note: Calibration submission requires a future SDK update. The UI is ready but the submit action is not yet functional. + +Calibration submitted successfully + +Failed to submit calibration. Make sure the transmitter is connected and ready. + +Tap to trigger a full sync + +Default Sync Days + +Placement signal + +Transmitter Placement + +Transmitter Placement Guide + +Adjust your transmitter position\nto improve signal strength + +Excellent + +Good + +Fair + +Weak + +Poor + +Great placement! Keep the transmitter in this position. + +Good placement. Signal is strong. + +Signal is acceptable. Try moving the transmitter slightly for a better reading. + +Weak signal. Reposition the transmitter closer to the sensor. + +Poor signal. Make sure the transmitter is placed directly over the sensor site. + +Connect to your transmitter to view signal strength. + +Last update: %1$s + +Reading… + +Transmitter Connected + +Searching for sensor… + +Place the transmitter on your skin directly above the sensor. Signal will stabilize when positioned correctly. + +Your transmitter is connected. Make sure it is positioned directly over your sensor site and secured with the adhesive patch. + +Sending calibration… + +Release for Official App + +Disconnect so the official Eversense app can connect. AAPS will reconnect every 5 minutes automatically. + +Released — AAPS reconnecting every 5 minutes… + +Coexistence Mode + +Automatically disconnect after each sync to give the official Eversense app time to connect and upload data + +Eversense transmitter not detecting — check placement + +Make sure the transmitter is placed directly over the sensor site and secured with the adhesive patch. + +Reconnecting… + + +Eversense sensor expires in %1$d days — plan your sensor replacement. + +Eversense sensor expires in %1$d days — replace your sensor soon. + +Eversense sensor expires in %1$d days — replace your sensor immediately. + +Eversense transmitter battery low: %1$d%% — please charge your transmitter. + +Eversense calibration is due — open AAPS to calibrate your sensor. + +Eversense Calibration Due Now + +Eversense firmware: %1$s — open the official Eversense app to check for updates + +No Eversense transmitters found. Make sure the transmitter is nearby and try again. + + +Connected: %1$s + +Battery: %1$d%% + +Insertion date: %1$s + +Last sync: %1$s + +Placement signal: %1$s + +Calibration phase: %1$s + +Last calibration: %1$s + +Next calibration: %1$s + +Never + +Disconnect + +Connect + + + + + + + +Use ESEL smoothing + +European transmitter (365) + +Routes login and cloud sync through European servers instead of the US ones. Leave off for a US transmitter. + + + Diagnostic logging + Record detailed Bluetooth and sensor data. Turn off after troubleshooting. + Disconnect from transmitter? + Signing out will delete the saved DMS username and password. Do you want to continue? + diff --git a/settings.gradle b/settings.gradle index ac3ed7318ee9..46a7217a8c53 100644 --- a/settings.gradle +++ b/settings.gradle @@ -33,6 +33,7 @@ include ':plugins:main' include ':plugins:sensitivity' include ':plugins:smoothing' include ':plugins:source' +include ':plugins:eversense' include ':plugins:sync' include ':pump:combov2' include ':pump:combov2:comboctl' diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogViewModelTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogViewModelTest.kt new file mode 100644 index 000000000000..0db6560a0b02 --- /dev/null +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogViewModelTest.kt @@ -0,0 +1,92 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import app.aaps.core.data.model.GlucoseUnit +import app.aaps.core.interfaces.logging.UserEntryLogger +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.interfaces.source.EversenseCalibrationSource +import app.aaps.shared.tests.generatedTextResolver +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +@OptIn(ExperimentalCoroutinesApi::class) +class EversenseCalibrationDialogViewModelTest { + private interface CalibratingSource : BgSource, EversenseCalibrationSource + private val profile: ProfileUtil = mock() + private val source: CalibratingSource = mock() + private val active: ActivePlugin = mock() + private val logger: UserEntryLogger = mock() + + @BeforeEach fun setup() { + Dispatchers.setMain(StandardTestDispatcher()) + whenever(profile.units).thenReturn(GlucoseUnit.MGDL) + whenever(active.activeBgSource).thenReturn(source) + whenever(source.isEnabled()).thenReturn(true) + whenever(source.isConnected()).thenReturn(true) + } + @AfterEach fun cleanup() = Dispatchers.resetMain() + + @Test fun invalidInputCannotReachTransmitter() = runTest { + val vm = EversenseCalibrationDialogViewModel(profile, active, logger, generatedTextResolver(), mock()) + for (value in listOf(0.0, -1.0, 39.0, 401.0, Double.NaN, Double.POSITIVE_INFINITY)) { + vm.updateBg(value) + assertThat(vm.uiState.value.canSubmit).isFalse() + vm.submit() + } + advanceUntilIdle() + verify(source, never()).calibrate(any()) + } + + @Test fun convertsMmolAndSendsOnlyOnceWhileSubmitting() = runTest { + whenever(profile.units).thenReturn(GlucoseUnit.MMOL) + whenever(profile.convertToMgdl(5.5, GlucoseUnit.MMOL)).thenReturn(99.0) + whenever(source.calibrate(99)).thenReturn(true) + val vm = EversenseCalibrationDialogViewModel(profile, active, logger, generatedTextResolver(), mock()) + vm.updateBg(5.5) + vm.submit() + vm.submit() + advanceUntilIdle() + verify(source).calibrate(99) + assertThat(vm.uiState.value.submitting).isFalse() + } + + @Test fun sourceSwitchBeforeSubmitPreventsSendingToInactiveTransmitter() = runTest { + val vm = EversenseCalibrationDialogViewModel(profile, active, logger, generatedTextResolver(), mock()) + whenever(active.activeBgSource).thenReturn(mock()) + whenever(profile.convertToMgdl(100.0, GlucoseUnit.MGDL)).thenReturn(100.0) + vm.updateBg(100.0) + vm.submit() + advanceUntilIdle() + verify(source, never()).calibrate(any()) + assertThat(vm.uiState.value.submitting).isFalse() + } + @Test fun rapidChangeWarningDoesNotBlockSubmission() = runTest { + val dynamics: EversenseCalibrationDynamics = mock() + whenever(dynamics.hasRapidChange()).thenReturn(true) + whenever(profile.convertToMgdl(100.0, GlucoseUnit.MGDL)).thenReturn(100.0) + whenever(source.calibrate(100)).thenReturn(true) + val vm = EversenseCalibrationDialogViewModel(profile, active, logger, generatedTextResolver(), dynamics) + assertThat(vm.dynamics.hasRapidChange()).isTrue() + vm.updateBg(100.0) + assertThat(vm.uiState.value.canSubmit).isTrue() + vm.submit() + advanceUntilIdle() + verify(source).calibrate(100) + } + +} diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamicsTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamicsTest.kt new file mode 100644 index 000000000000..9bca2ddb9e2c --- /dev/null +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamicsTest.kt @@ -0,0 +1,53 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import app.aaps.core.data.configuration.Constants +import app.aaps.core.data.iob.InMemoryGlucoseValue +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.interfaces.overview.LastBgData +import app.aaps.core.interfaces.utils.DateUtil +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class EversenseCalibrationDynamicsTest { + private val last: LastBgData = mock() + private val clock: DateUtil = mock() + private val now = 1_794_182_400_000L + private val assessment = EversenseCalibrationDynamics(last, clock) + init { whenever(clock.now()).thenReturn(now) } + + @Test fun verticalDoubleAndTripleArrowsWarnInBothDirections() { + val rapid = setOf(TrendArrow.SINGLE_UP, TrendArrow.SINGLE_DOWN, TrendArrow.DOUBLE_UP, + TrendArrow.DOUBLE_DOWN, TrendArrow.TRIPLE_UP, TrendArrow.TRIPLE_DOWN) + for (arrow in TrendArrow.entries) { + whenever(last.lastBg()).thenReturn(InMemoryGlucoseValue(now, 120.0, arrow)) + assertThat(assessment.hasRapidChange()).isEqualTo(arrow in rapid) + } + } + + @Test fun switchingToADiagonalArrowClearsTheWarning() { + val reading = InMemoryGlucoseValue(now, 120.0, TrendArrow.SINGLE_UP) + whenever(last.lastBg()).thenReturn(reading) + assertThat(assessment.hasRapidChange()).isTrue() + for (arrow in listOf(TrendArrow.FORTY_FIVE_UP, TrendArrow.FORTY_FIVE_DOWN)) { + reading.trendArrow = arrow + assertThat(assessment.hasRapidChange()).isFalse() + } + } + + @Test fun absentStaleAndFutureReadingsAreNotTreatedAsCurrentDynamics() { + assertThat(assessment.hasRapidChange()).isFalse() + for (timestamp in listOf(0L, now - Constants.OLD_BG_MINUTES * 60_000L - 1, now + 1)) { + whenever(last.lastBg()).thenReturn(InMemoryGlucoseValue(timestamp, 120.0, TrendArrow.DOUBLE_UP)) + assertThat(assessment.hasRapidChange()).isFalse() + } + } + + @Test fun freshnessBoundaryUsesTheSameAgeLimitAsAaps() { + whenever(last.lastBg()).thenReturn(InMemoryGlucoseValue(now - Constants.OLD_BG_MINUTES * 60_000L, 120.0, TrendArrow.SINGLE_DOWN)) + assertThat(assessment.hasRapidChange()).isTrue() + whenever(last.lastBg()).thenReturn(InMemoryGlucoseValue(now - Constants.OLD_BG_MINUTES * 60_000L - 1, 120.0, TrendArrow.SINGLE_DOWN)) + assertThat(assessment.hasRapidChange()).isFalse() + } +} diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamicsUiTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamicsUiTest.kt new file mode 100644 index 000000000000..1a6b99aed621 --- /dev/null +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamicsUiTest.kt @@ -0,0 +1,54 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import android.content.Context +import androidx.compose.foundation.layout.Column +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import app.aaps.core.interfaces.resources.TextRefIdRegistry +import app.aaps.ui.UiStringIds +import app.aaps.ui.R +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35]) +class EversenseCalibrationDynamicsUiTest { + @get:Rule val compose = createComposeRule() + + @Before fun setUp() { + TextRefIdRegistry.register("ui") { name -> UiStringIds.idOf(name) } + } + + @Test fun warningIsVisibleWithoutCoveringOrDisablingSubmission() { + val rapid = mutableStateOf(true) + var submitted = false + compose.setContent { + MaterialTheme { + Column { + EversenseCalibrationDynamicsWarningContent(rapid.value) + Button(onClick = { submitted = true }) { Text("Submit") } + } + } + } + val context: Context = RuntimeEnvironment.getApplication() + val message = context.getString(R.string.eversense_calibration_rapid_change_warning) + compose.onNodeWithText(message).assertIsDisplayed() + compose.onNodeWithText("Submit").performClick() + compose.runOnIdle { assertTrue(submitted); rapid.value = false } + compose.onNodeWithText(message).assertDoesNotExist() + } +} diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/navigation/ElementAvailabilityTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/navigation/ElementAvailabilityTest.kt index 2fa2d05497b9..47c5669e4452 100644 --- a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/navigation/ElementAvailabilityTest.kt +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/navigation/ElementAvailabilityTest.kt @@ -7,6 +7,8 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.plugin.PluginBase import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.pump.PumpWithConcentration +import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.interfaces.source.EversenseCalibrationSource import app.aaps.core.interfaces.source.DexcomBoyda import app.aaps.core.interfaces.source.XDripSource import app.aaps.shared.tests.TestBase @@ -171,7 +173,7 @@ class ElementAvailabilityTest : TestBase() { // Every type except the CGM/calibration and pump entries falls through to `true`. Looping // catches the case where someone adds a new entry to the gating `when` without // intentional defaults — this test will start failing for the new type. - val gated = setOf(ElementType.CGM_XDRIP, ElementType.CGM_DEX, ElementType.CALIBRATION, ElementType.FILL, ElementType.BATTERY_CHANGE) + val gated = setOf(ElementType.CGM_XDRIP, ElementType.CGM_DEX, ElementType.CALIBRATION, ElementType.EVERSENSE_CALIBRATION, ElementType.FILL, ElementType.BATTERY_CHANGE) ElementType.entries .filterNot { it in gated } .forEach { type -> @@ -179,6 +181,19 @@ class ElementAvailabilityTest : TestBase() { } } + private interface EversenseSource : BgSource, EversenseCalibrationSource + + @Test fun eversenseCalibrationRequiresAnActiveEversenseSource() { + val source: EversenseSource = mock() + whenever(activePlugin.activeBgSource).thenReturn(source) + whenever(source.isEnabled()).thenReturn(true) + assertThat(elementAvailability.isAvailable(ElementType.EVERSENSE_CALIBRATION)).isTrue() + whenever(source.isEnabled()).thenReturn(false) + assertThat(elementAvailability.isAvailable(ElementType.EVERSENSE_CALIBRATION)).isFalse() + whenever(activePlugin.activeBgSource).thenReturn(mock()) + assertThat(elementAvailability.isAvailable(ElementType.EVERSENSE_CALIBRATION)).isFalse() + } + // -------- helpers -------- private fun stubPump(refill: Boolean = false, battery: Boolean = false, batteryLogging: Boolean = false) { diff --git a/ui/src/androidMain/res/values-de-rDE/strings.xml b/ui/src/androidMain/res/values-de-rDE/strings.xml index 61880140a32f..c03bc7def8fc 100644 --- a/ui/src/androidMain/res/values-de-rDE/strings.xml +++ b/ui/src/androidMain/res/values-de-rDE/strings.xml @@ -356,4 +356,5 @@ Glukosewert ändert sich zu schnell (Δ %1$s %3$s pro 5 min, Grenzwert %2$s). Warte, bis sich die Werte stabilisiert haben. Sensorwechsel vermerken %1$s, %2$s + Der Glukosewert ändert sich gerade stark. Eine Kalibrierung bei starkem Anstieg oder Abfall kann unzuverlässig sein. Beachte die Eversense-Kalibrierungshinweise. Du kannst den Wert trotzdem senden. diff --git a/ui/src/androidMain/res/values-es-rES/strings.xml b/ui/src/androidMain/res/values-es-rES/strings.xml index e484ceda8711..b368950183b5 100644 --- a/ui/src/androidMain/res/values-es-rES/strings.xml +++ b/ui/src/androidMain/res/values-es-rES/strings.xml @@ -356,4 +356,5 @@ La glucosa está cambiando demasiado rápido (Δ %1$s %3$s por cada 5 min, límite %2$s). Espera a que se estabilice Registrar cambio de sensor %1$s, %2$s + La glucosa cambia rápidamente. La calibración durante una subida o bajada rápida puede ser poco fiable. Sigue las instrucciones de Eversense. Puedes enviar el valor de todos modos. diff --git a/ui/src/androidMain/res/values-fr-rFR/strings.xml b/ui/src/androidMain/res/values-fr-rFR/strings.xml index cbecff574cd2..f01420fb6cf1 100644 --- a/ui/src/androidMain/res/values-fr-rFR/strings.xml +++ b/ui/src/androidMain/res/values-fr-rFR/strings.xml @@ -356,4 +356,5 @@ La glycémie change trop vite (Δ %1$s %3$s par 5 min, limite %2$s). Attendez que ce soit stabe. Enregistrer le changement de capteur %1$s, %2$s + Le glucose change rapidement. Un étalonnage pendant une hausse ou une baisse rapide peut être peu fiable. Suivez les consignes Eversense. Vous pouvez tout de même envoyer cette valeur. diff --git a/ui/src/androidMain/res/values-it-rIT/strings.xml b/ui/src/androidMain/res/values-it-rIT/strings.xml index e99111954ad5..6f3bf6066716 100644 --- a/ui/src/androidMain/res/values-it-rIT/strings.xml +++ b/ui/src/androidMain/res/values-it-rIT/strings.xml @@ -356,4 +356,5 @@ Il glucosio sta cambiando troppo velocemente (Δ %1$s %3$s per 5 minuti, limite %2$s). Attendi stabilità. Registra cambio sensore %1$s, %2$s + Il glucosio sta cambiando rapidamente. La calibrazione durante una salita o discesa rapida può essere poco affidabile. Segui le indicazioni Eversense. Puoi comunque inviare il valore. diff --git a/ui/src/androidMain/res/values-nl-rNL/strings.xml b/ui/src/androidMain/res/values-nl-rNL/strings.xml index 3e3b33730c00..0dafc23a335d 100644 --- a/ui/src/androidMain/res/values-nl-rNL/strings.xml +++ b/ui/src/androidMain/res/values-nl-rNL/strings.xml @@ -356,4 +356,5 @@ Glucose waarde verandert te snel (Δ %1$s %3$s per 5 min, limiet %2$s). Wacht tot de waarde stabiel is Markeer eem sensor wijziging %1$s, %2$s + De glucose verandert snel. Kalibreren bij een snelle stijging of daling kan onbetrouwbaar zijn. Volg de kalibratie-instructies van Eversense. Je kunt de waarde toch verzenden. diff --git a/ui/src/androidMain/res/values-pl-rPL/strings.xml b/ui/src/androidMain/res/values-pl-rPL/strings.xml index c030137b3f20..615a29182560 100644 --- a/ui/src/androidMain/res/values-pl-rPL/strings.xml +++ b/ui/src/androidMain/res/values-pl-rPL/strings.xml @@ -358,4 +358,5 @@ Pojawi się tutaj, jeśli/gdy telefon pacjenta je zastosuje. Glukoza zmienia się zbyt szybko (Δ %1$s %3$s na 5 min, limit %2$s). Poczekaj na stabilizację. Zaznacz wymianę sensora %1$s, %2$s + Poziom glukozy szybko się zmienia. Kalibracja podczas szybkiego wzrostu lub spadku może być niewiarygodna. Postępuj zgodnie z instrukcjami Eversense. Nadal możesz wysłać wartość. diff --git a/ui/src/androidMain/res/values-pt-rBR/strings.xml b/ui/src/androidMain/res/values-pt-rBR/strings.xml index 100bebc3ad51..e85593f46e63 100644 --- a/ui/src/androidMain/res/values-pt-rBR/strings.xml +++ b/ui/src/androidMain/res/values-pt-rBR/strings.xml @@ -356,4 +356,5 @@ A glicose está mudando rápido demais (Δ %1$s %3$s por 5 min, limite %2$s). Aguarde a estabilização. Registrar troca de sensor %1$s, %2$s + A glicose está mudando rapidamente. A calibração durante uma subida ou queda rápida pode ser pouco confiável. Siga as orientações Eversense. Você pode enviar o valor mesmo assim. diff --git a/ui/src/androidMain/res/values-pt-rPT/strings.xml b/ui/src/androidMain/res/values-pt-rPT/strings.xml index c5c62a3a1527..aed1d75aab69 100644 --- a/ui/src/androidMain/res/values-pt-rPT/strings.xml +++ b/ui/src/androidMain/res/values-pt-rPT/strings.xml @@ -356,4 +356,5 @@ A glicose está a mudar demasiado depressa (Δ %1$s %3$s por 5 min, limite %2$s). Aguarde que estabilize. Marcar troca de sensor %1$s, %2$s + A glicose está a mudar rapidamente. A calibração durante uma subida ou descida rápida pode ser pouco fiável. Siga as instruções Eversense. Pode enviar o valor mesmo assim. diff --git a/ui/src/androidMain/res/values/strings.xml b/ui/src/androidMain/res/values/strings.xml index 5d9750bbcff7..041d1148f8fe 100644 --- a/ui/src/androidMain/res/values/strings.xml +++ b/ui/src/androidMain/res/values/strings.xml @@ -382,4 +382,14 @@ Mark sensor change %1$s, %2$s +Calibration in progress (%1$s) + + + +Not connected — reconnecting to the transmitter… + +Calibration failed — check the transmitter connection and try again + + + Glucose is changing rapidly. Calibration during a rapid rise or fall may be unreliable. Follow the Eversense calibration guidance. You can still submit this value. diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogScreen.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogScreen.kt new file mode 100644 index 000000000000..c59585ea6204 --- /dev/null +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogScreen.kt @@ -0,0 +1,189 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Info +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalFocusManager +import app.aaps.core.ui.compose.stringResource +import androidx.compose.ui.unit.dp +import app.aaps.core.ui.compose.metroViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.aaps.core.interfaces.navigation.ElementType +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.AapsTopAppBar +import app.aaps.core.ui.compose.NumberInputRow +import app.aaps.core.ui.compose.bottomBarSafeArea +import app.aaps.core.ui.compose.clearFocusOnTap +import app.aaps.core.ui.compose.navigation.label +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.ui.UiStrings +import app.aaps.core.data.format.NumberFormat +import app.aaps.core.ui.CoreUiStrings + +@Composable +fun EversenseCalibrationDialogScreen( + viewModel: EversenseCalibrationDialogViewModel = metroViewModel(), + onNavigateBack: () -> Unit +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val snackbarHostState = remember { SnackbarHostState() } + + LaunchedEffect(Unit) { + viewModel.sideEffect.collect { effect -> + when (effect) { + EversenseCalibrationDialogViewModel.SideEffect.CalibrationAccepted -> onNavigateBack() + is EversenseCalibrationDialogViewModel.SideEffect.CalibrationFailed -> snackbarHostState.showSnackbar(effect.message) + } + } + } + + EversenseCalibrationDialogContent( + uiState = uiState, + snackbarHostState = snackbarHostState, + onBgChange = viewModel::updateBg, + onNavigateBack = onNavigateBack, + onSubmitClick = viewModel::submit, + dynamics = viewModel.dynamics + ) +} + +@Composable +private fun EversenseCalibrationDialogContent( + uiState: EversenseCalibrationDialogUiState, + snackbarHostState: SnackbarHostState, + onBgChange: (Double) -> Unit, + onNavigateBack: () -> Unit, + onSubmitClick: () -> Unit, + dynamics: EversenseCalibrationDynamics +) { + val focusManager = LocalFocusManager.current + + Scaffold( + topBar = { + AapsTopAppBar( + title = { Text(stringResource(CoreUiStrings.eversense_calibration_label)) }, + navigationIcon = { + IconButton(onClick = onNavigateBack) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = stringResource(CoreUiStrings.close) + ) + } + }, + actions = {} + ) + }, + snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, + bottomBar = { + Button( + onClick = { + focusManager.clearFocus() + onSubmitClick() + }, + enabled = uiState.canSubmit, + modifier = Modifier + .fillMaxWidth() + .bottomBarSafeArea() + .padding(horizontal = AapsSpacing.extraLarge, vertical = AapsSpacing.medium) + ) { + Icon( + imageVector = Icons.Filled.Check, + contentDescription = null, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(AapsSpacing.medium)) + if (uiState.hasValidBg) { + val bgFormat = remember(uiState.isMgdl) { if (uiState.isMgdl) NumberFormat() else NumberFormat(minFractionDigits = 1) } + Text("${bgFormat.format(uiState.bg)} ${uiState.unitLabel}") + } else { + Text(stringResource(CoreUiStrings.ok)) + } + } + } + ) { paddingValues -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues) + .verticalScroll(rememberScrollState()) + .clearFocusOnTap(focusManager) + .padding(horizontal = AapsSpacing.extraLarge, vertical = AapsSpacing.medium), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium) + ) { + EversenseCalibrationDynamicsWarning(dynamics) + if (uiState.notConnected) { + NotConnectedCard() + } + + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer) + ) { + Column(modifier = Modifier.padding(horizontal = AapsSpacing.extraLarge, vertical = AapsSpacing.medium)) { + NumberInputRow( + labelRef = CoreUiStrings.bg_label, + value = uiState.bg, + onValueChange = onBgChange, + valueRange = uiState.bgRange, + step = uiState.bgStep, + unitLabel = TextRef.Literal(uiState.unitLabel), + decimalPlaces = uiState.bgDecimalPlaces, + enabled = !uiState.submitting + ) + } + } + } + } +} + +@Composable +private fun NotConnectedCard() { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer + ) + ) { + Row( + modifier = Modifier.padding(horizontal = AapsSpacing.extraLarge, vertical = AapsSpacing.large), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.Info, + contentDescription = null, + modifier = Modifier.size(20.dp) + ) + Spacer(modifier = Modifier.width(AapsSpacing.medium)) + Text(text = stringResource(UiStrings.eversense_calibration_not_connected), style = MaterialTheme.typography.bodyMedium) + } + } +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogUiState.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogUiState.kt new file mode 100644 index 000000000000..963671a06611 --- /dev/null +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogUiState.kt @@ -0,0 +1,21 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import androidx.compose.runtime.Immutable +import app.aaps.core.data.model.GlucoseUnit + +@Immutable +data class EversenseCalibrationDialogUiState( + val bg: Double = 0.0, + val units: GlucoseUnit = GlucoseUnit.MGDL, + val bgRange: ClosedFloatingPointRange = 40.0..400.0, + val bgStep: Double = 1.0, + val bgDecimalPlaces: Int = 0, + val notConnected: Boolean = false, + val submitting: Boolean = false +) { + + val isMgdl: Boolean get() = units == GlucoseUnit.MGDL + val unitLabel: String get() = units.displayLabel + val hasValidBg: Boolean get() = bg.isFinite() && bg in bgRange + val canSubmit: Boolean get() = hasValidBg && !submitting +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogViewModel.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogViewModel.kt new file mode 100644 index 000000000000..755153272a55 --- /dev/null +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDialogViewModel.kt @@ -0,0 +1,105 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import androidx.compose.runtime.Stable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import app.aaps.core.data.model.GlucoseUnit +import app.aaps.core.data.ue.Action +import app.aaps.core.data.ue.Sources +import app.aaps.core.data.ue.ValueWithUnit +import app.aaps.core.interfaces.logging.UserEntryLogger +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.source.EversenseCalibrationSource +import app.aaps.ui.UiStrings +import app.aaps.core.interfaces.plugin.ActivePlugin +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesIntoMap +import dev.zacsweers.metro.binding +import dev.zacsweers.metrox.viewmodel.ViewModelKey +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import dev.zacsweers.metro.Inject + +@ContributesIntoMap(AppScope::class, binding = binding()) +@ViewModelKey +@Stable +@Inject +class EversenseCalibrationDialogViewModel( + private val profileUtil: ProfileUtil, + private val activePlugin: ActivePlugin, + private val uel: UserEntryLogger, + private val rh: TextResolver, + val dynamics: EversenseCalibrationDynamics +) : ViewModel() { + + private val eversenseCalibrationSource get() = activePlugin.activeBgSource as? EversenseCalibrationSource + + private val _uiState = MutableStateFlow(EversenseCalibrationDialogUiState()) + val uiState: StateFlow = _uiState.asStateFlow() + + sealed class SideEffect { + data object CalibrationAccepted : SideEffect() + data class CalibrationFailed(val message: String) : SideEffect() + } + + // replay = 1 so a side effect emitted just before screen rotation still reaches the recreated + // collector — same reasoning as CalibrationDialogViewModel. + private val _sideEffect = MutableSharedFlow( + replay = 1, + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST + ) + val sideEffect: SharedFlow = _sideEffect.asSharedFlow() + + init { + val units = profileUtil.units + val isMmol = units == GlucoseUnit.MMOL + _uiState.update { + EversenseCalibrationDialogUiState( + units = units, + // Eversense's accepted fingerstick calibration range is 40-400 mg/dL. + bgRange = if (isMmol) 2.2..22.2 else 40.0..400.0, + bgStep = if (isMmol) 0.1 else 1.0, + bgDecimalPlaces = if (isMmol) 1 else 0, + notConnected = eversenseCalibrationSource?.isConnected() != true + ) + } + } + + fun updateBg(value: Double) { + _uiState.update { it.copy(bg = value) } + } + + fun submit() { + val state = _uiState.value + if (!state.canSubmit) return + _uiState.update { it.copy(submitting = true) } + val bgMgdl = profileUtil.convertToMgdl(state.bg, state.units).toInt() + viewModelScope.launch { + try { + val source = eversenseCalibrationSource + val success = source?.isEnabled() == true && source.calibrate(bgMgdl) + if (success) { + uel.log( + action = Action.CALIBRATION, + source = Sources.Eversense, + value = ValueWithUnit.fromGlucoseUnit(state.bg, state.units) + ) + _sideEffect.emit(SideEffect.CalibrationAccepted) + } else { + _sideEffect.emit(SideEffect.CalibrationFailed(rh.gs(UiStrings.eversense_calibration_send_failed))) + } + } finally { + _uiState.update { it.copy(submitting = false) } + } + } + } +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamics.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamics.kt new file mode 100644 index 000000000000..0eb1ea61ff19 --- /dev/null +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/eversenseCalibrationDialog/EversenseCalibrationDynamics.kt @@ -0,0 +1,62 @@ +package app.aaps.ui.compose.eversenseCalibrationDialog + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.lifecycle.compose.LifecycleResumeEffect +import app.aaps.core.data.configuration.Constants +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.interfaces.overview.LastBgData +import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.ui.compose.banner.WarningBanner +import app.aaps.core.ui.compose.stringResource +import app.aaps.ui.UiStrings +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** Uses the same recent glucose data as the overview. It never gates calibration submission. */ +@Inject +class EversenseCalibrationDynamics( + private val lastBgData: LastBgData, + private val dateUtil: DateUtil +) { + fun hasRapidChange(): Boolean { + val last = lastBgData.lastBg() ?: return false + val age = dateUtil.now() - last.timestamp + if (age !in 0..Constants.OLD_BG_MINUTES * 60_000L) return false + return when (last.trendArrow) { + TrendArrow.SINGLE_UP, TrendArrow.SINGLE_DOWN, + TrendArrow.DOUBLE_UP, TrendArrow.DOUBLE_DOWN, + TrendArrow.TRIPLE_UP, TrendArrow.TRIPLE_DOWN -> true + else -> false + } + } +} + +@Composable +fun EversenseCalibrationDynamicsWarning(dynamics: EversenseCalibrationDynamics) { + var rapid by remember(dynamics) { mutableStateOf(false) } + val scope = rememberCoroutineScope() + LifecycleResumeEffect(dynamics) { + val job = scope.launch { + while (isActive) { + rapid = withContext(Dispatchers.Default) { dynamics.hasRapidChange() } + delay(5_000) + } + } + onPauseOrDispose { job.cancel() } + } + EversenseCalibrationDynamicsWarningContent(rapid) +} + +@Composable +internal fun EversenseCalibrationDynamicsWarningContent(rapid: Boolean) { + if (rapid) WarningBanner(stringResource(UiStrings.eversense_calibration_rapid_change_warning)) +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/main/MainScreen.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/main/MainScreen.kt index 09c5b2fdd06a..f1aba81d48e6 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/main/MainScreen.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/main/MainScreen.kt @@ -64,6 +64,7 @@ import app.aaps.ui.compose.maintenance.MaintenanceDialogs import app.aaps.ui.compose.maintenance.MaintenanceViewModel import app.aaps.ui.compose.manageSheet.ManageSheetState import app.aaps.ui.compose.manageSheet.ManageViewModel +import app.aaps.ui.compose.overview.EversenseCalibrationProgress import app.aaps.ui.compose.overview.EatReminderBanner import app.aaps.ui.compose.overview.OverviewScreen import app.aaps.ui.compose.overview.chips.ChipsViewModel @@ -300,6 +301,7 @@ fun MainScreen( commandsAllowed = masterOrPairedClient, formatDuration = mainViewModel::formatDuration, eatReminderBanner = { + EversenseCalibrationProgress() EatReminderBanner( state = eatReminderState, onStop = mainViewModel::stopEatReminder, diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/navigation/ElementAvailability.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/navigation/ElementAvailability.kt index 914aa531f8db..e9f7df5e5d18 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/navigation/ElementAvailability.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/navigation/ElementAvailability.kt @@ -4,6 +4,7 @@ import app.aaps.core.interfaces.navigation.ElementType import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.plugin.PluginBase import app.aaps.core.interfaces.source.DexcomBoyda +import app.aaps.core.interfaces.source.EversenseCalibrationSource import app.aaps.core.interfaces.source.XDripSource import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.Inject @@ -26,6 +27,7 @@ class ElementAvailability( ) { fun isAvailable(elementType: ElementType): Boolean = when (elementType) { + ElementType.EVERSENSE_CALIBRATION -> (activePlugin.activeBgSource as? EversenseCalibrationSource)?.isEnabled() == true ElementType.CALIBRATION -> xDripSource.isEnabled() || isCalibrationOverrideActive() ElementType.CGM_XDRIP -> xDripSource.isEnabled() ElementType.CGM_DEX -> dexcomBoyda.isEnabled() diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/EversenseCalibrationBanner.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/EversenseCalibrationBanner.kt new file mode 100644 index 000000000000..f368f839e647 --- /dev/null +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/EversenseCalibrationBanner.kt @@ -0,0 +1,101 @@ +package app.aaps.ui.compose.overview + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Timer +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import app.aaps.core.ui.compose.stringResource +import androidx.compose.ui.unit.dp +import app.aaps.core.objects.extensions.tickerFlow +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.ui.UiStrings +import kotlin.time.Clock +import app.aaps.core.keys.LongNonKey +import app.aaps.core.ui.compose.LocalPreferences +import androidx.lifecycle.compose.collectAsStateWithLifecycle + +/** 15 minutes, matching the official Eversense app's post-calibration countdown bar. */ +private const val CALIBRATION_COUNTDOWN_MS = 15 * 60 * 1000L + +/** + * Home-screen banner mirroring the official Eversense app's post-calibration countdown bar (see + * the feature request's reference screenshot). Renders nothing once [submittedAtMs] is more than + * 15 minutes old, or is 0 (the never-submitted default) — callers don't need a separate "is + * Eversense in use" gate: EversenseLastCalibrationSubmittedAt is only ever written on a successful + * calibration submission (both the Settings -> Eversense -> Calibration screen and the + * quick-launch "Eversense Calibration" dialog write it), so a fresh value already implies + * Eversense is the one in use. + */ +@Composable +fun EversenseCalibrationBanner( + submittedAtMs: Long, + modifier: Modifier = Modifier +) { + var now by remember(submittedAtMs) { mutableLongStateOf(Clock.System.now().toEpochMilliseconds()) } + LaunchedEffect(submittedAtMs) { + tickerFlow(1_000L).collect { now = Clock.System.now().toEpochMilliseconds() } + } + + val remainingMs = submittedAtMs + CALIBRATION_COUNTDOWN_MS - now + val visible = submittedAtMs > 0 && remainingMs > 0 + + AnimatedVisibility( + visible = visible, + enter = fadeIn(), + exit = fadeOut() + ) { + val totalSeconds = (remainingMs / 1000).coerceAtLeast(0).toInt() + val minutes = totalSeconds / 60 + val seconds = totalSeconds % 60 + val countdownText = "$minutes:${seconds.toString().padStart(2, '0')}" + + Surface( + color = MaterialTheme.colorScheme.secondaryContainer, + modifier = modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier.padding(AapsSpacing.medium), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.small) + ) { + Icon( + imageVector = Icons.Default.Timer, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.size(20.dp) + ) + Text( + text = stringResource(UiStrings.eversense_calibration_in_progress, countdownText), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + } + } + } +} + + +@Composable +fun EversenseCalibrationProgress() { + val preferences = LocalPreferences.current + val submittedAt by preferences.observe(LongNonKey.EversenseLastCalibrationSubmittedAt).collectAsStateWithLifecycle() + EversenseCalibrationBanner(submittedAtMs = submittedAt) +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModel.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModel.kt index 74d07b45ca43..a04a59dc882b 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModel.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModel.kt @@ -16,6 +16,7 @@ import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventConfigBuilderChange import app.aaps.core.interfaces.rx.events.EventInitializationChanged import app.aaps.core.interfaces.rx.events.EventNsClientStatusUpdated +import app.aaps.core.interfaces.source.EversenseCalibrationSource import app.aaps.core.interfaces.stats.TddCalculator import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter @@ -180,6 +181,10 @@ class StatusViewModel( val bgSource = activePlugin.activeBgSource // Sensor battery: not shown in Overview (compact), shown in Actions (expanded) unless AAPSCLIENT val hasBattery = !config.AAPSCLIENT && bgSource.sensorBatteryLevel != -1 + // Eversense's sensorBatteryLevel is the transmitter battery. Show it beside the sensor age + // on the compact Overview row only while Eversense is the active BG source. + val showEversenseTransmitterBattery = hasBattery && + (bgSource as? EversenseCalibrationSource)?.isEnabled() == true val level = if (hasBattery) rh.gs(CoreUiStrings.units_format_percent, bgSource.sensorBatteryLevel) else null val levelPercent = if (hasBattery) bgSource.sensorBatteryLevel / 100f else -1f @@ -192,7 +197,7 @@ class StatusViewModel( levelStatus = if (levelPercent >= 0) getLevelStatus((levelPercent * 100).toDouble(), IntKey.OverviewSbatWarning, IntKey.OverviewSbatCritical) else StatusLevel.UNSPECIFIED, levelPercent = if (levelPercent >= 0) 1f - levelPercent else -1f, icon = IcCgmInsert, - compactLevel = false // Overview: sensor battery not shown + compactLevel = showEversenseTransmitterBattery ) } @@ -330,4 +335,4 @@ class StatusViewModel( else -> StatusLevel.NORMAL } } -} \ No newline at end of file +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchAction.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchAction.kt index 2466abaca9de..a00cd0995fb9 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchAction.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchAction.kt @@ -83,6 +83,7 @@ sealed class QuickLaunchAction { val Treatment = StaticAction(ElementType.TREATMENT) val Cgm = StaticAction(ElementType.CGM_XDRIP) val Calibration = StaticAction(ElementType.CALIBRATION) + val EversenseCalibration = StaticAction(ElementType.EVERSENSE_CALIBRATION) val InsulinManagement = StaticAction(ElementType.INSULIN_MANAGEMENT) val ProfileSwitch = StaticAction(ElementType.PROFILE_MANAGEMENT) val TempTargetManagement = StaticAction(ElementType.TEMP_TARGET_MANAGEMENT) @@ -115,7 +116,7 @@ sealed class QuickLaunchAction { * `PAIR_WITH_MASTER`, which is a one time setup step and not something to keep on a toolbar. */ val staticActions: List = listOf( - Insulin, Carbs, Wizard, Treatment, Cgm, Calibration, + Insulin, Carbs, Wizard, Treatment, Cgm, Calibration, EversenseCalibration, ProfileSwitch, InsulinManagement, TempTargetManagement, QuickWizardManagement, SceneManagement, AutomationManagement, FoodManagement, RunningMode, AuthorizedClients, diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchResolver.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchResolver.kt index 4dadc1a4899c..f0f736f747cd 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchResolver.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/quickLaunch/QuickLaunchResolver.kt @@ -1,5 +1,7 @@ package app.aaps.ui.compose.quickLaunch +import app.aaps.core.interfaces.navigation.ElementType + import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Extension import androidx.compose.ui.graphics.vector.ImageVector @@ -98,6 +100,7 @@ class QuickLaunchResolver( } fun isValid(action: QuickLaunchAction): Boolean = when (action) { + QuickLaunchAction.EversenseCalibration -> true // Keep the saved action when another BG source is active. is QuickLaunchAction.QuickWizardAction -> quickWizard.get(action.guid) != null is QuickLaunchAction.AutomationAction -> { @@ -133,6 +136,7 @@ class QuickLaunchResolver( * entry is only hidden here, never removed from the saved toolbar like an [isValid] failure. */ fun isShownNow(action: QuickLaunchAction): Boolean = when (action) { + QuickLaunchAction.EversenseCalibration -> elementAvailability.isAvailable(ElementType.EVERSENSE_CALIBRATION) is QuickLaunchAction.QuickWizardAction -> quickWizard.get(action.guid)?.isActive() == true else -> true } diff --git a/wear/watchfaces/README.md b/wear/watchfaces/README.md new file mode 100644 index 000000000000..251c8e25c29b --- /dev/null +++ b/wear/watchfaces/README.md @@ -0,0 +1,28 @@ +# Material and Sport custom watchfaces for AndroidAPS 4 + +Material 1.18 and Sport 1.18 are maintained in [BernhardRo/AndroidAPS, branch `dev`](https://github.com/BernhardRo/AndroidAPS/tree/dev). Integrated from `AAPS-Material-Sport-Watchface-Patch-2026-11-07.zip` on 2026-11-08; later local revisions add the glucose delta and reading-age placements, plus three Sport complication slots. + +- [Material source and usage](material/README.md) +- [Sport source and usage](sport/README.md) +- Importable assets: `plugins/configuration/src/androidMain/assets/AAPS Material.zip` and `AAPS Sport.zip`. + +The archive's 31 project files were imported. Asset paths, Compose icon references and contract-test paths were adapted to this checkout's Android/common source sets. The matching-divider contract test follows the current renderer's additional preference-label argument while retaining its false default. The archive's workspace-specific `AGENTS.md` and `Project.md` are reference documents and were not installed as project instructions. + +Both assets were rebuilt with the pinned Python dependencies. Their ZIP compression differs from the archive, but every contained file is byte-identical. The existing AAPS V2 asset and native renderer are unchanged. These are CWF packages, not standalone WFF applications. + +## Local verification + +Use an isolated environment from the repository root (PowerShell): + +```powershell +python -m venv build/watchface-venv +./build/watchface-venv/Scripts/python.exe -m pip install -r wear/watchfaces/sport/requirements.txt +./build/watchface-venv/Scripts/python.exe wear/watchfaces/material/build_watchface.py --check +./build/watchface-venv/Scripts/python.exe wear/watchfaces/sport/build_watchface.py --check +./build/watchface-venv/Scripts/python.exe -m unittest discover -s wear/watchfaces/material -p "test_*.py" -v +./build/watchface-venv/Scripts/python.exe -m unittest discover -s wear/watchfaces/sport -p "test_*.py" -v +``` + +On integration: Material's 26 tests and Sport's 45 tests passed; both builder consistency checks and `:plugins:configuration:mergeAndroidMainAssets` succeeded. ZIP CRCs and contained-file equality against the original package were checked. The per-face `TESTRESULTS.md` files are historical records from the source checkout. No APK installation or actual-watch verification was performed for this integration. + +AAPS automatically loads bundled CWF assets only when its existing import list is empty. For an existing populated list, copy the two ZIPs into the selected AAPS `exports` folder before importing; see the face-specific instructions. diff --git a/wear/watchfaces/material/.gitignore b/wear/watchfaces/material/.gitignore new file mode 100644 index 000000000000..c18dd8d83cee --- /dev/null +++ b/wear/watchfaces/material/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/wear/watchfaces/material/CustomWatchface.json b/wear/watchfaces/material/CustomWatchface.json new file mode 100644 index 000000000000..77f90c34e287 --- /dev/null +++ b/wear/watchfaces/material/CustomWatchface.json @@ -0,0 +1,200 @@ +{ + "metadata": { + "name": "AAPS Material", + "author": "OpenCode", + "created_at": "14/10/2026", + "author_version": "1.18", + "cwf_version": "1.0", + "comment": "Material 3 Expressive-inspired layout. Same data fields as AAPS V2 (1.0), by Andrew Warrington, adapted to CWF by Philoul. No changes to data, alerts or treatment logic." + }, + "dynPrefColor": "palette", + "pointSize": 2, + "enableSecond": false, + "background": { + "width": 400, "height": 400, "topmargin": 0, "leftmargin": 0, + "visibility": "visible", "dynPref": "surface" + }, + "chart": { + "width": 216, "height": 86, "topmargin": 266, "leftmargin": 92, + "visibility": "visible" + }, + "time": { + "width": 174, "height": 80, "topmargin": 83, "leftmargin": 113, + "visibility": "visible", "textsize": 64, "gravity": "center", + "font": "roboto_condensed_regular", "fontStyle": "normal", "dynPref": "primary" + }, + "timePeriod": { + "width": 34, "height": 22, "topmargin": 144, "leftmargin": 250, + "visibility": "visible", "textsize": 14, "gravity": "center", + "font": "roboto_condensed_regular", "dynPref": "secondary" + }, + "day": { + "width": 44, "height": 26, "topmargin": 106, "leftmargin": 292, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "dynPref": "secondary" + }, + "month": { + "width": 44, "height": 26, "topmargin": 132, "leftmargin": 292, + "visibility": "visible", "textsize": 18, "gravity": "center", "allCaps": true, + "font": "roboto_condensed_regular", "dynPref": "secondary" + }, + "sgv": { + "width": 160, "height": 74, "topmargin": 18, "leftmargin": 114, + "visibility": "visible", "textsize": 54, "gravity": "center", + "font": "roboto_condensed_regular", "fontStyle": "normal" + }, + "loop": { + "width": 44, "height": 44, "topmargin": 116, "leftmargin": 60, + "visibility": "visible", "textsize": 0, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#FFFFFF", "dynPref": "primary" + }, + "direction": { + "width": 400, "height": 400, "topmargin": 0, "leftmargin": 0, + "visibility": "visible" + }, + "timestamp": { + "width": 44, "height": 44, "topmargin": 116, "leftmargin": 60, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#FFFFFF" + }, + "uploader_battery": { + "width": 70, "height": 24, "topmargin": 81, "leftmargin": 48, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "fontColor": "#757575", "background": "Phone" + }, + "rig_battery": { + "width": 70, "height": 24, "topmargin": 81, "leftmargin": 282, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "dynPref": "secondary", "background": "Rig" + }, + "freetext1": { + "width": 30, "height": 32, "topmargin": 166, "leftmargin": 40, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "textvalue": "Δ", "dynPref": "deltaLabel" + }, + "delta": { + "width": 118, "height": 32, "topmargin": 166, "leftmargin": 72, + "visibility": "visible", "textsize": 23, "gravity": "center", + "font": "roboto_condensed_bold", "dynPref": "primary" + }, + "reservoir": { + "width": 110, "height": 32, "topmargin": 166, "leftmargin": 250, + "visibility": "visible", "textsize": 23, "gravity": "center", + "font": "roboto_condensed_bold", "dynPref": "primary" + }, + "freetext2": { + "width": 38, "height": 32, "topmargin": 166, "leftmargin": 210, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "textvalue": "RES", "dynPref": "reservoirLabel" + }, + "cob1": { + "width": 94, "height": 20, "topmargin": 205, "leftmargin": 37, + "visibility": "visible", "textsize": 16, "gravity": "center", + "font": "roboto_condensed_regular", "dynPref": "secondary" + }, + "cob2": { + "width": 96, "height": 34, "topmargin": 225, "leftmargin": 36, + "visibility": "visible", "textsize": 25, "gravity": "center", + "font": "roboto_condensed_bold", "dynPref": "primary" + }, + "freetext3": { + "width": 106, "height": 18, "topmargin": 204, "leftmargin": 147, + "visibility": "visible", "textsize": 14, "gravity": "center", + "font": "roboto_condensed_regular", "textvalue": "BASAL", "dynPref": "basalLabel" + }, + "basalRate": { + "width": 110, "height": 24, "topmargin": 220, "leftmargin": 145, + "visibility": "visible", "textsize": 22, "gravity": "center", + "font": "roboto_condensed_bold", "dynPref": "primary" + }, + "freetext4": { + "width": 28, "height": 18, "topmargin": 243, "leftmargin": 151, + "visibility": "visible", "textsize": 12, "gravity": "center", + "font": "roboto_condensed_regular", "textvalue": "BGI", "dynPref": "bgiLabel" + }, + "bgi": { + "width": 74, "height": 20, "topmargin": 241, "leftmargin": 180, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "dynPref": "secondary" + }, + "iob1": { + "width": 94, "height": 20, "topmargin": 205, "leftmargin": 269, + "visibility": "visible", "textsize": 16, "gravity": "center", + "font": "roboto_condensed_regular", "dynPref": "iobHeading" + }, + "iob2": { + "width": 96, "height": 34, "topmargin": 225, "leftmargin": 268, + "visibility": "visible", "textsize": 25, "gravity": "center", + "font": "roboto_condensed_bold", "dynPref": "iobValue" + }, + "dynPref": { + "surface": { + "prefKey": "key_match_divider", + "true": { "dynPref": "plainSurface" }, + "false": { "dynPref": "tonalSurface" } + }, + "tonalSurface": { + "prefKey": "key_dark", + "true": { "valueKey": "day", "image1": "MaterialDark" }, + "false": { "valueKey": "day", "image1": "MaterialLight" } + }, + "plainSurface": { + "prefKey": "key_dark", + "true": { "valueKey": "day", "image1": "MaterialDarkPlain" }, + "false": { "valueKey": "day", "image1": "MaterialLightPlain" } + }, + "primary": { + "prefKey": "key_dark", + "true": { "valueKey": "day", "fontColor1": "#F0F5F1" }, + "false": { "valueKey": "day", "fontColor1": "#18231D" } + }, + "secondary": { + "prefKey": "key_dark", + "true": { "valueKey": "day", "fontColor1": "#BAC8BF" }, + "false": { "valueKey": "day", "fontColor1": "#46584C" } + }, + "deltaLabel": { + "prefKey": "key_show_delta", + "true": { "dynPref": "secondary" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "reservoirLabel": { + "prefKey": "key_show_reservoir_level", + "true": { "dynPref": "secondary" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "basalLabel": { + "prefKey": "key_show_temp_basal", + "true": { "dynPref": "secondary" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "bgiLabel": { + "prefKey": "key_show_bgi", + "true": { "dynPref": "secondary" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "iobHeading": { + "prefKey": "key_show_detailed_iob", + "true": { "textsize1": 20, "dynPref": "primary" }, + "false": { "dynPref": "secondary" } + }, + "iobValue": { + "prefKey": "key_show_detailed_iob", + "true": { "textsize1": 16, "dynPref": "secondary" }, + "false": { "dynPref": "primary" } + }, + "palette": { + "prefKey": "key_dark", + "true": { + "highColor": "#FFCF72", "midColor": "#9EE7C4", "lowColor": "#FF8C96", + "lowBatColor": "#FF8C96", "carbColor": "#FFBD82", + "basalBackgroundColor": "#22483D", "basalCenterColor": "#88C9ED", "gridColor": "#61766A" + }, + "false": { + "highColor": "#795400", "midColor": "#146C48", "lowColor": "#BA1A32", + "lowBatColor": "#BA1A32", "carbColor": "#874600", + "basalBackgroundColor": "#B3DCCD", "basalCenterColor": "#246588", "gridColor": "#65796D" + } + } + } +} diff --git a/wear/watchfaces/material/CustomWatchface.png b/wear/watchfaces/material/CustomWatchface.png new file mode 100644 index 000000000000..e76efe739d7c Binary files /dev/null and b/wear/watchfaces/material/CustomWatchface.png differ diff --git a/wear/watchfaces/material/MaterialDark.svg b/wear/watchfaces/material/MaterialDark.svg new file mode 100644 index 000000000000..bcea2b230529 --- /dev/null +++ b/wear/watchfaces/material/MaterialDark.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/wear/watchfaces/material/MaterialDarkPlain.svg b/wear/watchfaces/material/MaterialDarkPlain.svg new file mode 100644 index 000000000000..bc1b9a146a1d --- /dev/null +++ b/wear/watchfaces/material/MaterialDarkPlain.svg @@ -0,0 +1,3 @@ + + + diff --git a/wear/watchfaces/material/MaterialLight.svg b/wear/watchfaces/material/MaterialLight.svg new file mode 100644 index 000000000000..20e1a1e59bc9 --- /dev/null +++ b/wear/watchfaces/material/MaterialLight.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/wear/watchfaces/material/MaterialLightPlain.svg b/wear/watchfaces/material/MaterialLightPlain.svg new file mode 100644 index 000000000000..78081570e53b --- /dev/null +++ b/wear/watchfaces/material/MaterialLightPlain.svg @@ -0,0 +1,3 @@ + + + diff --git a/wear/watchfaces/material/Phone.svg b/wear/watchfaces/material/Phone.svg new file mode 100644 index 000000000000..b380fff3c6fe --- /dev/null +++ b/wear/watchfaces/material/Phone.svg @@ -0,0 +1,4 @@ + + + + diff --git a/wear/watchfaces/material/README.md b/wear/watchfaces/material/README.md new file mode 100644 index 000000000000..b71c0cf58099 --- /dev/null +++ b/wear/watchfaces/material/README.md @@ -0,0 +1,110 @@ +# AAPS Material (1.18) + +Integrated into this AndroidAPS 4 checkout; see [integration and current verification](../README.md). The source-checkout notes below document the original design and its history. + +A separate **Custom Watchface** for the Wear target of [BernhardRo/AndroidAPS, branch `dev`](https://github.com/BernhardRo/AndroidAPS/tree/dev). + +The layout takes its information set from the bundled **AAPS V2 (1.0)** by Andrew Warrington, adapted to CWF by Philoul. The original ZIP is not changed. + +## Design + +Material 3 Expressive-inspired styling: a black OLED background, mint accent, rounded tonal surfaces, a large central clock, and clear type hierarchy. A light variant follows the existing dark-mode setting. The existing Wear fonts are reused; no font download or new Android dependency is required. + +- Top: glucose and phone/rig batteries with distinct icons. +- Outer edge: live glucose trend as an AAPS-4-style full circle, bright arc and outward arrowheads. +- Center: time, optional day/month stacked to its right, optional AM/PM below the clock, and the separate existing colored loop icon with glucose-reading age inside it. +- Chips: delta and remaining pump insulin (RES) in their original two fields below the clock. +- Cards: COB, basal rate/BGI, and IOB, including the detailed IOB option. +- Bottom: the existing live chart, including its configured history, target lines, treatments and basal overlay. + +The chart is smaller than in AAPS V2; its complete rectangle stays inside a round screen. No chart data or history settings are changed. The template uses the same 400 × 400 coordinate space as AAPS V2 and the renderer scales it to the display width. + +Version 1.11 gives day and month taller text fields: 26 instead of 18 template pixels, while keeping their 18-pixel font. The day/month spacing is adjusted, and optional AM/PM has a 22-pixel-tall field below the clock, to the left of the date. This addresses the user's report of a clipped month on the Galaxy Watch 4. The new test reserves a full font line plus extra space instead of checking visible glyphs alone; actual Android rendering still needs verification. + +Version 1.18 moves glucose age into the loop-status ring and restores native delta and remaining pump insulin (RES) to their original two pills below the clock. Native loop-state colors and glucose-age warning colors remain active. + +Glucose remains at the top with 54-pixel text and time in the center with 64-pixel text. The version 1.9 ring (diameter 380, stroke 7, tips at radius 198), all other fields, warning colors and the version 1.10 matching-divider support are unchanged. + +### Matching divider / Querbalken farbgleich + +In the watch's **AAPS(Custom)** settings: + +- **Off:** keep the existing colored Material surfaces behind time, delta/reservoir, COB/basal/IOB and the chart. +- **On:** match those surfaces to the overall background: black in dark mode, white in light mode. + +This changes only the decorative background image. Text, live values, warning colors, trend ring, loop icons and chart data remain unchanged. Chart curves, grid, treatments and basal overlays keep their existing colors. Your saved setting is used; the ZIP does not turn the setting on or off. With the native default of off, the earlier Material look is preserved. + +The face uses the native `key_match_divider` preference to select one of four SVG backgrounds through its existing dynamic-preference support. No APK or native renderer change is needed. `preview-surfaces.png` compares both settings in dark and light modes. Its images use synthetic data, not watch screenshots. On-watch switching still needs verification. + +### Trend ring + +The geometry follows `ui/.../compose/overview/BgInfoSection.kt`: a 30%-opacity full circle, a bright 40° arc, and outward triangles at the actual trend position. Flat is right/3 o'clock; rising is upper-right or top; falling is lower-right or bottom. Double-up/down use two triangles. The ring follows the existing glucose range color, **not** the loop status. Reading age and stale-value strike-through remain visible independently. + +The eight generated `Arrow*.png` files use white pixels and transparency. The existing CWF `TrendArrowMap` selects the appropriate file and applies its native glucose-color filter. This preserves normal Wear updates without an APK rebuild, protocol change or new native watchface code. Disabling the Wear direction-arrow setting hides the whole ring. Unknown/NONE uses a dim circle without a bright arc or arrowhead, not a fabricated flat arrow. + +**User confirmation, 2026-10-15:** the ring became visible on the user's **Samsung Galaxy Watch 4** after enabling **Trendpfeil anzeigen**. That setting was the cause of the reported missing ring, not a demonstrated size or resource-loading fault. This confirms visibility of the earlier ring only; version 1.9's larger ring and all individual trend states still need on-watch verification. + +### If the ring is missing on the watch + +In the 400-pixel template, the version 1.9 circle is 380 pixels across, the stroke outer radius is 193.5, and the arrowhead vertices stay inside radius 198. The PNGs are recognized by this checkout's importer. Static checks are not a substitute for checking the installed phone/Wear version and the watch display. + +1. In the watch's AAPS display settings, enable **Show Direction Arrow** (**Trendpfeil anzeigen**). The ring is the native direction view; this setting hides or shows the whole ring. This face does not override your setting. +2. Check with the watch awake, not charging, and with simplified UI off for the test. `SimpleUi` draws its own glucose/time display instead of the custom layout and does not use the ring PNGs. +3. Replace the ZIP in `exports` and explicitly load **AAPS Material (1.18)** again; select **AAPS(Custom)** on the watch. The selection image is synthetic and is not proof that its resources rendered on the watch. The user also reported that the ring is visible on the watch even when absent from the Samsung phone overview image; that image alone does not establish a missing ring. +4. If still absent, provide the watch model, phone/Wear AAPS versions, a photo of the active face, and whether any small trend arrow appears. A small arrow would suggest the native fallback icon rather than the custom ring resource. No native renderer change is included in this package. + +**Existing Wear limitation:** this branch transmits both triple-up and triple-down with the same `X` symbol. The existing CWF renderer maps that symbol to its double-up resource. An asset-only face cannot distinguish those triple directions or match the phone's three-triangle display; this existing ambiguity is not fixed here. Use the phone display to check triple trends. The ring matches the seven distinct ordinary directions supported by the renderer, not all phone trend states. + +All live text comes from the existing AAPS fields. The face does not set units, thresholds, treatment values or user preferences. Optional fields still follow the Wear display settings. Rig battery, BGI and date are off by default in the existing renderer; enable them there if wanted. Empty tonal surfaces may remain when their fields are hidden. + +The native stale-value strike-through, reading-age warning, low-phone-battery warning and grey/green/red loop icons remain under the existing renderer's control. The glucose range colors change visually, not semantically or numerically. Static theme steps use the current calendar day as `valueKey`: unlike the renderer's zero-range `NONE` value, it selects the single style step even when glucose is missing. + +## Files and build + +Editable sources are `CustomWatchface.json`, the six SVGs and the trend-ring geometry in `build_watchface.py`. The generated package is: + +`plugins/configuration/src/androidMain/assets/AAPS Material.zip` + +Run from the AndroidAPS checkout root with Python and Pillow installed: + +```powershell +python -m pip install -r wear/watchfaces/material/requirements.txt +python wear/watchfaces/material/build_watchface.py +python wear/watchfaces/material/build_watchface.py --check +python -m unittest discover -s wear/watchfaces/material -p "test_*.py" -v +``` + +The builder creates a deterministic ZIP with the importer-required root entries `CustomWatchface.json` and `CustomWatchface.png`, plus the six SVGs and eight generated trend PNGs. It also writes `CustomWatchface.png`, `preview-states.png`, `preview-trends.png` and `preview-surfaces.png` here. The test suite uses the unchanged bundled AAPS V2 ZIP and the checkout's view/preference definitions to check the asset contract, compares ring positions/counts with the phone's AAPS 4 implementation, and checks all four matching-divider/theme combinations. + +**The previews use synthetic data and are not screenshots from an Android watch.** They use the source layout, bundled fonts and packaged trend-ring masks, but Android text metrics, loop icons and chart drawing are approximations. Do not use their sample readings for treatment decisions. + +## Use on the watch + +1. Keep `AAPS Material.zip` zipped and copy it into the `exports` folder of the AAPS directory selected on the phone. +2. In the phone's AAPS Wear screen, tap **Load Watchface** (**Watchface laden** in German) and select **AAPS Material (1.18)**. The selection sends it to the watch. To update an earlier copy, replace its ZIP in `exports` and import this version again. The button is shown only while AAPS reports a connected watch. +3. Select the existing **AAPS(Custom)** watchface on the watch if needed, and adjust its display settings. + +No APK rebuild is needed for this import path when the installed version supports the same CWF format. The ZIP is also included as a phone-app asset for future builds. Note: `FileListProviderImpl` loads bundled ZIPs only when no valid ZIPs exist in `exports`; adding an asset alone does not add it to an already populated import list. Copy the new ZIP to `exports` explicitly. + +This package uses the same legacy custom-watchface service as AAPS V2. It is **not** a new standalone Watch Face Format (WFF) APK and does not change `wear:watchfacepush`. Compatibility on watches that reject legacy faces is not established by these asset checks. + +## Verification before daily use + +The automated checks cover field parity, resource names, preference chains, text samples, round-screen chart bounds, palette contrast and archive consistency. They are static/design checks, not Android execution tests. + +On the actual watch, verify: + +- Round/square layout and readable text at its actual size; localized month and decimal formats. Check that the full day/month is visible, especially `OKT`/`OCT` and longer abbreviations, and that optional AM/PM stays clear of clock/date/delta text. +- mg/dL or mmol/L as configured, 12/24-hour time, date and every optional field toggle. +- Toggle **Querbalken farbgleich** in both dark and light modes: only the decorative surfaces should change; values, warnings and ring must remain visible. Check that the choice survives changing watch mode or reselecting the face. +- Normal/detailed IOB, larger and negative IOB values, long temporary-basal/rig-battery strings. +- High/low glucose, missing data, old readings, low phone battery and all loop states. +- Ring direction against the phone for flat, diagonal, up/down and double up/down; no highlighted direction for NONE; visibility toggle and light/dark tinting. Check the triple-trend limitation above. +- Chart history/treatments/basal settings, taps and the existing chart/action shortcuts. +- Ambient mode and the existing simplified-UI option; this package adds no new ambient-mode policy. + +No device installation, instrumented test or treatment-logic change is part of this work. See `TESTRESULTS.md` for the local verification record. + +Design reference: [Wear OS Material 3 Expressive color guidance](https://developer.android.com/design/ui/wear/guides/styles/color). + +Enable Show Reservoir Level in the watch settings to display the remaining pump insulin in the right pill. The value and warning colors come from AAPS. diff --git a/wear/watchfaces/material/Rig.svg b/wear/watchfaces/material/Rig.svg new file mode 100644 index 000000000000..ee23cb57cc7c --- /dev/null +++ b/wear/watchfaces/material/Rig.svg @@ -0,0 +1,4 @@ + + + + diff --git a/wear/watchfaces/material/TESTRESULTS.md b/wear/watchfaces/material/TESTRESULTS.md new file mode 100644 index 000000000000..1f7e27d2b1d5 --- /dev/null +++ b/wear/watchfaces/material/TESTRESULTS.md @@ -0,0 +1,75 @@ +# AAPS Material 1.11 verification + +Historical verification date: 2026-10-15. Local environment: Windows, Python with Pillow 12.1.1. Current project: [BernhardRo/AndroidAPS, branch `dev`](https://github.com/BernhardRo/AndroidAPS/tree/dev). See [integration verification](../README.md) for the later import checks. + +## Executed checks + +Commands ran from the AndroidAPS checkout root: + +| Check | Command | Result | +| --- | --- | --- | +| Build importable CWF asset and previews | `python wear/watchfaces/material/build_watchface.py` | Passed | +| Rebuild consistency | `python wear/watchfaces/material/build_watchface.py --check` | Passed; asset bytes match the sources | +| Static/design regression suite | `python -m unittest discover -s wear/watchfaces/material -p "test_*.py" -v` | 26 tests passed | +| Original face, Wear runtime and phone UI unchanged | `git diff --exit-code -- "plugins/configuration/src/main/assets/AAPS V2.zip" wear/src/main shared/impl/src/main plugins/sync/src/main ui/src/main` | Passed; no differences | + +The suite checks: + +- Live-field parity with the bundled AAPS V2 author version 1.0, excluding decorative free text and the added AM/PM indicator. +- CWF metadata version acceptance, ZIP structure, CRC, PNG preview decoding, deterministic packaging and asset/source equality. +- View/preference/font names against the checkout, preference-chain resolution, and label hiding. +- No live-value or preference overrides; no dynamic font steps masking native glucose/age/phone-battery warnings; no custom images masking native loop icons. +- 400 × 400 view bounds and the chart's four corners inside the trend ring's inner edge. +- Glucose at the top and the larger-font clock in the center; date to the right of the clock, below the rig battery; optional AM/PM in free space below the clock glyphs and left of the date; reading age beside glucose in the header. +- At least 4.5:1 contrast for primary/secondary card text, glucose range colors and clock text on both the hero surface and black/white background, and neutral battery/age text on black/white. +- Representative large, decimal, negative and detailed-IOB text widths and glyph heights using the bundled fonts, without shrinking the preview to conceal clipping; glucose, reading age, clock, day, German/English month and AM/PM sample glyph bounds inside the trend ring's inner edge. +- Day/month/AM-PM fields reserve full font line height plus four template pixels, including design checks at six zoom factors. This supplements visible-glyph tests; it is not an Android TextView test. +- Preview rendering for 96 combinations of dark/light, matching-divider on/off, normal/detailed IOB, 12/24-hour display and normal/mmol/high/low/stale/missing data, plus hidden-optional-fields cases with matching-divider on and off. +- Full-size native direction view, recognized `Arrow*.png` names, transparent white pixels for native tinting, highlighted segment at the correct angle, dim-only NONE resource and outward triangle geometry inside the display. +- Arc position, 40° sweep and triangle counts checked against the phone's `BgInfoSection.kt` for the seven distinguishable ordinary directions. +- Missing-reading previews cannot inherit a flat indicator; hiding the direction setting removes the ring for every sample trend in both themes. +- Direction-view preference mapping and native trend-resource selection checked against the checkout; circle stroke and arrowhead geometry stay inside the template's display boundary. +- Enlarged centerline diameter of 384 pixels with unchanged 5-pixel stroke and arrow tips at radius 197. +- Native `key_match_divider` mapping and its false default, all four theme/background combinations, and flat background SVG structure. +- Pixel samples from all seven decorative surfaces match black/white with the option on; glucose-header and outer-ring preview regions are unchanged between settings. Non-background text and palette rules stay identical and primary/secondary text retains at least 4.5:1 contrast on plain backgrounds. + +All preview sheets were rebuilt. `preview-states.png` and `preview-surfaces.png` were visually reviewed for version 1.11, including the optional AM/PM sample and matching-divider off/on in both themes. `preview-trends.png` was regenerated but not separately visually reviewed for this version; ring resources are byte-identical to version 1.10. These are explicitly labeled as synthetic-data design previews. Android drawing/tinting and its exact font metrics are not covered by these checks. + +Version 1.11 increases both date fields from 18 to 26 pixels tall, with the font unchanged at 18. Day starts at y=106 and month at y=132. Optional AM/PM moves below the clock and left of the date (x=250, y=144, width=34, height=22), keeping its 14-pixel font. Clock, glucose, ring, chart, remaining fields, palette, warning hooks and matching-divider behavior are unchanged. No native code or APK change is included. The clipping correction still needs user verification on the watch. + +The user's earlier packages (`AAPS Material_1_10.zip`, `AAPS Material 1_9.zip`, and `AAPS Material - Kopie.zip`) were preserved. Read-only comparison against the user's 1.10 ZIP confirmed changes only to JSON and the package preview. JSON changes are confined to `metadata`, `day`, `month` and `timePeriod`. All six SVGs and eight ring PNGs remain byte-identical. The new package is written to the standard `AAPS Material.zip` path. + +## User-reported clipped month + +The user supplied `Screenshot_20261015-114617.png`, a Samsung phone overview image, and reported that the month was clipped on the watch. The image shows the date area; the user separately confirmed that the ring is present on the watch despite being absent from that phone image. No treatment or glucose interpretation was made from the screenshot. + +Local measurements with the bundled font at size 18 give ascent 17 and descent 5, hence a 22-pixel line height. The earlier fields were only 18 pixels tall. The native renderer sets TextView size/font but does not disable its font padding. This supports insufficient field height as the likely cause; it is not a runtime measurement of the user's installed build. Earlier tests measured only visible glyph bounds and therefore did not catch this risk. The new regression test requires line-height reserve without reducing the date font. + +History: version 1.1 swapped clock/glucose positions and used a 64-pixel central clock. Version 1.2 restored their original positions and made the header clock larger than version 1.0. Version 1.3 added the AAPS-4-style outer trend ring and inset clock/date and chart bounds for it. Version 1.4 used 58-pixel clock and 68-pixel glucose text. Version 1.5 increased clock text to 64 pixels and reduced glucose to 60. Version 1.6 stacked the date to the right of the clock, slightly moved the clock and placed optional AM/PM below it. Version 1.7 reduced glucose text to 54 pixels. Version 1.8 put glucose at the top and time in the center, with their helper fields moved accordingly. Version 1.9 enlarged the ring diameter from 380 to 384 and shortened arrowheads from 6 to 4 pixels, keeping tip radius 197. Version 1.10 connected matching-divider to decorative surfaces, preserving text and palette colors. The chart remains 216 × 86 template pixels. Eight transparent arrow resources and the separate native loop-status icon are retained, with no Wear/app code or transport change. Synthetic strike-through still follows the glucose view's center. + +## User-reported missing ring: cause confirmed + +On 2026-10-15 the user identified their watch as a **Samsung Galaxy Watch 4**, then confirmed: the ring is now visible, and **Trendpfeil anzeigen had been switched off**. This resolves the reported visibility problem for that earlier ring. No code fix or diagnosis ZIP was needed. Installed phone/Wear builds remain unknown, and this report does not establish all trend states or version 1.9's larger ring as verified. + +Read-only code inspection confirmed: + +- `CustomWatchface.kt`: `zoomFactor` uses display width / 400; the native direction view follows `PrefMap.SHOW_DIRECTION`, selects the named arrow resources and uses native BG tinting. +- `ResFileMap.kt` / `ZipWatchfaceFormat.kt`: all eight packaged PNG names are recognized by this checkout's importer. +- `BaseWatchFace.kt` / `SimpleUi.kt`: simplified UI draws a separate glucose/time display rather than the custom layout and its ring resources. +- Version 1.9 geometry: circle diameter 384 in a 400-pixel template, stroke outer radius 194.5, arrowhead vertex radius at most 197. Template geometry is not runtime evidence. + +After confirming visibility, the user requested a slightly larger ring, added in version 1.9 and retained thereafter. In the later screenshot discussion, the user again confirmed that the ring is visible on the watch. No ring change was made for version 1.11. Native code and user settings remain untouched. The `1e-9` tolerance in geometry tests accounts for floating-point rounding; all 26 current tests passed. + +## Package + +- File: `plugins/configuration/src/main/assets/AAPS Material.zip` +- Size: 180,312 bytes +- SHA-256: `2aa57c3f42252433d5f7a08b9e99d846affbfddc59ea2b43416f39aeb5bae21c` + +## Not verified + +The agent performed no Android APK build, emulator/device rendering, on-device import, ambient-mode run, real data synchronization, touch interactions or battery-use measurement. No application was installed and no instrumented tests were run. The user's ring visibility confirmation is recorded above; it does not verify version 1.11, the corrected date fields, matching-divider switching or the complete on-watch checklist. The previews approximate Android text/icon/chart rendering and are not runtime evidence. + +Before daily use, carry out the actual-watch checklist in `README.md`. Device-specific legacy-watchface compatibility and unusually long basal/rig-battery strings remain open checks. The package is not a standalone WFF APK and does not modify the Wear OS Watch Face Push module. + +The baseline's triple-up/down transport ambiguity remains: both use `X`, which the existing CWF renderer resolves to the double-up resource. Therefore this asset does not establish parity with the phone's three-triangle indications. Check triple trends on the phone; see the limitation in `README.md`. diff --git a/wear/watchfaces/material/build_watchface.py b/wear/watchfaces/material/build_watchface.py new file mode 100644 index 000000000000..319834c9aae9 --- /dev/null +++ b/wear/watchfaces/material/build_watchface.py @@ -0,0 +1,339 @@ +"""Build a CWF asset and layout previews with synthetic data, not a Wear renderer.""" + +from __future__ import annotations + +import argparse +from functools import lru_cache +import io +import json +import math +from pathlib import Path +import xml.etree.ElementTree as ET +import zipfile + +from PIL import Image, ImageDraw, ImageFont + +SOURCE = Path(__file__).resolve().parent +ROOT = SOURCE.parents[2] +ASSET = ROOT / "plugins/configuration/src/androidMain/assets/AAPS Material.zip" +FONTS = ROOT / "wear/src/main/res/font" +STATIC_RESOURCES = ("MaterialDark.svg", "MaterialLight.svg", "MaterialDarkPlain.svg", "MaterialLightPlain.svg", "Phone.svg", "Rig.svg") +# Match the native default without changing a user's saved watch preference. +PREF_DEFAULTS = {"key_match_divider": False} +# Same positions and triangle counts as BgInfoSection.toArcIndicator for the +# seven directions that the existing CWF renderer can distinguish. +TREND_ARROWS = { + "ArrowNone": ("NONE", None, 0), + "ArrowFlat": ("FLAT", 0, 1), + "Arrow45Up": ("FORTY_FIVE_UP", -45, 1), + "ArrowSingleUp": ("SINGLE_UP", -90, 1), + "ArrowDoubleUp": ("DOUBLE_UP", -90, 2), + "Arrow45Down": ("FORTY_FIVE_DOWN", 45, 1), + "ArrowSingleDown": ("SINGLE_DOWN", 90, 1), + "ArrowDoubleDown": ("DOUBLE_DOWN", 90, 2), +} +RING_RADIUS = 190 +RING_STROKE = 7 +RING_ARROW_HEIGHT = 8 # Tips reach radius 198, leaving room inside the display edge. +RING_SWEEP = 40 +RING_TRACK_ALPHA = round(255 * 0.3) +RESOURCES = (*STATIC_RESOURCES, *(f"{name}.png" for name in TREND_ARROWS)) +VIEW_PREFS = { + "day": "key_show_date", "month": "key_show_date", + "sgv": "key_show_bg", "direction": "key_show_direction", + "timestamp": "key_show_ago", "loop": "key_show_loop_status", + "delta": "key_show_delta", "reservoir": "key_show_reservoir_level", + "uploader_battery": "key_show_uploader_battery", "rig_battery": "key_show_rig_battery", + "cob1": "key_show_cob", "cob2": "key_show_cob", + "iob1": "key_show_iob", "iob2": "key_show_iob", + "basalRate": "key_show_temp_basal", "bgi": "key_show_bgi", +} +SAMPLES = { + "time": "10:08", "day": "14", "month": "OCT", "sgv": "106", + "loop": "", "timestamp": "2'", "uploader_battery": "82%", "rig_battery": "67%", + "delta": "+3", "reservoir": "120 U", "cob1": "COB", "cob2": "18g", + "basalRate": "0.85U/h", "bgi": "-1.2", "iob1": "IOB", "iob2": "2.40", + "timePeriod": "AM", +} + + +def load_face() -> dict: + return json.loads((SOURCE / "CustomWatchface.json").read_text(encoding="utf-8")) + + +def resolve_pref(face: dict, key: str, prefs: dict) -> dict: + """Resolve the selected branches like CustomWatchface.buildDynPrefs.""" + result = {} + visited = set() + while key: + if key in visited: + raise ValueError(f"Preference cycle: {key}") + visited.add(key) + rule = face["dynPref"][key] + branch = rule[str(prefs.get(rule["prefKey"], PREF_DEFAULTS.get(rule["prefKey"], True))).lower()] + result.update({k: v for k, v in branch.items() if k != "dynPref"}) + key = branch.get("dynPref", "") + return result + + +def font_for(view: dict, size: int): + name = view.get("font", "roboto_condensed_regular") + return ImageFont.truetype(str(FONTS / f"{name}.ttf"), size) + + +def trend_triangles(name: str): + """Adapt AAPS 4's outward triangles to leave space at the display edge.""" + _, angle, count = TREND_ARROWS[name] + triangles = [] + half_base = RING_STROKE * 2 + height = RING_ARROW_HEIGHT + base_distance = RING_RADIUS + spacing = math.degrees(half_base * 1.6 / RING_RADIUS) + for index in range(count): + radians = math.radians(angle + (index - (count - 1) / 2) * spacing) + dx, dy = math.cos(radians), math.sin(radians) + base_x, base_y = 200 + base_distance * dx, 200 + base_distance * dy + triangles.append(((base_x + height * dx, base_y + height * dy), + (base_x - half_base * dy, base_y + half_base * dx), + (base_x + half_base * dy, base_y - half_base * dx))) + return triangles + + +def render_trend(name: str, scale=3): + """White/alpha bitmap: the native Wear renderer applies the live BG color.""" + _, angle, _ = TREND_ARROWS[name] + image = Image.new("RGBA", (400 * scale, 400 * scale)) + draw = ImageDraw.Draw(image) + # Pillow's stroke is inside the box; expand it by half a stroke to center it. + outer_radius = RING_RADIUS + RING_STROKE / 2 + box = tuple(n * scale for n in (200 - outer_radius, 200 - outer_radius, + 200 + outer_radius, 200 + outer_radius)) + draw.ellipse(box, outline=(255, 255, 255, RING_TRACK_ALPHA), width=RING_STROKE * scale) + if angle is not None: + start = (angle - RING_SWEEP / 2) % 360 + draw.arc(box, start, start + RING_SWEEP, fill="white", width=RING_STROKE * scale) + for end in (angle - RING_SWEEP / 2, angle + RING_SWEEP / 2): + radians = math.radians(end) + x = (200 + RING_RADIUS * math.cos(radians)) * scale + y = (200 + RING_RADIUS * math.sin(radians)) * scale + radius = RING_STROKE / 2 * scale + draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill="white") + for triangle in trend_triangles(name): + draw.polygon([(x * scale, y * scale) for x, y in triangle], fill="white") + return image + + +@lru_cache(maxsize=len(TREND_ARROWS)) +def trend_resource_bytes(name: str) -> bytes: + output = io.BytesIO() + render_trend(name).resize((400, 400), Image.Resampling.LANCZOS).save(output, format="PNG") + return output.getvalue() + + +def draw_svg(image, name: str, scale: int, origin=(0, 0)): + """Render our rectangle-only SVGs; reject additions this preview cannot show.""" + svg = ET.fromstring((SOURCE / name).read_bytes()) + draw = ImageDraw.Draw(image) + for node in svg: + if node.tag.split("}")[-1] != "rect": + raise ValueError("The preview supports only SVG rectangles") + x = (float(node.get("x", 0)) + origin[0]) * scale + y = (float(node.get("y", 0)) + origin[1]) * scale + box = (x, y, x + float(node.get("width")) * scale, y + float(node.get("height")) * scale) + fill = node.get("fill", "#000000") + draw.rounded_rectangle( + box, radius=float(node.get("rx", 0)) * scale, + fill=None if fill == "none" else fill, outline=node.get("stroke"), + width=max(1, round(float(node.get("stroke-width", 1)) * scale)), + ) + + +def draw_text(image, face: dict, key: str, text: str, prefs: dict, scale: int, color=None): + view = face[key] + style = resolve_pref(face, view["dynPref"], prefs) if "dynPref" in view else {} + text = style.get("textvalue1", view.get("textvalue", text)) + if not text: + return + size = int(style.get("textsize1", view.get("textsize", 22))) * scale + if size <= 0: + return + font = font_for(view, size) + color = color or style.get("fontColor1", view.get("fontColor", "#757575")) + x, y = view["leftmargin"] * scale, view["topmargin"] * scale + width, height = view["width"] * scale, view["height"] * scale + layer = Image.new("RGBA", (width, height)) + draw = ImageDraw.Draw(layer) + bounds = draw.textbbox((0, 0), text, font=font) + # Clip within the configured view. Do not shrink text to hide a sizing error. + tx = 0 if view.get("gravity") == "left" else (width - (bounds[2] - bounds[0])) / 2 + ty = (height - (bounds[3] - bounds[1])) / 2 - bounds[1] + draw.text((tx, ty), text, font=font, fill=color) + image.alpha_composite(layer, (x, y)) + + +def render(face: dict, *, dark=True, state="normal", detailed=False, hour12=False, prefs=None, trend="ArrowFlat"): + """Design preview only. Android text metrics, graph and icons may differ.""" + scale = 3 + values = dict(SAMPLES) + settings = {key: True for key in VIEW_PREFS.values()} + settings.update(PREF_DEFAULTS) + settings.update(key_dark=dark, key_show_detailed_iob=detailed) + settings.update(prefs or {}) + if detailed: + values.update(iob1="2.40", iob2="(1.60|0.80)") + if state == "mmol": + values.update(sgv="5.9", delta="+0.2", avg_delta="+0.1", bgi="-0.1") + elif state == "high": + values.update(sgv="248", delta="+8", avg_delta="+6.2") + elif state == "low": + values.update(sgv="58", delta="-4", avg_delta="-3.1") + elif state == "stale": + values.update(timestamp="18'", loop="", uploader_battery="12%") + elif state == "missing": + values.update(sgv="---", timestamp="--", loop="") + trend = "ArrowNone" + palette = resolve_pref(face, face["dynPrefColor"], settings) + bg_color = palette[{"high": "highColor", "low": "lowColor"}.get(state, "midColor")] + image = Image.new("RGBA", (400 * scale, 400 * scale)) + background = resolve_pref(face, face["background"]["dynPref"], settings)["image1"] + draw_svg(image, f"{background}.svg", scale) + + # Synthetic chart: show history, target grid, carbs and basal overlay. + chart = face["chart"] + x, y, w, h = (chart[k] for k in ("leftmargin", "topmargin", "width", "height")) + draw = ImageDraw.Draw(image) + for offset in (20, 45, 70): + draw.line([(x * scale, (y + offset) * scale), ((x + w) * scale, (y + offset) * scale)], + fill=palette["gridColor"], width=scale) + draw.rectangle((x * scale, (y + h - 13) * scale, (x + w) * scale, (y + h - 5) * scale), + fill=palette["basalBackgroundColor"]) + draw.line([(x * scale, (y + h - 10) * scale), ((x + w) * scale, (y + h - 10) * scale)], + fill=palette["basalCenterColor"], width=scale) + trace = (50, 54, 49, 39, 35, 38, 32, 29, 34, 37, 35, 32, 30) + points = [((x + i * (w - 12) / (len(trace) - 1) + 6) * scale, (y + n) * scale) for i, n in enumerate(trace)] + draw.line(points, fill=palette["midColor"], width=2 * scale) + for px, py in points: + draw.ellipse((px - 2 * scale, py - 2 * scale, px + 2 * scale, py + 2 * scale), fill=palette["midColor"]) + px, py = points[4] + draw.ellipse((px - 3 * scale, py - 9 * scale, px + 3 * scale, py - 3 * scale), fill=palette["carbColor"]) + graph_font = font_for({"font": "roboto_condensed_regular"}, 12 * scale) + for label, offset in (("−2h", 6), ("−1h", 94), ("now", w - 27)): + draw.text(((x + offset) * scale, (y + h - 1) * scale), label, font=graph_font, anchor="ls", fill=palette["gridColor"]) + + for key, view in face.items(): + if not isinstance(view, dict) or view.get("visibility") != "visible": + continue + if key in VIEW_PREFS and not settings[VIEW_PREFS[key]]: + continue + if key == "timePeriod" and not hour12: + continue + if "background" in view: + draw_svg(image, f"{view['background']}.svg", scale, (view["leftmargin"], view["topmargin"])) + if "textsize" in view: + color = bg_color if key == "sgv" else None + if key == "timestamp" and state in ("stale", "missing"): + color = "#E53935" + if key == "uploader_battery" and state == "stale": + color = palette["lowBatColor"] + if key == "loop": + bx, by = view["leftmargin"] * scale, view["topmargin"] * scale + bw, bh = view["width"] * scale, view["height"] * scale + loop_color = "#888888" if state == "missing" else "#CF0000" if state == "stale" else "#00CF00" + draw.arc((bx + scale, by + scale, bx + bw - scale, by + bh - scale), 25, 155, fill=loop_color, width=3 * scale) + draw.arc((bx + scale, by + scale, bx + bw - scale, by + bh - scale), 205, 335, fill=loop_color, width=3 * scale) + draw_text(image, face, key, values.get(key, ""), settings, scale, color) + if settings["key_show_direction"]: + # Preview the same generated bitmap/alpha mask that is packaged for Wear. + ring = Image.open(io.BytesIO(trend_resource_bytes(trend))).resize(image.size, Image.Resampling.LANCZOS) + tinted = Image.new("RGBA", ring.size, bg_color) + tinted.putalpha(ring.getchannel("A")) + image.alpha_composite(tinted) + if state == "stale" and settings["key_show_bg"]: + sgv = face["sgv"] + text_width = font_for(sgv, sgv["textsize"]).getlength(values["sgv"]) + center_x = sgv["leftmargin"] + sgv["width"] / 2 + center_y = sgv["topmargin"] + sgv["height"] / 2 + draw.line([((center_x - text_width / 2) * scale, center_y * scale), + ((center_x + text_width / 2) * scale, center_y * scale)], + fill=bg_color, width=3 * scale) + mask = Image.new("L", image.size) + ImageDraw.Draw(mask).ellipse((0, 0, 400 * scale - 1, 400 * scale - 1), fill=255) + image.putalpha(mask) + return image.resize((400, 400), Image.Resampling.LANCZOS) + + +def archive_bytes(face: dict) -> bytes: + preview = io.BytesIO() + render(face).save(preview, format="PNG") + files = {"CustomWatchface.json": (SOURCE / "CustomWatchface.json").read_bytes(), + "CustomWatchface.png": preview.getvalue()} + files.update({name: (SOURCE / name).read_bytes() for name in STATIC_RESOURCES}) + files.update({f"{name}.png": trend_resource_bytes(name) for name in TREND_ARROWS}) + output = io.BytesIO() + with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for name, data in sorted(files.items()): + entry = zipfile.ZipInfo(name, (2026, 10, 14, 0, 0, 0)) + entry.compress_type = zipfile.ZIP_DEFLATED + entry.external_attr = 0o644 << 16 + archive.writestr(entry, data) + return output.getvalue() + + +def write_previews(face: dict): + render(face).save(SOURCE / "CustomWatchface.png") + sheet = Image.new("RGB", (1280, 948), "#101713") + draw = ImageDraw.Draw(sheet) + heading = font_for({}, 24) + draw.text((28, 14), "AAPS MATERIAL / DESIGN PREVIEW / SYNTHETIC DATA", font=heading, fill="#F0F5F1") + states = (("Dark · flat", {}), ("Light · mmol/L · rising", {"dark": False, "state": "mmol", "trend": "Arrow45Up"}), + ("Detailed IOB · double up", {"detailed": True, "hour12": True, "trend": "ArrowDoubleUp"}), + ("High · rising", {"state": "high", "trend": "ArrowSingleUp"}), ("Low · falling", {"state": "low", "trend": "ArrowSingleDown"}), + ("Stale · low phone battery", {"state": "stale"})) + for index, (label, kwargs) in enumerate(states): + x, y = 24 + (index % 3) * 420, 56 + (index // 3) * 444 + draw.text((x + 8, y), label, font=heading, fill="#BAC8BF") + preview = render(face, **kwargs) + sheet.paste(preview, (x, y + 32), preview) + sheet.save(SOURCE / "preview-states.png") + trend_sheet = Image.new("RGB", (1704, 948), "#101713") + draw = ImageDraw.Draw(trend_sheet) + draw.text((28, 14), "AAPS MATERIAL / TREND RING / SYNTHETIC DATA", font=heading, fill="#F0F5F1") + for index, name in enumerate(TREND_ARROWS): + x, y = 24 + (index % 4) * 420, 56 + (index // 4) * 444 + label = TREND_ARROWS[name][0].replace("_", " ") + draw.text((x + 8, y), label, font=heading, fill="#BAC8BF") + preview = render(face, trend=name) + trend_sheet.paste(preview, (x, y + 32), preview) + trend_sheet.save(SOURCE / "preview-trends.png") + surface_sheet = Image.new("RGB", (864, 948), "#101713") + draw = ImageDraw.Draw(surface_sheet) + draw.text((28, 14), "MATCHING DIVIDER / SYNTHETIC DATA", font=heading, fill="#F0F5F1") + states = (("Dark / OFF / Material", True, False), ("Dark / ON / plain", True, True), + ("Light / OFF / Material", False, False), ("Light / ON / plain", False, True)) + for index, (label, dark, matching) in enumerate(states): + x, y = 24 + (index % 2) * 420, 56 + (index // 2) * 444 + draw.text((x + 8, y), label, font=heading, fill="#BAC8BF") + preview = render(face, dark=dark, prefs={"key_match_divider": matching}) + surface_sheet.paste(preview, (x, y + 32), preview) + surface_sheet.save(SOURCE / "preview-surfaces.png") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="Check the committed asset without writing files") + args = parser.parse_args() + face = load_face() + package = archive_bytes(face) + if args.check: + if not ASSET.exists() or ASSET.read_bytes() != package: + raise SystemExit("AAPS Material.zip is missing or stale. Run the builder.") + print("Asset matches its source files.") + return + ASSET.write_bytes(package) + write_previews(face) + print(f"Created {ASSET}") + print(f"Design previews: {SOURCE / 'preview-states.png'}") + + +if __name__ == "__main__": + main() diff --git a/wear/watchfaces/material/preview-states.png b/wear/watchfaces/material/preview-states.png new file mode 100644 index 000000000000..e7c9ed859a0e Binary files /dev/null and b/wear/watchfaces/material/preview-states.png differ diff --git a/wear/watchfaces/material/preview-surfaces.png b/wear/watchfaces/material/preview-surfaces.png new file mode 100644 index 000000000000..80521f3501fc Binary files /dev/null and b/wear/watchfaces/material/preview-surfaces.png differ diff --git a/wear/watchfaces/material/preview-trends.png b/wear/watchfaces/material/preview-trends.png new file mode 100644 index 000000000000..8ff737a3a072 Binary files /dev/null and b/wear/watchfaces/material/preview-trends.png differ diff --git a/wear/watchfaces/material/requirements.txt b/wear/watchfaces/material/requirements.txt new file mode 100644 index 000000000000..96fb13d9cfee --- /dev/null +++ b/wear/watchfaces/material/requirements.txt @@ -0,0 +1 @@ +Pillow==12.1.1 diff --git a/wear/watchfaces/material/test_watchface.py b/wear/watchfaces/material/test_watchface.py new file mode 100644 index 000000000000..2ce2652ac8dc --- /dev/null +++ b/wear/watchfaces/material/test_watchface.py @@ -0,0 +1,403 @@ +"""Static CWF contract checks. These do not replace testing on a watch.""" + +import io +import itertools +import json +import math +import re +import unittest +import xml.etree.ElementTree as ET +import zipfile + +from PIL import Image + +import build_watchface as build + + +def strict_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate key: {key}") + result[key] = value + return result + + +def contrast(first, second): + def luminance(color): + channels = [int(color[n:n + 2], 16) / 255 for n in (1, 3, 5)] + channels = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in channels] + return sum(a * b for a, b in zip(channels, (0.2126, 0.7152, 0.0722))) + low, high = sorted((luminance(first), luminance(second))) + return (high + 0.05) / (low + 0.05) + + +class MaterialWatchfaceTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.face = json.loads((build.SOURCE / "CustomWatchface.json").read_text(encoding="utf-8"), object_pairs_hook=strict_object) + with zipfile.ZipFile(build.ROOT / "plugins/configuration/src/androidMain/assets/AAPS V2.zip") as archive: + cls.reference = json.loads(archive.read("CustomWatchface.json")) + + def test_same_live_fields_as_aaps_v2(self): + def visible(face): + return {k for k, v in face.items() if isinstance(v, dict) and v.get("visibility") == "visible" + and k not in {"background", "freetext1", "freetext2", "freetext3", "freetext4", "timePeriod"}} + self.assertEqual(self.reference["metadata"]["name"], "AAPS V2") + self.assertEqual(self.reference["metadata"]["author_version"], "1.0") + self.assertEqual((visible(self.reference) - {"avg_delta"}) | {"reservoir"}, visible(self.face)) + self.assertEqual(self.reference["pointSize"], self.face["pointSize"]) + self.assertEqual(self.reference["enableSecond"], self.face["enableSecond"]) + + def test_no_live_value_or_preference_override(self): + metadata_keys = set(self.face["metadata"]) + self.assertFalse(any(k.startswith("key_") or k == "cwf_authorization" for k in metadata_keys)) + for key in build.VIEW_PREFS | {"time": "", "timePeriod": ""}: + with self.subTest(key=key): + view = self.face[key] + self.assertNotIn("textvalue", view) + self.assertNotIn("dynValue", view) + self.assertNotIn("dynData", view) + for dark, detailed in itertools.product((True, False), repeat=2): + style = build.resolve_pref(self.face, view["dynPref"], {"key_dark": dark, "key_show_detailed_iob": detailed}) if "dynPref" in view else {} + self.assertFalse(any(k.startswith("textvalue") for k in style)) + + def test_metadata_version_passes_current_import_check(self): + interface = build.ROOT / "core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata" + supported = re.search(r'CUSTOM_VERSION = "([^"]+)"', (interface / "ResFormat.kt").read_text(encoding="utf-8")).group(1) + app_version = [int(n) for n in supported.split(".")] + face_version = [int(n) for n in self.face["metadata"]["cwf_version"].split(".")] + self.assertGreaterEqual(len(app_version), 2) + self.assertGreaterEqual(len(face_version), 2) + self.assertGreaterEqual(app_version[0], face_version[0]) + + def test_native_warning_hooks_not_masked(self): + # CustomWatchface skips native age/battery/SGV warnings if stepFontColor > 0. + for key in ("sgv", "direction", "timestamp", "uploader_battery"): + self.assertNotIn("dynPref", self.face[key], key) + self.assertNotIn("dynData", self.face[key], key) + # Loop colors still come from the native grey/green/red background icons. + loop = self.face["loop"] + self.assertNotIn("background", loop) + for dark in (True, False): + style = build.resolve_pref(self.face, loop["dynPref"], {"key_dark": dark}) + self.assertFalse(any(k.startswith("image") for k in style)) + + def test_all_names_and_preferences_exist_in_renderer(self): + shared = build.ROOT / "shared/impl/src/commonMain/kotlin/app/aaps/shared/impl/weardata" + symbols = {key: symbol for symbol, key in re.findall(r'\b([A-Z0-9_]+)\("([^"]+)"', (build.ROOT / "shared/impl/src/androidMain/kotlin/app/aaps/shared/impl/weardata/ViewKeys.kt").read_text(encoding="utf-8"))} + renderer = (build.ROOT / "wear/src/main/kotlin/app/aaps/wear/watchfaces/CustomWatchface.kt").read_text(encoding="utf-8") + pref_keys = set(re.findall(r'\("([^"]+)"', (shared / "JsonKeyValues.kt").read_text(encoding="utf-8"))) + metadata = (build.ROOT / "core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/CwfMetaDataKey.kt").read_text(encoding="utf-8") + pref_keys.update(re.findall(r'\("(key_[^"]+)"', metadata)) + for key, view in self.face.items(): + if isinstance(view, dict) and "width" in view: + self.assertIn(key, symbols) + self.assertIn(f"ViewKeys.{symbols[key]}.key", renderer) + if "dynPref" in view: + self.assertIn(view["dynPref"], self.face["dynPref"]) + if "font" in view: + self.assertTrue((build.FONTS / f"{view['font']}.ttf").exists()) + for rule in self.face["dynPref"].values(): + self.assertIn(rule["prefKey"], pref_keys) + + def test_view_bounds_and_round_safe_chart(self): + for key, view in self.face.items(): + if isinstance(view, dict) and "width" in view: + self.assertGreater(view["width"], 0, key) + self.assertGreater(view["height"], 0, key) + self.assertGreaterEqual(view["leftmargin"], 0, key) + self.assertGreaterEqual(view["topmargin"], 0, key) + self.assertLessEqual(view["leftmargin"] + view["width"], 400, key) + self.assertLessEqual(view["topmargin"] + view["height"], 400, key) + chart = self.face["chart"] + for x in (chart["leftmargin"], chart["leftmargin"] + chart["width"]): + for y in (chart["topmargin"], chart["topmargin"] + chart["height"]): + self.assertLess(math.hypot(x - 200, y - 200), build.RING_RADIUS - build.RING_STROKE / 2) + + def test_theme_steps_have_a_valid_nonmedical_value(self): + # NONE has a zero-length range in DynProvider; a lone '*1' entry would not work. + # Calendar day is always valid, independent of missing or stale glucose data. + for dark, detailed in itertools.product((True, False), repeat=2): + prefs = {"key_dark": dark, "key_show_detailed_iob": detailed} + for key in self.face["dynPref"]: + style = build.resolve_pref(self.face, key, prefs) + if any(re.search(r"\d$", k) for k in style): + self.assertEqual(style.get("valueKey"), "day", key) + + def test_free_labels_follow_visibility_preferences(self): + for label, pref in (("freetext1", "key_show_delta"), ("freetext2", "key_show_reservoir_level"), + ("freetext3", "key_show_temp_basal"), ("freetext4", "key_show_bgi")): + for dark in (True, False): + rule = self.face[label]["dynPref"] + hidden = build.resolve_pref(self.face, rule, {pref: False, "key_dark": dark}) + shown = build.resolve_pref(self.face, rule, {pref: True, "key_dark": dark}) + self.assertEqual(hidden["textvalue1"], "") + self.assertNotIn("textvalue1", shown) + + def test_normal_and_warning_color_contrast(self): + for dark, surface, hero in ((True, "#1B241F", "#14271F"), (False, "#E6EFE8", "#D7F5E6")): + settings = {"key_dark": dark} + for rule in ("primary", "secondary"): + self.assertGreaterEqual(contrast(build.resolve_pref(self.face, rule, settings)["fontColor1"], surface), 4.5) + palette = build.resolve_pref(self.face, "palette", settings) + background = "#000000" if dark else "#FFFFFF" + for key in ("midColor", "highColor", "lowColor"): + self.assertGreaterEqual(contrast(palette[key], hero), 4.5) + self.assertGreaterEqual(contrast(palette[key], background), 4.5) + time_color = build.resolve_pref(self.face, self.face["time"]["dynPref"], settings)["fontColor1"] + self.assertGreaterEqual(contrast(time_color, background), 4.5) + self.assertGreaterEqual(contrast(time_color, hero), 4.5) + self.assertGreaterEqual(contrast("#757575", background), 4.5) + + def test_header_glucose_and_central_clock_keep_their_helpers(self): + time, sgv = self.face["time"], self.face["sgv"] + day, month = self.face["day"], self.face["month"] + # Date is stacked to the right of the clock, clear of the rig battery. + for view in (day, month): + self.assertGreaterEqual(view["leftmargin"], time["leftmargin"] + time["width"]) + self.assertGreaterEqual(view["topmargin"], time["topmargin"]) + self.assertLessEqual(view["topmargin"] + view["height"], time["topmargin"] + time["height"]) + self.assertGreaterEqual(view["topmargin"], self.face["rig_battery"]["topmargin"] + self.face["rig_battery"]["height"]) + self.assertEqual(day["leftmargin"], month["leftmargin"]) + self.assertLessEqual(day["topmargin"] + day["height"], month["topmargin"]) + self.assertLessEqual(sgv["topmargin"] + sgv["height"], time["topmargin"] + time["height"] / 2) + self.assertEqual((sgv["leftmargin"], sgv["topmargin"], sgv["width"], sgv["height"]), (114, 18, 160, 74)) + self.assertEqual((time["leftmargin"], time["topmargin"], time["width"], time["height"]), (113, 83, 174, 80)) + self.assertGreater(time["textsize"], 42) + self.assertGreater(time["textsize"], sgv["textsize"]) + self.assertEqual(time["textsize"], 64) + self.assertEqual(sgv["textsize"], 54) + age = self.face["timestamp"] + loop = self.face["loop"] + self.assertEqual((age["leftmargin"], age["topmargin"], age["width"], age["height"]), + (loop["leftmargin"], loop["topmargin"], loop["width"], loop["height"])) + self.assertEqual(loop["textsize"], 0) + self.assertEqual(self.face["delta"]["topmargin"], self.face["reservoir"]["topmargin"]) + period = self.face["timePeriod"] + # AM/PM uses free space below the clock glyphs, left of the taller date. + self.assertLessEqual(period["leftmargin"] + period["width"], day["leftmargin"]) + time_bounds = build.font_for(time, time["textsize"]).getbbox("23:59") + period_bounds = build.font_for(period, period["textsize"]).getbbox("PM") + time_bottom = time["topmargin"] + time["height"] / 2 + (time_bounds[3] - time_bounds[1]) / 2 + period_top = period["topmargin"] + period["height"] / 2 - (period_bounds[3] - period_bounds[1]) / 2 + self.assertGreater(period_top, time_bottom) + self.assertLessEqual(period["topmargin"] + period["height"], self.face["reservoir"]["topmargin"]) + + def test_date_helpers_allow_full_font_line_height_and_extra_space(self): + # Glyph bounds alone missed the 1.10 clipping. Reserve a full font line + # plus four template pixels for platform font padding. This remains a + # design check, not a measurement of Android's actual TextView metrics. + for key, textsize, height in (("day", 18, 26), ("month", 18, 26), ("timePeriod", 14, 22)): + view = self.face[key] + self.assertEqual(view["textsize"], textsize) + self.assertEqual(view["height"], height) + self.assertGreaterEqual(view["height"], sum(build.font_for(view, textsize).getmetrics()) + 4) + for zoom in (0.9, 0.99, 1.0, 1.125, 1.2, 1.5): + with self.subTest(key=key, zoom=zoom): + # Use high-resolution metrics to avoid whole-font-size rounding. + font = build.font_for(view, round(textsize * zoom * 100)) + line_height = sum(font.getmetrics()) / 100 + self.assertGreaterEqual(int(view["height"] * zoom), line_height + 4 * zoom) + + def test_representative_text_fits_without_auto_shrinking(self): + cases = {"time": ("23:59", "10:08", "12:59"), "day": ("1", "14", "31"), + "month": ("JAN", "FEB", "MÄR", "APR", "MAI", "JUN", "JUL", "AUG", "SEP", "SEPT", "OKT", "OCT", "NOV", "DEZ"), + "timePeriod": ("AM", "PM"), "sgv": ("106", "400", "22.2", "---"), + "delta": ("+12.3", "-12.3"), "reservoir": ("120 U", "200 U", "300 U"), + "timestamp": ("18'", "60'"), "uploader_battery": ("100%",), + "cob2": ("120g",), "basalRate": ("0.85U/h", "120%"), + "bgi": ("-12.3",), "iob1": ("IOB", "12.34"), "iob2": ("12.34", "(1.60|0.80)", "(-10.00|10.00)")} + for detailed in (True, False): + for key, samples in cases.items(): + view = self.face[key] + style = build.resolve_pref(self.face, view["dynPref"], {"key_show_detailed_iob": detailed}) if "dynPref" in view else {} + font = build.font_for(view, style.get("textsize1", view["textsize"])) + for text in samples: + if key == "iob2" and text.startswith("(") and not detailed: + continue + with self.subTest(key=key, text=text, detailed=detailed): + self.assertLessEqual(font.getlength(text), view["width"]) + bounds = font.getbbox(text) + self.assertLessEqual(bounds[3] - bounds[1], view["height"]) + if key in ("time", "sgv", "timestamp", "day", "month", "timePeriod"): + center_x = view["leftmargin"] + view["width"] / 2 + center_y = view["topmargin"] + view["height"] / 2 + for x in (center_x - font.getlength(text) / 2, center_x + font.getlength(text) / 2): + for y in (center_y - (bounds[3] - bounds[1]) / 2, center_y + (bounds[3] - bounds[1]) / 2): + self.assertLess(math.hypot(x - 200, y - 200), build.RING_RADIUS - build.RING_STROKE / 2) + + def test_archive_contract_and_resources(self): + package = build.archive_bytes(self.face) + self.assertEqual(package, build.archive_bytes(self.face)) + with zipfile.ZipFile(io.BytesIO(package)) as archive: + self.assertIsNone(archive.testzip()) + self.assertEqual(set(archive.namelist()), {"CustomWatchface.json", "CustomWatchface.png", *build.RESOURCES}) + self.assertEqual(json.loads(archive.read("CustomWatchface.json")), self.face) + preview = Image.open(io.BytesIO(archive.read("CustomWatchface.png"))) + self.assertEqual(preview.size, (400, 400)) + preview.verify() + resources = {name.removesuffix(".svg") for name in build.RESOURCES} + for rule in self.face["dynPref"].values(): + for branch in (rule["true"], rule["false"]): + if "image1" in branch: + self.assertIn(branch["image1"], resources) + for view in self.face.values(): + if isinstance(view, dict) and "background" in view: + self.assertIn(view["background"], resources) + for name in build.STATIC_RESOURCES: + self.assertTrue(ET.fromstring(archive.read(name)).tag.endswith("svg")) + res_map = (build.ROOT / "shared/impl/src/commonMain/kotlin/app/aaps/shared/impl/weardata/ResFileMap.kt").read_text(encoding="utf-8") + for name in build.TREND_ARROWS: + self.assertIn(f'("{name}")', res_map) + self.assertEqual(archive.read(f"{name}.png"), build.trend_resource_bytes(name)) + + def test_previews_render_missing_and_optional_states(self): + for dark, detailed, hour12, matching in itertools.product((True, False), repeat=4): + for state in ("normal", "mmol", "high", "low", "stale", "missing"): + self.assertEqual(build.render(self.face, dark=dark, detailed=detailed, hour12=hour12, state=state, + prefs={"key_match_divider": matching}).size, (400, 400)) + hidden = {key: False for key in build.VIEW_PREFS.values()} + for matching in (True, False): + self.assertEqual(build.render(self.face, prefs=hidden | {"key_match_divider": matching}).size, (400, 400)) + + def test_matching_divider_selects_the_four_background_resources(self): + renderer = (build.ROOT / "wear/src/main/kotlin/app/aaps/wear/watchfaces/CustomWatchface.kt").read_text(encoding="utf-8") + self.assertIn("PREF_MATCH_DIVIDER(JsonKeyValues.PREF_MATCH_DIVIDER.key, R.string.key_match_divider, false, true, R.string.pref_matching_divider)", renderer) + surface = self.face["background"]["dynPref"] + self.assertEqual(self.face["dynPref"][surface]["prefKey"], "key_match_divider") + for dark, matching in itertools.product((True, False), repeat=2): + expected = f"Material{'Dark' if dark else 'Light'}{'Plain' if matching else ''}" + rule = build.resolve_pref(self.face, surface, {"key_dark": dark, "key_match_divider": matching}) + self.assertEqual(rule, {"valueKey": "day", "image1": expected}) + self.assertIn(f"{expected}.svg", build.RESOURCES) + self.assertFalse(build.PREF_DEFAULTS["key_match_divider"]) + self.assertEqual(build.resolve_pref(self.face, surface, {"key_dark": True})["image1"], "MaterialDark") + self.assertEqual(build.resolve_pref(self.face, surface, {"key_dark": False})["image1"], "MaterialLight") + + def test_plain_surfaces_only_contain_the_full_screen_background(self): + for name, color in (("MaterialDarkPlain.svg", "#000000"), ("MaterialLightPlain.svg", "#FFFFFF")): + svg = ET.fromstring((build.SOURCE / name).read_bytes()) + self.assertEqual((svg.get("width"), svg.get("height")), ("400", "400")) + self.assertEqual(len(svg), 1) + self.assertTrue(svg[0].tag.endswith("rect")) + self.assertEqual(svg[0].attrib, {"width": "400", "height": "400", "fill": color}) + + def test_matching_divider_does_not_change_text_or_warning_styles(self): + for dark, detailed in itertools.product((True, False), repeat=2): + off = {"key_dark": dark, "key_show_detailed_iob": detailed, "key_match_divider": False} + on = off | {"key_match_divider": True} + for key, view in self.face.items(): + if key != "background" and isinstance(view, dict) and "dynPref" in view: + self.assertEqual(build.resolve_pref(self.face, view["dynPref"], off), build.resolve_pref(self.face, view["dynPref"], on), key) + self.assertEqual(build.resolve_pref(self.face, "palette", off), build.resolve_pref(self.face, "palette", on)) + background = "#000000" if dark else "#FFFFFF" + for rule in ("primary", "secondary"): + self.assertGreaterEqual(contrast(build.resolve_pref(self.face, rule, on)["fontColor1"], background), 4.5) + + def test_matching_divider_removes_surfaces_but_keeps_header_and_ring(self): + # Sample empty parts of each tonal surface, not the text or chart strokes. + points = ((120, 100), (40, 182), (360, 182), (60, 211), (150, 211), (275, 211), (90, 303)) + for dark in (True, False): + off = build.render(self.face, dark=dark, prefs={"key_match_divider": False}) + on = build.render(self.face, dark=dark, prefs={"key_match_divider": True}) + background = (0, 0, 0, 255) if dark else (255, 255, 255, 255) + for point in points: + self.assertEqual(on.getpixel(point), background, (dark, point)) + self.assertNotEqual(off.getpixel(point), background, (dark, point)) + for box in ((114, 18, 274, 80), (0, 0, 25, 400), (375, 0, 400, 400)): + self.assertEqual(off.crop(box).tobytes(), on.crop(box).tobytes()) + + def test_packaged_asset_is_current(self): + self.assertEqual(build.ASSET.read_bytes(), build.archive_bytes(self.face)) + + def test_ring_is_a_native_full_size_direction_view(self): + view = self.face["direction"] + self.assertEqual((view["width"], view["height"], view["leftmargin"], view["topmargin"]), (400, 400, 0, 0)) + # Native TrendArrowMap chooses the named PNG, and native colorFilter tints it. + self.assertNotIn("rotation", view) + self.assertNotIn("color", view) + self.assertNotIn("dynData", view) + self.assertNotIn("dynPref", view) + + def test_ring_visibility_is_controlled_by_the_native_direction_preference(self): + renderer = (build.ROOT / "wear/src/main/kotlin/app/aaps/wear/watchfaces/CustomWatchface.kt").read_text(encoding="utf-8") + self.assertIn("DIRECTION(ViewKeys.DIRECTION.key, R.id.direction, PrefMap.SHOW_DIRECTION)", renderer) + self.assertIn("binding.direction.setImageDrawable(TrendArrowMap.drawable(singleBg[0]))", renderer) + self.assertEqual(self.face["direction"]["visibility"], "visible") + self.assertEqual(build.VIEW_PREFS["direction"], "key_show_direction") + self.assertNotIn("key_show_direction", self.face["metadata"]) + + def test_ring_and_arrowheads_have_display_edge_clearance(self): + # Static template geometry only; this cannot prove a watch's runtime viewport. + self.assertLess(build.RING_RADIUS + build.RING_STROKE / 2, 200) + for name in build.TREND_ARROWS: + for triangle in build.trend_triangles(name): + for x, y in triangle: + self.assertLessEqual(math.hypot(x - 200, y - 200), 198.4 + 1e-9) + + def test_thicker_ring_and_arrowheads_fit_the_display(self): + self.assertEqual(build.RING_RADIUS * 2, 380) + self.assertEqual(build.RING_STROKE, 7) + self.assertAlmostEqual(build.RING_RADIUS + build.RING_ARROW_HEIGHT, 198) + for name, (_, _, count) in build.TREND_ARROWS.items(): + tips = [triangle[0] for triangle in build.trend_triangles(name)] + self.assertEqual(len(tips), count) + for x, y in tips: + self.assertAlmostEqual(math.hypot(x - 200, y - 200), 198) + + def test_ring_matches_aaps4_arc_positions_and_counts(self): + source = (build.ROOT / "ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/BgInfoSection.kt").read_text(encoding="utf-8") + native = {key: (float(angle), int(count)) for key, angle, count in + re.findall(r'TrendArrow\.(\w+)\s*-> ArcIndicator\(centerAngle = (-?[\d.]+)f, sweepAngle = sweepAngle, triangleCount = (\d+)\)', source)} + self.assertEqual(build.RING_SWEEP, float(re.search(r'val sweepAngle = ([\d.]+)f', source).group(1))) + for name, (key, angle, count) in build.TREND_ARROWS.items(): + with self.subTest(name=name): + if key == "NONE": + self.assertIsNone(angle) + self.assertEqual(count, 0) + else: + self.assertEqual((angle, count), native[key]) + triangles = build.trend_triangles(name) + self.assertEqual(len(triangles), count) + for triangle in triangles: + for x, y in triangle: + self.assertLess(math.hypot(x - 200, y - 200), 200) + self.assertGreater(math.hypot(x - 200, y - 200), build.RING_RADIUS) + + def test_ring_pngs_are_transparent_white_and_have_correct_highlight(self): + for name, (_, angle, _) in build.TREND_ARROWS.items(): + with self.subTest(name=name): + image = Image.open(io.BytesIO(build.trend_resource_bytes(name))) + self.assertEqual(image.mode, "RGBA") + self.assertEqual(image.size, (400, 400)) + self.assertEqual(image.getpixel((200, 200))[3], 0) + for point in ((0, 0), (399, 0), (0, 399), (399, 399)): + self.assertEqual(image.getpixel(point)[3], 0) + self.assertTrue(all((r, g, b) == (255, 255, 255) for r, g, b, a in image.get_flattened_data() if a)) + if angle is None: + self.assertLess(image.getchannel("A").getextrema()[1], 100) + else: + def point(degrees): + radians = math.radians(degrees) + return (round(200 + build.RING_RADIUS * math.cos(radians)), + round(200 + build.RING_RADIUS * math.sin(radians))) + self.assertGreater(image.getpixel(point(angle))[3], 200) + self.assertLess(image.getpixel(point(angle + 180))[3], 100) + + def test_ring_visibility_and_missing_trend_are_not_flat(self): + for dark in (True, False): + none = build.render(self.face, dark=dark, trend="ArrowNone") + flat = build.render(self.face, dark=dark, trend="ArrowFlat") + self.assertNotEqual(none.tobytes(), flat.tobytes()) + # A missing reading must not inherit the selected sample trend. + self.assertEqual(build.render(self.face, dark=dark, state="missing", trend="ArrowFlat").tobytes(), + build.render(self.face, dark=dark, state="missing", trend="ArrowNone").tobytes()) + hidden = {"key_show_direction": False} + for name in build.TREND_ARROWS: + self.assertEqual(build.render(self.face, dark=dark, trend=name, prefs=hidden).tobytes(), + build.render(self.face, dark=dark, trend="ArrowNone", prefs=hidden).tobytes()) + + +if __name__ == "__main__": + unittest.main() diff --git a/wear/watchfaces/sport/.gitignore b/wear/watchfaces/sport/.gitignore new file mode 100644 index 000000000000..c18dd8d83cee --- /dev/null +++ b/wear/watchfaces/sport/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/wear/watchfaces/sport/CustomWatchface.json b/wear/watchfaces/sport/CustomWatchface.json new file mode 100644 index 000000000000..7eb17e91b54d --- /dev/null +++ b/wear/watchfaces/sport/CustomWatchface.json @@ -0,0 +1,200 @@ +{ + "metadata": { + "name": "AAPS Sport", + "author": "OpenCode", + "created_at": "16/10/2026", + "author_version": "1.18", + "cwf_version": "1.0", + "comment": "Digital sport dashboard. Lower-right light-blue reservoir gauge: 0-200 U, 4 U steps. Native basal text, COB, IOB, trend and warning hooks. Three configurable system complication slots. No chart or app changes." + }, + "enableSecond": false, + "pointSize": 2, + "highColor": "#FFD166", + "midColor": "#B5F46A", + "lowColor": "#FF727C", + "reservoirColor": "#65DEED", + "background": { + "width": 400, "height": 400, "leftmargin": 0, "topmargin": 0, + "visibility": "visible" + }, + "complication1": { + "width": 76, "height": 32, "leftmargin": 162, "topmargin": 4, + "visibility": "visible" + }, + "complication2": { + "width": 40, "height": 40, "leftmargin": 20, "topmargin": 120, + "visibility": "visible" + }, + "complication3": { + "width": 40, "height": 40, "leftmargin": 340, "topmargin": 120, + "visibility": "visible" + }, + "chart": { + "width": 1, "height": 1, "leftmargin": 200, "topmargin": 200, + "visibility": "gone" + }, + "cover_chart": { + "width": 208, "height": 208, "leftmargin": 192, "topmargin": 192, + "visibility": "visible", "dynPref": "reservoirGauge" + }, + "direction": { + "width": 146, "height": 146, "leftmargin": 59, "topmargin": 24, + "visibility": "visible" + }, + "freetext1": { + "width": 72, "height": 20, "leftmargin": 96, "topmargin": 49, + "visibility": "visible", "textsize": 12, "gravity": "center", + "font": "roboto_condensed_regular", "fontColor": "#ABB8C2", "dynPref": "glucoseUnits" + }, + "sgv": { + "width": 110, "height": 54, "leftmargin": 77, "topmargin": 65, + "visibility": "visible", "textsize": 40, "gravity": "center", + "font": "roboto_condensed_bold", "fontStyle": "normal" + }, + "timestamp": { + "width": 44, "height": 44, "leftmargin": 246, "topmargin": 104, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#FFFFFF" + }, + "delta": { + "width": 60, "height": 28, "leftmargin": 102, "topmargin": 116, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#ABB8C2" + }, + "freetext2": { + "width": 140, "height": 22, "leftmargin": 198, "topmargin": 40, + "visibility": "visible", "textsize": 12, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#65DEED", "dynPref": "basalLabel" + }, + "basalRate": { + "width": 140, "height": 30, "leftmargin": 198, "topmargin": 62, + "visibility": "visible", "textsize": 20, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#65DEED" + }, + "iob1": { + "width": 88, "height": 44, "leftmargin": 252, "topmargin": 286, + "visibility": "visible", "textsize": 32, "gravity": "left", + "font": "roboto_condensed_bold", "fontColor": "#65DEED", "dynPref": "iobTotal" + }, + "iob2": { + "width": 88, "height": 44, "leftmargin": 252, "topmargin": 286, + "visibility": "visible", "textsize": 32, "gravity": "left", + "font": "roboto_condensed_bold", "fontColor": "#65DEED", "dynPref": "iobValue" + }, + "time": { + "width": 284, "height": 116, "leftmargin": 58, "topmargin": 159, + "visibility": "visible", "textsize": 92, "gravity": "center", + "font": "roboto_condensed_bold", "fontStyle": "normal", "fontColor": "#F3F7FA" + }, + "timePeriod": { + "width": 46, "height": 22, "leftmargin": 177, "topmargin": 258, + "visibility": "visible", "textsize": 14, "gravity": "center", + "font": "roboto_condensed_regular", "fontColor": "#ABB8C2" + }, + "day": { + "width": 32, "height": 28, "leftmargin": 34, "topmargin": 189, + "visibility": "visible", "textsize": 18, "gravity": "center", + "font": "roboto_condensed_regular", "fontColor": "#ABB8C2" + }, + "month": { + "width": 64, "height": 28, "leftmargin": 18, "topmargin": 217, + "visibility": "visible", "textsize": 18, "gravity": "center", "allCaps": true, + "font": "roboto_condensed_regular", "fontColor": "#ABB8C2" + }, + "cob1": { + "width": 24, "height": 24, "leftmargin": 72, "topmargin": 293, + "visibility": "visible", "textsize": 14, "gravity": "center", "textvalue": "", + "font": "roboto_condensed_bold", "fontColor": "#FFAB5C", "dynPref": "cobIcon" + }, + "cob2": { + "width": 120, "height": 44, "leftmargin": 100, "topmargin": 286, + "visibility": "visible", "textsize": 32, "gravity": "left", + "font": "roboto_condensed_bold", "fontColor": "#FFAB5C" + }, + "freetext3": { + "width": 108, "height": 22, "leftmargin": 146, "topmargin": 323, + "visibility": "visible", "textsize": 12, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#65DEED", "dynPref": "reservoirLabel" + }, + "reservoir": { + "width": 136, "height": 38, "leftmargin": 132, "topmargin": 342, + "visibility": "visible", "textsize": 20, "gravity": "center", + "font": "roboto_condensed_bold" + }, + "loop": { + "width": 44, "height": 44, "leftmargin": 246, "topmargin": 104, + "visibility": "visible", "textsize": 0, "gravity": "center", + "font": "roboto_condensed_bold", "fontColor": "#F3F7FA" + }, + "freetext4": { + "width": 24, "height": 24, "leftmargin": 224, "topmargin": 293, + "visibility": "visible", "textsize": 14, "gravity": "center", "textvalue": "", + "font": "roboto_condensed_bold", "fontColor": "#65DEED", "dynPref": "iobIcon" + }, + "dynPref": { + "reservoirGauge": { + "prefKey": "key_show_reservoir_level", + "true": { + "valueKey": "reservoir", "minData": 0, "maxData": 204, "invalidImage": "Empty", + "image1": "Reservoir000", "image2": "Reservoir004", "image3": "Reservoir008", + "image4": "Reservoir012", "image5": "Reservoir016", "image6": "Reservoir020", + "image7": "Reservoir024", "image8": "Reservoir028", "image9": "Reservoir032", + "image10": "Reservoir036", "image11": "Reservoir040", "image12": "Reservoir044", + "image13": "Reservoir048", "image14": "Reservoir052", "image15": "Reservoir056", + "image16": "Reservoir060", "image17": "Reservoir064", "image18": "Reservoir068", + "image19": "Reservoir072", "image20": "Reservoir076", "image21": "Reservoir080", + "image22": "Reservoir084", "image23": "Reservoir088", "image24": "Reservoir092", + "image25": "Reservoir096", "image26": "Reservoir100", "image27": "Reservoir104", + "image28": "Reservoir108", "image29": "Reservoir112", "image30": "Reservoir116", + "image31": "Reservoir120", "image32": "Reservoir124", "image33": "Reservoir128", + "image34": "Reservoir132", "image35": "Reservoir136", "image36": "Reservoir140", + "image37": "Reservoir144", "image38": "Reservoir148", "image39": "Reservoir152", + "image40": "Reservoir156", "image41": "Reservoir160", "image42": "Reservoir164", + "image43": "Reservoir168", "image44": "Reservoir172", "image45": "Reservoir176", + "image46": "Reservoir180", "image47": "Reservoir184", "image48": "Reservoir188", + "image49": "Reservoir192", "image50": "Reservoir196", "image51": "Reservoir200" + }, + "false": { "valueKey": "day", "image1": "Empty" } + }, + "glucoseUnits": { + "prefKey": "key_show_bg", + "true": { "dynPref": "units" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "units": { + "prefKey": "key_units", + "true": { "valueKey": "day", "textvalue1": "mg/dL" }, + "false": { "valueKey": "day", "textvalue1": "mmol/L" } + }, + "basalLabel": { + "prefKey": "key_show_temp_basal", + "true": { "valueKey": "day", "textvalue1": "BASAL" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "iobTotal": { + "prefKey": "key_show_detailed_iob", + "true": { "valueKey": "day", "fontColor1": "#65DEED" }, + "false": { "valueKey": "day", "textvalue1": "" } + }, + "iobValue": { + "prefKey": "key_show_detailed_iob", + "true": { "valueKey": "day", "topOffset1": 38, "leftOffset1": -16, "textsize1": 12, "fontColor1": "#ABB8C2" }, + "false": { "valueKey": "day", "topOffset1": 0, "leftOffset1": 0, "textsize1": 32, "fontColor1": "#65DEED" } + }, + "iobIcon": { + "prefKey": "key_show_iob", + "true": { "valueKey": "day", "image1": "IobIcon", "textvalue1": "" }, + "false": { "valueKey": "day", "image1": "Empty", "textvalue1": "" } + }, + "cobIcon": { + "prefKey": "key_show_cob", + "true": { "valueKey": "day", "image1": "CobIcon", "textvalue1": "" }, + "false": { "valueKey": "day", "image1": "Empty", "textvalue1": "" } + }, + "reservoirLabel": { + "prefKey": "key_show_reservoir_level", + "true": { "valueKey": "day", "textvalue1": "RES / U" }, + "false": { "valueKey": "day", "textvalue1": "" } + } + } +} diff --git a/wear/watchfaces/sport/CustomWatchface.png b/wear/watchfaces/sport/CustomWatchface.png new file mode 100644 index 000000000000..243282dcbb4b Binary files /dev/null and b/wear/watchfaces/sport/CustomWatchface.png differ diff --git a/wear/watchfaces/sport/README.md b/wear/watchfaces/sport/README.md new file mode 100644 index 000000000000..7ce899a01813 --- /dev/null +++ b/wear/watchfaces/sport/README.md @@ -0,0 +1,103 @@ +# AAPS Sport (1.18) + +Integrated into this AndroidAPS 4 checkout; see [integration and current verification](../README.md). The source-checkout notes below document the original design and its history. + +A separate, importable **Custom Watchface (CWF)** for [BernhardRo/AndroidAPS, branch `dev`](https://github.com/BernhardRo/AndroidAPS/tree/dev). The installed phone/Wear version is still unknown. + +No application code, treatment logic, alerts, data transport, AAPS V2 or AAPS Material files were changed. This is not a standalone WFF APK. + +## Design + +Black background, large bold digital time, light-blue reservoir/basal/IOB, orange COB and small instrument-style edge marks. The 400 × 400 template has: + +Version 1.18 keeps three complication slots (top center and left/right above the time), moves glucose delta below the reading, and places glucose-reading age inside the loop-status icon. Version 1.14 enlarged the **trend triangles again: eight-pixel height and 22-pixel base**, from six and 18 pixels. A larger transparent 146 × 146 canvas gives the tips room, without changing the visible ring's radius, six-pixel stroke or screen center. Its view moves three pixels up/left only to compensate for the three-pixel transparent border added on each side. The package remains compact; the updated ZIP stays below its 95 kB transfer budget. Loading of 1.6 was user-confirmed; later changes still need on-watch verification. + +- **Time:** central, 92-pixel text, native 12/24-hour format; optional AM/PM below it. No seconds. +- **Glucose:** upper left, inside a 146 × 146 transparent trend view at x=59, y=24. The visible ring stays centered at x=132, y=97 with 61-pixel radius. Subdued circle and highlighted segment retain a six-pixel stroke, native direction selection and glucose-color tinting. Glucose text remains 40 pixels. Trend triangles have eight-pixel height and 22-pixel base. A one-pixel base inset puts tips at radius 71, two pixels inside the larger canvas; double-marker spacing follows the wider base. Direction center angles, counts and 40-degree highlight sweep are unchanged. Units follow the existing units setting. The small value below glucose is now the native delta from the previous reading. +- **Basal:** upper right, turquoise, with the loop icon directly below it on the same center line. Basal uses AAPS's native current-basal text: a rate with units or a temporary-basal percentage. It updates as text, not as an arc; no parsing or new basal calculation is used. Basal and loop retain separate visibility settings. +- **COB/IOB:** matching 32-pixel, left-aligned values with 24 × 24 icons to their left and an equal four-pixel icon-to-value-field gap. Value fields start at x=100/252, y=286, fully below the clock field ending at y=275. Icons sit at x=72/224, y=293. The COB field is wider (120 pixels versus 88 for IOB) to allow native strings such as `120(40)g` while keeping both groups inside the round display and clear of the reservoir arc. Four pixels separate the full COB field from the IOB icon. The leading gap no longer grows for short strings; glyph side bearings add a little blank space. Native `left` gravity also top-aligns text, so the fields sit three pixels lower to preserve the total baseline in the local font model. COB stays orange and IOB turquoise. There is no `COB` or `IOB / U` heading. Both totals remain native, in both IOB modes. Detailed IOB keeps its native 12-pixel breakdown below the total, left-aligned at x=236, y=324. Preview baselines keep the `g` descender from shifting the digits upward; Android font padding can differ. +- **Reservoir:** light-blue quarter-circle gauge at the lower right, growing from bottom to right. The native remaining-amount string and `RES / U` heading share the watch's horizontal center at x=200. Their vertical placement and 20/12-pixel fonts are unchanged. Native reservoir warning/urgent text colors still take priority over the normal light-blue text. +- **Date:** day above abbreviated month, stacked to the left of the clock. Both retain 18-pixel text and 28-pixel field height to allow line-height space. The stack is vertically centered on the clock, without shrinking or moving the time. +- **Loop:** the native green/red/grey loop-status icon remains grouped under basal at the upper right. The number inside it now shows the age of the glucose reading; native loop-age text is hidden. The separate **Show Ago** and **Show Loop Status** preferences still control their respective fields. + +### AAPS icon sources + +The builder reads the actual phone overview icon geometry from `core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/icons/IcCarbs.kt` and `IcBolus.kt`. `ElementTypeStyle.kt` maps COB to `IcCarbs` and insulin/IOB to `IcBolus`. Paths are converted to `CobIcon.svg`/`IobIcon.svg`; only size and fill color change. No app source is edited. These are static field identifiers, not new alerts, buttons or copies of the phone chip's blinking behavior. + +Existing text views `cob1` and `freetext4` act as blank icon containers, using native preference-controlled backgrounds. Each icon follows its own COB/IOB visibility setting; native total values are not replaced or parsed. + +### Reservoir scale: full at 200 U + +The user selected a **0–200 U display scale**. The light-blue arc grows from the bottom toward the right edge. It is half full at 100 U, full from exactly 200 U, and stays full above 200 U. The native amount text is **not capped**: for example, 250 U still reads 250 U. + +The existing CWF image-step mechanism selects **51 arc images in 4 U increments**, not a smooth animation. Intermediate values round down for the arc only; the native numeric string keeps its own format. This is a display scale, not a new treatment target, alarm threshold or assertion about pump capacity. + +`cover_chart` carries the gauge image, despite its native view name; the actual history `chart` is gone. The gauge follows `key_show_reservoir_level`, independently of COB/IOB. Each gauge SVG has a 208 × 208 viewport over the lower-right crop (`viewBox="192 192 208 208"`), placed at x=192, y=192. A negative 90-degree sweep and SVG sweep flag 0 mirror the arc, without mirroring text or icons. The checked native loader already supports SVG resources and resolves dynamic image references by resource name without the extension. No app extension is needed. + +Implementation detail: the renderer uses an exclusive upper bound for its image bins. With `invalidImage` plus 51 numbered images, `minData: 0` and `maxData: 204` give 4 U bins. The last bin starts at exactly 200 U. **204 is a lookup bound, not the full-scale value.** Tests cover every boundary and values above the scale. + +The checked phone code sends `reservoir=0` and an empty native string when the amount is unavailable; a real zero also has no positive-amount string. The face preserves that ambiguity: only the dim track is shown, with no fabricated `0 U` value. A blank amount/dim track is not proof that the pump is empty. This ZIP cannot add a separate unknown/stale reservoir state that is absent from the source data. + +### Agreed limits + +There is **no history chart and no battery or step display**. The checked renderer cannot use COB, IOB or basal rate as numeric gauge sources, and exposes no watch-battery or step-count source. The static COB/IOB quarters from version 1.0 were removed rather than implying that those values control their lengths. Phone battery was not substituted. + +The checked phone-to-Wear status also has no dedicated pump-battery value. Its existing battery fields refer to the phone and Nightscout rig/uploader, not the pump. A real pump-battery bar would require app/transport/renderer changes; the user chose to leave this out rather than display a different device's battery. + +The background is always black, including with the existing light-mode option. `Querbalken farbgleich` has no separate effect: this face has no contrasting status-bar surfaces to match. User settings are not overridden. + +### Trend ring and warnings + +Enable **Trendpfeil anzeigen** on the watch to show the ring. It belongs to the native `direction` view, not the loop-status icon. The seven ordinary directions use the phone's arc positions and triangle counts. An unknown/NONE direction has only the subdued ring, not a flat-trend marker. + +The branch transports both triple-up and triple-down with the same `X` symbol, which the existing renderer resolves to double-up. This package does not fix that ambiguity or claim complete phone/Wear trend parity. Native stale-reading, glucose-color, reservoir-warning and loop-warning hooks remain in use; no thresholds or warning logic were changed. The reservoir arc itself stays light blue; warning colors come from the native reservoir text. + +### Compact transfer and resolved loading report + +The user reported that **1.5 appears in the phone list, but selecting it leaves the old watchface on the watch, with no visible error**. The local ZIP CRC, JSON and PNGs are valid. The checked phone code sends the entire ZIP through one `MessageClient.sendMessage` call; it does not use an Asset or chunk the file. Google describes message payloads as [generally not larger than 100k](https://developers.google.com/android/reference/com/google/android/gms/wearable/MessageClient). This guidance is not proof of a hard cutoff or the user's exact failure cause; no phone/Wear failure log is available. + +Version 1.6 reduces the package by **85.3%**, without reducing the number of gauge steps or changing transport code. The builder rejects a ZIP above a conservative **95,000-byte budget**, leaving margin below that guidance. The 51 SVGs retain the crop, colors, round caps and arc geometry. Their local previews render the packaged SVG through resvg; native AndroidSVG rasterization may differ slightly. Only the gallery thumbnail is palette-quantized, not the live text colors or PNG trend masks. + +After trying 1.6, the user replied **"funktioniert!"** on 2026-10-16. This confirms successful loading/activation for the user's setup and closes the reported loading problem. It does not prove that message size was the cause, nor verify all reservoir/trend states, exact spacing, warnings or ambient behavior. + +## Import + +Package: [`AAPS Sport.zip`](../../../plugins/configuration/src/androidMain/assets/AAPS%20Sport.zip). + +1. Keep the ZIP zipped and copy it into `/exports/AAPS Sport.zip` on the phone. +2. With the watch connected, use **AAPS → Wear → Watchface laden → AAPS Sport (1.18)**. Selecting it sends the face to the watch. To update an earlier version, replace its ZIP in `exports`, close/reopen the load list, and confirm that it shows version 1.18 before selecting it. +3. Select **AAPS(Custom)** on the watch if needed. +4. In its existing settings, enable the fields you want: glucose, trend arrow, **delta**, reading age, COB, IOB, loop status, **reservoir**, **basal/temporary basal**, **date** and **complications 1–3**. Date, reading age and complications are off by default in the checked native code; the preview deliberately shows date and age. Assign providers such as battery in the watchface editor. Saved settings are respected, not changed by the ZIP. + +No APK rebuild or installation is needed when the installed app supports this CWF format. As with Material, a future phone build may include the ZIP as an asset, but adding an asset does not refresh an already populated `exports` list. Copy this ZIP explicitly. + +## Sources and local checks + +- `CustomWatchface.json`: live-field layout and existing preference chains. +- `SportArtwork.json`: editable colors, reservoir scale/geometry, crop, edge marks, trend-ring geometry and icon source paths/colors. Keep its gauge steps consistent with the explicit native image list in `CustomWatchface.json`; tests check this. +- `build_watchface.py`: SVG/PNG resource generation, deterministic size-limited ZIP and synthetic previews. Pillow and resvg-py versions are pinned in `requirements.txt`. This is an asset-building helper, not application code. +- `test_watchface.py`: static CWF contract and design checks. +- `CustomWatchface.png`, `preview-states.png`, `preview-trends.png`, `preview-reservoir.png`: generated previews. + +From `AndroidAPS/`: + +```powershell +python -m pip install -r wear/watchfaces/sport/requirements.txt +python wear/watchfaces/sport/build_watchface.py +python wear/watchfaces/sport/build_watchface.py --check +python -m unittest discover -s wear/watchfaces/sport -p "test_*.py" -v +``` + +The ZIP contains 65 root entries: `CustomWatchface.json`, the indexed `CustomWatchface.png` thumbnail, 51 gauge SVGs, two icon SVGs, and ten other PNGs (background, empty image and eight trend masks). No fonts are downloaded or added; the face uses fonts already in Wear. + +**All previews use synthetic data. They are not Android screenshots or evidence of live watch behavior.** They use the packaged artwork and trend masks, but approximate text placement and native loop icons. Their sample readings must not be used for treatment decisions. + +## Watch verification still needed + +- Basic loading/activation of **1.6** is user-confirmed on 2026-10-16. Later requests refined icons, spacing, reservoir color/position, ring thickness and marker size. Confirm loading, complication placement, value placement and the retained trend markers for **1.18** at normal viewing size. If transfer fails, collect phone/Wear logs around selection; the checked phone code logs `sendMessage` with the payload size and a `failure` line on send failure. +- Check `OKT`/`OCT`, longer month abbreviations, 12/24-hour time and optional AM/PM for clipping. Check the date-to-clock gap and the lower reservoir text's clearance from the arc on the actual display. +- Check glucose units, reading age, the six-pixel ring and trend-ring visibility against the phone, including text clearance and all larger direction markers, especially the double markers and image-edge clearance. Missing data must not be mistaken for a flat trend. +- Check the orange wheat and turquoise syringe icons, their closer spacing to short and long 32-pixel COB/IOB totals, spacing from the clock, and normal/detailed IOB. The native breakdown remains below the IOB total. The local font model is not proof of exact Android placement. Check negative values, larger COB strings and rate/percentage basal strings. Arbitrarily long native strings and all locales cannot be guaranteed by sample-based tests. +- Compare the light-blue reservoir heading, normal amount text and lower-right SVG arc with IOB/basal color and with the phone at naturally occurring levels, including visibility and clipping. Check the arc's clearance from long/negative IOB and detailed breakdown text: the local sample model has only a small gap for the longest negative total. Full scale is 200 U; only the arc is limited. COB must remain orange. Check native warning/urgent text appearance without changing treatment or pump settings for a visual test. +- Toggle optional fields, including reservoir and basal: their headings/arc should follow them. Each COB/IOB switch must hide both its icon and its value, without hiding the other group or reservoir arc. Basal and loop must still hide independently, despite being grouped together. +- Check native stale-data and loop-warning appearance, ambient mode, wake/touch behavior and battery use. Multiple gauge images are loaded by the native renderer; memory use and runtime behavior still need watch verification. No device testing or installation has been done by the agent. diff --git a/wear/watchfaces/sport/SportArtwork.json b/wear/watchfaces/sport/SportArtwork.json new file mode 100644 index 000000000000..6971d1a3f815 --- /dev/null +++ b/wear/watchfaces/sport/SportArtwork.json @@ -0,0 +1,22 @@ +{ + "size": 400, + "background": "#000000", + "edge": { "radius": 195, "stroke": 1, "color": "#1D282F" }, + "ticks": { + "radius": 175, "length": 5, "stroke": 1, "color": "#45535D", + "angles": [35, 45, 55, 65, 75] + }, + "reservoir": { + "radius": 184, "stroke": 8, "start": 90, "sweep": -90, + "color": "#65DEED", "track": "#173238", "maximum": 200, "increment": 4, + "crop": [192, 192, 400, 400] + }, + "trend": { "size": 146, "radius": 61, "stroke": 6, "arrowHeight": 8, "arrowHalfBase": 11, "arrowInset": 1, "sweep": 40, "trackAlpha": 60 }, + "icons": { + "size": 24, + "sources": { + "CobIcon": { "file": "core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/icons/IcCarbs.kt", "color": "#FFAB5C" }, + "IobIcon": { "file": "core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/icons/IcBolus.kt", "color": "#65DEED" } + } + } +} diff --git a/wear/watchfaces/sport/TESTRESULTS.md b/wear/watchfaces/sport/TESTRESULTS.md new file mode 100644 index 000000000000..a17a936baeb5 --- /dev/null +++ b/wear/watchfaces/sport/TESTRESULTS.md @@ -0,0 +1,178 @@ +# AAPS Sport 1.14 verification + +Historical verification date: 2026-10-16. Local environment: Windows, Python, Pillow 12.1.1 and resvg-py 0.5.0. Current project: [BernhardRo/AndroidAPS, branch `dev`](https://github.com/BernhardRo/AndroidAPS/tree/dev). See [integration verification](../README.md) for the later import checks. + +## Executed checks + +Run from the AndroidAPS checkout root: + +| Check | Command / method | Result | +| --- | --- | --- | +| Build ZIP and previews | `python wear/watchfaces/sport/build_watchface.py` | Passed | +| Rebuild consistency | `python wear/watchfaces/sport/build_watchface.py --check` | Passed; ZIP matches sources | +| Static/design tests | `python -m unittest discover -s wear/watchfaces/sport -p "test_*.py" -v` | 45 tests passed | +| Complete ZIP transport budget | Compare final bytes with the 95,000-byte builder budget; test oversized-package rejection | Passed; 81,819 bytes | +| Tracked files unchanged | `git diff --exit-code HEAD -- .` | Passed; no tracked-file differences | +| Preserve existing Material sources, previews and existing ZIP assets | SHA-256 comparison with the pre-edit baseline of 37 existing files | Passed; none changed or removed | + +The final suite passed after rebuilding. Packaged SVG artwork is rendered locally by resvg for the static/design checks. This is not an AndroidSVG runtime test. + +## Change from 1.13: larger arrowheads with transparent edge room + +- Increased triangle height from six to eight pixels and base from 18 to 22 pixels, retaining the one-pixel base inset. The tip now reaches radius 71 instead of 69; double-marker spacing follows the wider base. Ring radius/stroke, native direction center angles/counts, tinting, highlighted sweep and all live data remain unchanged. +- Expanded the transparent image/view from 140 × 140 to 146 × 146 and shifted its origin from x=62/y=27 to x=59/y=24. The visible ring remains centered at x=132/y=97 with radius 61 and stroke 6; the extra three pixels per side provide two pixels of geometric tip margin. Glucose text and all other field positions are unchanged. +- Existing tests now compare with 1.13-style triangles: area 88 instead of 54 square pixels, more rendered opaque area in all seven marker states, no opaque border clipping, full round-screen envelope clearance, unchanged six-pixel track width and native mapping. Cropping the new NONE resource by three pixels per side gives exactly the previous image, proving the plain ring pixels are unchanged apart from transparent padding. +- ZIP changes are limited to metadata, the transparent direction frame, thumbnail and eight resized trend PNGs. All 55 other artwork resources are byte-identical to 1.13, including every reservoir SVG and both icons. +- **1.14 has not been tested on the watch.** Verify larger single/double arrowheads and image placement on the actual display. + +## History: 1.13 changes from 1.12 + +- Increased triangle height from four to six template pixels and base from 15.6 to 18 pixels. Added explicit `arrowHalfBase: 9` and `arrowInset: 1` artwork parameters; the builder places the base one pixel inward to keep the tip at radius 69, one pixel inside the existing 140 × 140 canvas. Double-marker spacing follows the new base width. Native direction center angles/counts and segment sweep remain unchanged. +- Ring stroke remains six pixels, radius 61, position/view size unchanged. The NONE/plain-circle PNG is byte-identical; no data source, preference, glucose font, other field or warning hook changed. +- Added geometric area, rendered visible-area and edge-clipping checks for all seven marker states, compared with locally regenerated 1.12-style markers. Each triangle's geometric area is 54 square pixels instead of 31.2. Tests also retain the six-pixel track-width check, native mapping, tintable white masks and full round-screen envelope clearance. +- ZIP comparison confirms changes only to version metadata, thumbnail and seven marker PNGs. All 56 other artwork resources are byte-identical, including NONE, every reservoir SVG, icons, background and empty image. +- **1.13 has not been tested on the watch.** Confirm the larger single/double markers and their edge clearance on the actual display. + +## History: 1.12 changes from 1.11 + +- Increased trend stroke from four to six template pixels, for both the subdued circle and highlighted segment in all eight PNG masks. View size 140 × 140, centerline radius 61, position, 40-pixel glucose font, native tinting/selection, 40-degree segment sweep and triangle counts/height remain unchanged. Existing builder rules scale triangle bases and double-marker spacing with stroke width; the outer tip reaches radius 68, still two pixels inside the resource canvas. +- Added a raster width check: the NONE mask has a six-pixel midline cross-section, compared with four in a locally regenerated previous-stroke mask. Tests retain geometry, text clearance, round-screen envelope, white-mask tinting and native direction mapping checks. +- ZIP differences are limited to version metadata, thumbnail and the eight trend PNGs. All 55 other artwork resources are byte-identical, including every reservoir SVG, icons, background and empty image. All live-field JSON geometry and preferences remain unchanged. +- Pump-battery display was investigated but deferred by the user. Checked `EventData.Status`/`DataHandlerMobile.sendStatus` expose phone battery and rig/uploader status, not a dedicated pump battery; no app changes or substitute battery display were added. +- **1.12 has not been tested on the watch.** Local previews and prior ring visibility/loading confirmations do not verify this new stroke or all trend states. + +## History: 1.11 changes from 1.10 + +- Moved only `RES / U` and the native reservoir amount 20 pixels right, from shared x=180 to x=200, matching the watch's horizontal center. Their left margins become 146/132; widths 108/136, top positions 323/342, fonts 12/20 and centered gravity are unchanged. +- Lower-right gauge, colors, native warning hooks, COB/IOB and all other fields remain unchanged. Tests check the shared screen center, unchanged vertical positions, fonts, widths, text/gauge clearance and visibility behavior. +- ZIP comparison confirms only JSON and thumbnail changed; all 63 artwork resources are byte-identical to 1.10. JSON differences are limited to metadata and the two reservoir text views. +- **1.11 has not been tested on the watch.** The local preview and tests are not proof of exact Android placement. + +## History: 1.10 changes from 1.9 + +- Mirrored only the reservoir arc/track from lower left to lower right. The gauge view moves to x=192, y=192 with the same 208 × 208 size; SVG crop becomes `viewBox="192 192 208 208"`. Start remains 90 degrees; sweep becomes -90 degrees, with SVG sweep flag 0. Fill grows from bottom toward right rather than left. +- Radius 184, stroke 8, round caps, light-blue fill/dim track, 51 states, 4 U bins, 200 U full scale and uncapped native amount are unchanged. No reservoir heading, amount, COB, IOB or other text/icon position changed. JSON comparison with 1.9 is limited to metadata and `cover_chart`. +- ZIP comparison confirms only JSON, thumbnail and the 51 gauge SVGs changed. All 12 other artwork resources are byte-identical. The transparent empty PNG retains identical bytes despite the changed crop origin. +- Added tests for the correct side, fill direction, no old left-side arc, and rasterized clearance between the full right-side gauge and representative negative/detailed IOB and reservoir text. At 1x/3x, the tested glyphs clear the opaque gauge plus a one-pixel mask expansion. The long `-12.34` sample does not clear a two-pixel expansion at 3x; no wider margin or exact Android alignment is claimed. Other fields were not moved to hide this limitation. +- **1.10 has not been tested on the watch.** Verify actual IOB/gauge clearance and native SVG placement; the 1.6 loading confirmation does not verify this revision. + +## History: 1.9 changes from 1.8 + +- User requested the reservoir bar and its text in the same light-blue insulin color as IOB/basal. Changed all 51 gauge SVG fills to `#65DEED`, the dim track to `#173238`, the `RES / U` heading to `#65DEED`, and the normal native reservoir amount via `reservoirColor` to `#65DEED`. +- COB text and wheat remain orange. Native warning/urgent amount colors still take priority; the reservoir text view has no fixed `fontColor`, and warning/urgent colors and thresholds are not overridden. The arc itself remains light blue at all levels. +- The user also requested COB farther right toward the center. COB icon/value move together eight pixels, from x=64/92 to x=72/100. Their four-pixel internal gap, fonts and vertical placement are retained. The full COB field still clears the IOB icon by four pixels; long native strings fit. IOB and all other field positions are unchanged. +- Fonts, native values, visibility preferences, 200 U scale, all step boundaries and gauge geometry are unchanged. Only metadata, `reservoirColor`, the reservoir heading and COB icon/value positions differ in JSON. ZIP comparison confirms only JSON, thumbnail and the 51 reservoir SVGs changed; all 12 other artwork resources are byte-identical to 1.8. +- Added a palette-consistency test and replaced the orange-specific pixel counter with a fill/track color-based counter. Every gauge image must still increase in visible filled area; exact SVG geometry/color checks remain in place. +- **1.9 has not been tested on the watch.** Previous loading confirmation is not confirmation of this color update, COB position or native warning behavior. + +## History: 1.8 changes from 1.7 + +- User requested icons closer to the numbers. The large visible gap came from centering short numbers inside wide value fields. All three native total views (`cob2`, `iob1`, `iob2`) now use `gravity: left`; normal and detailed IOB still use the native total values. +- Icon positions and 24-pixel sizes are unchanged. Value fields move four pixels left to x=92/252, reducing the icon-to-field gap from eight to four pixels. Their widths and 32-pixel fonts are retained. Tests cover zero, short, long, negative and placeholder strings in both IOB modes; the modeled leading gap stays four pixels rather than growing with field space. Raster checks at 1x/3x allow up to three extra pixels of glyph side bearing. +- Native LEFT maps to `Gravity.START`, without vertical centering. Total fields move three pixels down to y=286 to preserve their previous total baseline in the Pillow model. The preview helper now respects horizontal gravity and top alignment rather than assuming all text is centered. Android font padding is still not verified by this model. +- Detailed IOB's offset changes to down 38/left 16, placing the 12-pixel breakdown at x=236, y=324 below the total under top alignment. Sample strings fit and retain vertical separation. Icons and the entire total row remain below the clock. +- Only JSON and thumbnail differ inside the ZIP. All 63 artwork resources, including the icons, are byte-identical to 1.7; all other fields, preferences, data, warning hooks and scale are unchanged. Archive remains 65 entries and below the transport budget. +- **1.8 has not been tested on the watch.** User confirmation of 1.6 loading does not confirm this spacing change. + +## History: 1.7 changes from 1.6 + +- New user report: on the actual watch, the COB/IOB headings sit very close to the large time, almost overlapping. The user requested AAPS symbols before larger numbers instead of those headings. Earlier equal-coordinate/ink-gap checks did not verify the watch's full clock-to-heading layout. +- Replaced both headings with 24 × 24 SVG icons: orange wheat/carbs from AAPS `IcCarbs`, and turquoise syringe/insulin from `IcBolus`. The builder reads the existing Compose source path commands; tests compare every SVG command and operand with the source, and check the phone overview's `ElementTypeStyle` mapping. No app/icon source was edited. +- Blank `cob1` and `freetext4` text views carry existing preference-controlled drawable backgrounds. Icons follow the COB/IOB switches independently; no native numeric value is replaced with icon text. Icons are static identifiers, not new warning/blink logic. +- Both total fonts increase from 26 to 32 pixels. Native total fields begin at y=283 with height 44; the entire view is below the clock field ending at y=275. Tests require at least six physical pixels of view separation at six native zoom factors, not only separation of sample glyphs. +- Icons sit at x=64/224, y=293; each has an eight-pixel gap to its value field. Value centers are x=156/300, y=305. The COB value field is 120 pixels wide for long native strings, versus 88 for IOB. Tests check sample strings, matching numeral tops/baselines, icon/value centering, inter-group separation and icon clearance from the round reservoir arc. An initial design preview put the wheat too near the arc; final icons are smaller and inset. +- Detailed IOB retains the same 32-pixel total row; its native 12-pixel breakdown is moved down 26 and left 20 pixels from the base IOB2 field, centering it at x=280. The local preview helper now handles native step-based left offsets and TextView image backgrounds. +- Clock, date, basal/loop, reservoir text, 200 U scale, preferences and warning hooks are unchanged. All 61 original artwork resources are byte-identical to 1.6; only JSON and thumbnail changed, and two icon SVGs were added. Archive has 65 entries and remains below the transport budget. +- **1.7 has not been tested on the watch.** The 1.6 loading confirmation does not confirm this new layout, spacing, icon rendering or transfer. + +## History: reported failure and user-confirmed 1.6 loading + +- User report for 1.5: the watchface is present in the AAPS list, but selecting it shows no error and leaves the old watchface on the watch. This confirms list visibility, not successful delivery or activation. +- The 1.5 ZIP was locally readable with valid CRC, JSON and decodable PNGs. Investigation found that `WearViewModel.selectWatchface` sends its ZIP bytes via `EventMobileToWearWatchface`; `DataLayerListenerServiceMobile` passes the entire array to one `MessageClient.sendMessage` call. No chunking/Asset transport is used on that path. +- [Google's MessageClient reference](https://developers.google.com/android/reference/com/google/android/gms/wearable/MessageClient) describes payloads as generally not larger than 100k. The old 519,551-byte package exceeded that guidance. This is a plausible transfer risk, not proof of the user's exact cause or a documented hard cutoff. No device log was provided. +- Replaced only the 51 reservoir PNGs with small SVGs. The checked `ZipWatchfaceFormat` recognizes SVG and stores arbitrary image resources under their extension-free name. `ResDataExtension` already parses them with AndroidSVG and renders them to a PictureDrawable. Native app/transport code is unchanged. +- Retained all 51 states in 4 U steps, the 0–200 U scale, 208 × 208 crop, 184-pixel arc radius, 8-pixel stroke, round caps and track/orange colors. Local tests parse every SVG path, verify endpoints and render the packaged SVGs through resvg for the existing pixel/design checks. Antialiasing may differ from the earlier raster artwork and from AndroidSVG. +- Thumbnail changed to a valid 400 × 400 indexed PNG with up to 256 colors. Full-color preview sheets remain available. All eight PNG direction masks, background and empty PNG are byte-identical to 1.5, preserving native bitmap tinting. +- JSON differs from 1.5 only in `metadata.author_version` (1.6). All field positions, fonts, colors, preferences and warning hooks are unchanged. +- Final ZIP is 76,356 bytes, **85.3% smaller**. Builder and tests enforce a conservative 95,000-byte budget and reject an oversized result. New local dependency resvg-py 0.5.0 is pinned with Pillow in `requirements.txt`. +- **User confirmation, 2026-10-16:** after trying the compact 1.6 package, the user replied **"funktioniert!"**. Basic loading/activation on the user's watch is therefore confirmed, and the reported loading failure is closed for this setup. The exact earlier failure cause remains unproven without logs. This broad confirmation does not verify all SVG arc levels, trend directions, live updates, precise spacing, warnings or ambient behavior. + +## History: 1.5 changes from 1.4 + +- Corrected COB/IOB preview text placement to use a fixed font-line baseline rather than centering each string's ink. The `g` descender no longer shifts the COB digits above the IOB digits. This changes the Python preview helper, not the Android renderer or live data. +- Moved only the IOB heading (`freetext4`) from top 252 to 251 to account for the slash extending one template pixel below capital letters in the bundled font. The total fields keep their native coordinates and font sizes in both detail modes; labels and units are retained. +- At template scale, the local font model measures both visible heading-to-number gaps as 14.5 pixels for `18g`/`2.40`. Tests also cover `120g`/negative IOB and zero strings in both IOB modes. Raster checks at 1x and 3x confirm equal numeral tops and equal lower heading edges. These checks do not establish exact Android pixel alignment. +- Other layout, font sizes, colors, native values, preferences, gauge and trend masks are unchanged. ZIP comparison with 1.4 found changes only to JSON and the preview. JSON changes are limited to `metadata` and `freetext4`. All 61 artwork resources remain byte-identical. + +## History: 1.4 changes from 1.3 + +- Day/month moved from the bottom strip to a vertical stack left of the clock, centered at x=50. Day top is 189 and month top is 217; the stack's vertical center matches the clock at y=217. Both retain 18-pixel text and 28-pixel field height. Date still follows the saved date preference, whose native default is off. +- Reservoir heading/amount moved 18 pixels down and 40 pixels inward to clear the round arc. Both share x=180; heading top is 323 and amount top is 342. Fonts remain 12/20 pixels. +- Clock size and position, all other fields, colors, preference chains, 200 U gauge and trend masks are unchanged. +- ZIP comparison with 1.3 found changes only to `CustomWatchface.json` and `CustomWatchface.png`. Changed JSON sections are limited to `metadata`, `day`, `month`, `freetext3` and `reservoir`. All 61 artwork resources remain byte-identical. + +## History: 1.3 changes from 1.2 + +- Glucose/ring/unit/age cluster moved left to x=132 center, without changing sizes or masks. Basal heading/value/loop share the mirrored x=268 axis. Loop is directly below basal, with the native icon and warning hook unchanged. +- Basal heading reduced to 12 pixels like `RES / U`; native basal value reduced to 20 like the reservoir amount. Basal and loop remain separately controlled by existing preferences. +- COB/IOB columns mirror each other at x=120/280. Headings are 14 pixels; total values are 26, with matching view dimensions and row positions. COB heading/value are orange; IOB heading/total are turquoise. +- A separate preference-controlled `freetext4` keeps the IOB heading stable in both native detail modes. Normal IOB uses native `iob2` for the total. Detailed IOB uses native `iob1` for the same-size total on the same row, and native `iob2` for the 12-pixel breakdown below. No live number is replaced by a decorative string. +- Day/month strip is centered on the canvas at the bottom. Reservoir number, gauge geometry and 200 U scale, main clock, palettes and no-chart/no-battery scope are unchanged. +- Removed background tick marks that would otherwise appear inside the relocated glucose ring. +- Read-only ZIP comparison with 1.2 found changes only to `CustomWatchface.json`, `CustomWatchface.png` and `Background.png`. All 51 gauge images, eight trend masks and the empty image remain byte-identical. The archive still has 63 entries. +- No application code, API, treatment, alert, warning threshold or data transport was changed. + +## History: 1.2 changes from 1.1 + +- Reservoir amount font reduced from 26 to 20 template pixels. +- COB value font increased from 22 to 26. Its field height increases from 32 to 38, with the top moved from 277 to 274 to keep the same center at (112, 293). +- Reservoir value center remains (140, 343). Labels, all other fields, colors, preference chains and the 200 U gauge are unchanged. +- Read-only comparison with the pre-edit 1.1 ZIP confirms changes only to JSON and the package preview. JSON changes are confined to `metadata`, `cob2` and `reservoir`; all 61 artwork resources are byte-identical. + +## History: 1.1 changes from 1.0 + +- Removed both static COB/IOB quarters. Added one orange lower-left reservoir gauge, full at the user-selected 200 U, using 51 images in 4 U steps. +- Added the native reservoir amount with no text/value cap. Native reservoir warning/urgent text hooks remain enabled; only the normal reservoir text color is set to orange. +- Upper right now shows native current-basal text in turquoise, including temporary-basal percentages. It is not a numeric arc source. +- COB/IOB remain as compact columns below the large clock, including native detailed IOB. Date and loop were repositioned below them; the small brand and fixed loop label were removed for space. +- Time, glucose/trend/age geometry, native glucose palette and no-chart/no-battery scope are unchanged. +- No application code, API, treatment, alert, warning threshold or data transport was changed. + +## Test coverage + +- Strict JSON parsing, no duplicate keys, separate face identity and compatible CWF major version in the checked source. +- Existing native view keys, JSON fields, font names, resource names and preference keys; no new app fields or API extensions. +- No preference metadata overrides, seconds, history chart or substituted battery display. +- Native live values, direction selection and glucose/stale/reservoir/loop-warning hooks are not replaced with sample text or custom warning logic. +- Reservoir uses the existing numeric `ValueMap.RESERVOIR` source. Its lower-right light-blue quarter-circle has a 200 U display maximum. SVG viewport dimensions/origin, negative sweep/direction flag, all 51 paths, colors, caps and increasing locally rendered visible arc area were checked. Heading/normal amount/gauge color must match IOB/basal, while COB remains orange and native warning colors are not overridden. +- Native image-index formula modeled locally, including its `maxData * 0.9999` boundary clamp and `stepDraw = dynDrawable.size - 1`. With one invalid entry and 51 images, `maxData=204` produces 4 U bins and selects the full image only from 200 U. Tests cover 0–500 U in quarter-unit samples, fractional boundaries, negative values, values above full scale and invalid selection. This is source-based modeling, not an executed Kotlin test. +- Above-full-scale previews keep identical arc pixels while changing the uncapped amount string. The native unknown value (zero plus empty amount string) is not replaced by a fabricated `0 U` reading. +- Gauge/amount/label follow reservoir visibility, not COB or IOB. Basal heading follows native basal visibility. COB and IOB icon backgrounds follow their native visibility settings independently, in both IOB modes. Units and normal/detailed IOB remain supported. +- Bounds, full bundled-font line height plus four template pixels of reserve, and checks at six zoom factors. This includes date fields rather than testing visible glyph bounds alone. +- Representative time, German/English month, decimal-comma/point glucose, negative IOB, detailed IOB, larger COB, native reservoir and basal rate/percentage strings. Text fits its field. The earlier conservative radius-178 lower-left bounds remain; other areas have a radius-189 check. The new right-side gauge clearance is checked separately with rasterized glyphs and a one-pixel expanded gauge mask. Glucose/age samples also stay within their own trend ring. +- Space between main text groups; no preview auto-shrinking to conceal field-size issues. +- Matching 32-pixel COB/IOB fonts and numeric rows, equal icon sizes/four-pixel field gaps and colors; smaller equal-sized basal/reservoir values and headings. Native IOB total remains 32 pixels in both modes. Fixed preview baselines, left/top alignment and rasterized numeral edges are checked. Full native clock/row view separation is checked at six zoom factors. Icons are compared with original AAPS paths and checked for visibility, arc clearance and icon/value-field separation. Short/long/negative/placeholder totals retain a close leading gap at 1x/3x instead of being centered within the fields. +- Mirrored glucose and basal/loop axes, basal/loop vertical order, independent visibility settings and full trend-ring envelope clearance from the round display edge. Background pixels inside the glucose ring are black, not decorative tick marks. +- Date stack left of the clock, unchanged date fonts/line reserve, shared date axis, vertical centering and at least 12 pixels of visible separation from representative clock strings. Date visibility does not change clock pixels. Lower reservoir text is centered at x=200 with unchanged size/height; clearance within radius 178 is checked explicitly. +- All configured text and glucose colors have at least 4.5:1 contrast against black. Decorative ticks and subdued trend tracks are not text and are not covered by this claim. +- Six-pixel ring stroke with unchanged centerline radius/screen center and a larger transparent image frame; raster comparison with the old four-pixel track, full marker envelope and text clearance. Eight-by-22-pixel triangles are checked for geometric/rendered area, two-pixel canvas margin and no opaque edge clipping. The cropped NONE image must match the previous plain-ring pixels exactly. Seven ordinary native directions and NONE, native resource names, transparent white masks, highlight positions and arrow counts remain checked. Full triple-up/down parity is not claimed. +- 24 preview combinations of six data states × normal/detailed IOB × 12/24-hour display, individual visibility toggles and all optional fields off. Additional previews include negative IOB, a long COB string and a temporary-basal percentage. Reservoir sheet covers unavailable/zero, 40, 100, 160, 200 and 250 U. +- Deterministic ZIP bytes, exact root entries, CRC, decodable PNGs, parsable/renderable SVGs, extension-free preference-resource references and source/asset consistency. Complete-package size, oversized-package rejection, native source support and indexed-thumbnail format are checked. + +## Visual review + +Final indexed `CustomWatchface.png` and full-color `preview-trends.png` were read as images for 1.14. Review checked the further enlarged single/double arrowheads in all seven marker states, the retained NONE circle/ring position, text space, centered reservoir text and unchanged lower-right arc/COB/IOB layout. State/reservoir sheets were rebuilt but not separately visually reviewed for this revision; tests cover optional visibility, other data states and text clearance. + +The images are **synthetic design previews**, not device screenshots. They use the packaged arc images and locally model native selection. Basic loading/activation of 1.6 is user-confirmed, not independently tested by the agent. Runtime text placement, exact native loop icons, warning colors/threshold choices, stale styling, tinting, memory use and refresh behavior have not been checked individually on Android. The normal preview shows date enabled; the ZIP does not change the user's saved date setting. + +The checked phone source uses a numeric zero and an empty reservoir string for unavailable data. The existing CWF numeric source cannot tell this apart from a real zero. The face preserves the native amount and shows no bright fill for that input; a dim track/blank amount is not a confirmed empty-pump diagnosis. Basal strings are taken as-is, not parsed or converted. + +## Scope and artifact + +Only `wear/watchfaces/sport/` JSON version/direction frame, artwork marker geometry/canvas size, tests, docs and generated previews, plus `plugins/configuration/src/main/assets/AAPS Sport.zip`, were updated for 1.14. Builder and dependencies are unchanged. All existing Material files and the user's other renamed/copied packages were preserved, verified against a new pre-edit hash baseline of 37 files. The previous 1.13 Sport ZIP was backed up outside the checkout in the approved OpenCode temp directory; earlier backups were not changed. No app code, original AAPS icon source, transport, glucose interpretation, treatment or alarm logic was changed. Nothing was committed, pushed or installed on a device. + +- Path: `plugins/configuration/src/main/assets/AAPS Sport.zip` +- Size: 81,819 bytes; 65 ZIP entries (53 SVG, 11 PNG, one JSON) +- SHA-256: `0896647474cdd8dc83232646e6c50cf343b9c6e703e52fe42e4a21d93eec8ed7` + +No Android APK build, emulator/device run, instrumented test, installation, ambient test or battery measurement was performed. The installed phone/Wear commit remains unknown. Previous Material ring visibility reports are not runtime verification of this new face. User verification on the watch remains required. diff --git a/wear/watchfaces/sport/build_watchface.py b/wear/watchfaces/sport/build_watchface.py new file mode 100644 index 000000000000..c36e82d29531 --- /dev/null +++ b/wear/watchfaces/sport/build_watchface.py @@ -0,0 +1,425 @@ +"""Build AAPS Sport CWF resources and synthetic design previews, not Android renders.""" + +from __future__ import annotations + +import argparse +from functools import lru_cache +import io +import json +import math +from pathlib import Path +import re +import zipfile + +from PIL import Image, ImageDraw, ImageFont +from resvg_py import svg_to_bytes + +SOURCE = Path(__file__).resolve().parent +ROOT = SOURCE.parents[2] +ASSET = ROOT / "plugins/configuration/src/androidMain/assets/AAPS Sport.zip" +FONTS = ROOT / "wear/src/main/res/font" +ART = json.loads((SOURCE / "SportArtwork.json").read_text(encoding="utf-8")) +TREND_ARROWS = { + "ArrowNone": ("NONE", None, 0), + "ArrowFlat": ("FLAT", 0, 1), + "Arrow45Up": ("FORTY_FIVE_UP", -45, 1), + "ArrowSingleUp": ("SINGLE_UP", -90, 1), + "ArrowDoubleUp": ("DOUBLE_UP", -90, 2), + "Arrow45Down": ("FORTY_FIVE_DOWN", 45, 1), + "ArrowSingleDown": ("SINGLE_DOWN", 90, 1), + "ArrowDoubleDown": ("DOUBLE_DOWN", 90, 2), +} +GAUGE_VALUES = tuple(range(0, ART["reservoir"]["maximum"] + 1, ART["reservoir"]["increment"])) +GAUGE_NAMES = tuple(f"Reservoir{value:03d}" for value in GAUGE_VALUES) +ICON_NAMES = tuple(ART["icons"]["sources"]) +RESOURCE_NAMES = ("Background", "Empty", *GAUGE_NAMES, *TREND_ARROWS, *ICON_NAMES) +# AAPS sends the complete ZIP in one Wear MessageClient call. Keep headroom +# below Google's general 100 kB message guidance; delivery still needs a watch test. +MAX_PACKAGE_BYTES = 95_000 +VIEW_PREFS = { + "sgv": "key_show_bg", "direction": "key_show_direction", "timestamp": "key_show_ago", "delta": "key_show_delta", + "cob1": "key_show_cob", "cob2": "key_show_cob", "iob1": "key_show_iob", "iob2": "key_show_iob", + "day": "key_show_date", "month": "key_show_date", "loop": "key_show_loop_status", + "reservoir": "key_show_reservoir_level", "basalRate": "key_show_temp_basal", +} +PREF_DEFAULTS = {key: True for key in VIEW_PREFS.values()} | {"key_show_date": False, "key_show_detailed_iob": False, "key_units": True} +SAMPLES = {"time": "10:08", "timePeriod": "AM", "sgv": "106", "delta": "+5", "timestamp": "2'", "day": "16", "month": "OCT", + "cob2": "18g", "iob1": "IOB", "iob2": "2.40", "loop": "", "basalRate": "0.85U/h"} +BASELINE_TEXT_VIEWS = frozenset(("cob1", "cob2", "freetext4", "iob1", "iob2")) + + +def load_face(): + return json.loads((SOURCE / "CustomWatchface.json").read_text(encoding="utf-8")) + + +def resolve_pref(face, key, prefs): + result, visited = {}, set() + while key: + if key in visited: + raise ValueError(f"Preference cycle: {key}") + visited.add(key) + rule = face["dynPref"][key] + branch = rule[str(prefs.get(rule["prefKey"], PREF_DEFAULTS.get(rule["prefKey"], True))).lower()] + result.update({k: v for k, v in branch.items() if k != "dynPref"}) + key = branch.get("dynPref", "") + return result + + +def style_for(face, key, prefs): + view = face[key] + return resolve_pref(face, view["dynPref"], prefs) if "dynPref" in view else {} + + +def select_drawable(style, value): + """Model DynProvider's image index, including its exclusive upper bound.""" + if style["valueKey"] != "reservoir": + return style["image1"] + if value is None or math.isnan(value): + return style["invalidImage"] + count = 0 + while f"image{count + 1}" in style: + count += 1 + steps = count if "invalidImage" in style else count - 1 + minimum, maximum = style["minData"], style["maxData"] + value = minimum if value < minimum else maximum * 0.9999 if value >= maximum else value + index = int(1 + (value - minimum) * steps / (maximum - minimum)) + return style[f"image{index}"] + + +def font_for(view, size): + return ImageFont.truetype(str(FONTS / f"{view['font']}.ttf"), size) + + +def point(center, radius, angle): + angle = math.radians(angle) + return center + radius * math.cos(angle), center + radius * math.sin(angle) + + +def arc(draw, center, radius, stroke, start, sweep, color, scale): + outer = radius + stroke / 2 + box = tuple(n * scale for n in (center - outer, center - outer, center + outer, center + outer)) + draw.arc(box, start, start + sweep, fill=color, width=stroke * scale) + for angle in (start, start + sweep): + x, y = point(center, radius, angle) + r = stroke / 2 + draw.ellipse(tuple(n * scale for n in (x - r, y - r, x + r, y + r)), fill=color) + + +def trend_triangles(name): + _, angle, count = TREND_ARROWS[name] + spec = ART["trend"] + center, radius = spec["size"] / 2, spec["radius"] + half_base = spec["arrowHalfBase"] + spacing = math.degrees(half_base * 2.5 / radius) + result = [] + for index in range(count): + radians = math.radians(angle + (index - (count - 1) / 2) * spacing) + dx, dy = math.cos(radians), math.sin(radians) + # Set the larger base slightly inside the ring so the tip stays on canvas. + x, y = point(center, radius + spec["stroke"] / 2 - spec["arrowInset"], math.degrees(radians)) + result.append(((x + spec["arrowHeight"] * dx, y + spec["arrowHeight"] * dy), + (x - half_base * dy, y + half_base * dx), (x + half_base * dy, y - half_base * dx))) + return result + + +def resource_filename(name): + # Keep white trend masks as PNG: native bitmap tinting must remain unchanged. + return f"{name}.svg" if name in GAUGE_NAMES or name in ICON_NAMES else f"{name}.png" + + +def gauge_svg(name): + spec = ART["reservoir"] + value = int(name.removeprefix("Reservoir")) + left, top, right, bottom = spec["crop"] + width, height = right - left, bottom - top + center, radius = ART["size"] / 2, spec["radius"] + + def path(sweep, color): + start = point(center, radius, spec["start"]) + end = point(center, radius, spec["start"] + sweep) + clockwise = int(sweep > 0) + return (f'') + + body = path(spec["sweep"], spec["track"]) + if value > 0: + body += path(spec["sweep"] * value / spec["maximum"], spec["color"]) + return (f'{body}').encode("utf-8") + + +def icon_svg(name): + """Reuse the phone overview's actual IcCarbs/IcBolus paths, without app edits.""" + spec = ART["icons"]["sources"][name] + source = (ROOT / spec["file"]).read_text(encoding="utf-8") + blocks = re.findall(r"path\([\s\S]*?\)\s*\{([^{}]*)\}", source) + if len(blocks) != 1 or "viewportWidth = 24f" not in source or "viewportHeight = 24f" not in source: + raise ValueError(f"Unsupported AAPS icon structure: {spec['file']}") + operations = {"moveTo": ("M", 2), "moveToRelative": ("m", 2), "lineTo": ("L", 2), + "lineToRelative": ("l", 2), "curveTo": ("C", 6), "curveToRelative": ("c", 6), "close": ("Z", 0)} + commands = [] + for line in blocks[0].strip().splitlines(): + if not line.strip(): + continue + match = re.fullmatch(r"\s*(\w+)\(([^)]*)\)\s*", line) + if not match or match[1] not in operations: + raise ValueError(f"Unsupported AAPS icon command: {line}") + command, count = operations[match[1]] + numbers = [float(n.strip().removesuffix("f")) for n in match[2].split(",") if n.strip()] + if len(numbers) != count: + raise ValueError(f"Wrong AAPS icon argument count: {line}") + commands.append(command + " ".join(f"{n:g}" for n in numbers)) + size = ART["icons"]["size"] + return (f'' + f'').encode("utf-8") + + +@lru_cache(maxsize=len(RESOURCE_NAMES)) +def resource_bytes(name): + if name in GAUGE_NAMES: + return gauge_svg(name) + if name in ICON_NAMES: + return icon_svg(name) + scale = 4 + size = ART["trend"]["size"] if name in TREND_ARROWS else ART["size"] + image = Image.new("RGBA", (size * scale, size * scale), ART["background"] if name == "Background" else (0, 0, 0, 0)) + draw = ImageDraw.Draw(image) + center = size / 2 + if name in TREND_ARROWS: + spec = ART["trend"] + radius, stroke = spec["radius"], spec["stroke"] + outer = radius + stroke / 2 + box = tuple(n * scale for n in (center - outer, center - outer, center + outer, center + outer)) + draw.ellipse(box, outline=(255, 255, 255, spec["trackAlpha"]), width=stroke * scale) + angle = TREND_ARROWS[name][1] + if angle is not None: + arc(draw, center, radius, stroke, angle - spec["sweep"] / 2, spec["sweep"], "white", scale) + for triangle in trend_triangles(name): + draw.polygon([(x * scale, y * scale) for x, y in triangle], fill="white") + elif name == "Background": + edge, ticks = ART["edge"], ART["ticks"] + draw.ellipse(tuple(n * scale for n in (center - edge["radius"], center - edge["radius"], center + edge["radius"], center + edge["radius"])), + outline=edge["color"], width=edge["stroke"] * scale) + for angle in ticks["angles"]: + ends = [point(center, ticks["radius"] - offset, angle) for offset in (0, ticks["length"])] + draw.line([(x * scale, y * scale) for x, y in ends], fill=ticks["color"], width=ticks["stroke"] * scale) + elif name != "Empty": + raise ValueError(f"Unknown resource: {name}") + if name == "Empty": + image = image.crop(tuple(n * scale for n in ART["reservoir"]["crop"])) + size = image.width // scale + output = io.BytesIO() + image.resize((size, size), Image.Resampling.LANCZOS).save(output, format="PNG") + return output.getvalue() + + +@lru_cache(maxsize=len(RESOURCE_NAMES)) +def resource_image(name): + data = resource_bytes(name) + if resource_filename(name).endswith(".svg"): + # Render the actual packaged SVG for local previews, not a separate artwork model. + # resvg is not AndroidSVG; on-watch rendering remains unverified. + data = svg_to_bytes(svg_string=data.decode("utf-8")) + return Image.open(io.BytesIO(data)).convert("RGBA") + + +def baseline_y(font, height): + """Center a font line, not each string's ink; descenders keep the same baseline.""" + ascent, descent = font.getmetrics() + return (height + ascent - descent) / 2 + + +def text_left(view, width, text_width): + gravity = view.get("gravity", "center") + return 0 if gravity == "left" else width - text_width if gravity == "right" else (width - text_width) / 2 + + +def text_baseline(view, font, height): + # Native LEFT/RIGHT map to START/END without CENTER_VERTICAL, so text is top-aligned. + # Pillow metrics approximate Android's font padding; verify the result on the watch. + return baseline_y(font, height) if view.get("gravity", "center") == "center" else font.getmetrics()[0] + + +def text_bounds(face, key, text, prefs): + view, style = face[key], style_for(face, key, prefs) + text = style.get("textvalue1", view.get("textvalue", text)) + if view.get("allCaps"): + text = text.upper() + font = font_for(view, style.get("textsize1", view["textsize"])) + bounds = font.getbbox(text) + width, height = font.getlength(text), bounds[3] - bounds[1] + left = view["leftmargin"] + style.get("leftOffset1", 0) + text_left(view, view["width"], width) + cy = view["topmargin"] + style.get("topOffset1", 0) + view["height"] / 2 + if key in BASELINE_TEXT_VIEWS: + baseline = cy - view["height"] / 2 + text_baseline(view, font, view["height"]) + bounds = font.getbbox(text, anchor="ls") + return left, baseline + bounds[1], left + width, baseline + bounds[3] + top = cy - height / 2 if view.get("gravity", "center") == "center" else cy - view["height"] / 2 + return left, top, left + width, top + height + + +def draw_text(image, face, key, value, prefs, scale, color=None): + view, style = face[key], style_for(face, key, prefs) + text = style.get("textvalue1", view.get("textvalue", value)) + if view.get("allCaps"): + text = text.upper() + if not text: + return + text_size = style.get("textsize1", view["textsize"]) + if text_size <= 0: + return + font = font_for(view, text_size * scale) + layer = Image.new("RGBA", (view["width"] * scale, view["height"] * scale)) + draw = ImageDraw.Draw(layer) + bounds = font.getbbox(text) + x = text_left(view, layer.width, font.getlength(text)) + if key in BASELINE_TEXT_VIEWS: + y, anchor = text_baseline(view, font, layer.height), "ls" + else: + top = (layer.height - (bounds[3] - bounds[1])) / 2 if view.get("gravity", "center") == "center" else 0 + y, anchor = top - bounds[1], "la" + draw.text((x, y), text, font=font, anchor=anchor, fill=color or style.get("fontColor1", view.get("fontColor", "#F3F7FA"))) + image.alpha_composite(layer, ((view["leftmargin"] + style.get("leftOffset1", 0)) * scale, + (view["topmargin"] + style.get("topOffset1", 0)) * scale)) + + +def render(face, *, state="normal", trend="ArrowFlat", detailed=False, hour12=False, prefs=None, values=None, reservoir=120): + """Synthetic preview. Native loop icons, font metrics and stale styling may differ.""" + scale = 3 + settings = PREF_DEFAULTS | {"key_show_date": True, "key_show_detailed_iob": detailed, "key_units": state != "mmol"} | (prefs or {}) + samples = SAMPLES | ({"iob1": "2.40", "iob2": "(1.60|0.80)"} if settings["key_show_detailed_iob"] else {}) + # The checked phone code sends 0 and an empty string for unavailable reservoir. + samples["reservoir"] = f"{reservoir:.0f} U" if reservoir is not None and reservoir > 0 else "" + if state == "mmol": + samples["sgv"] = "5.9" + elif state == "high": + samples["sgv"] = "248" + elif state == "low": + samples["sgv"] = "58" + elif state == "stale": + samples.update(timestamp="18'", loop="") + elif state == "missing": + samples.update(sgv="---", timestamp="--", loop="") + trend = "ArrowNone" + samples.update(values or {}) + color = face[{"high": "highColor", "low": "lowColor"}.get(state, "midColor")] + image = resource_image("Background").resize((400 * scale, 400 * scale), Image.Resampling.LANCZOS) + # Match the native image lookup, then place the cropped gauge at its view origin. + view = face["cover_chart"] + name = select_drawable(style_for(face, "cover_chart", settings), 0 if reservoir is None else reservoir) + gauge = resource_image(name).resize((view["width"] * scale, view["height"] * scale), Image.Resampling.LANCZOS) + image.alpha_composite(gauge, (view["leftmargin"] * scale, view["topmargin"] * scale)) + if settings["key_show_direction"]: + view = face["direction"] + ring = resource_image(trend).resize((view["width"] * scale, view["height"] * scale), Image.Resampling.LANCZOS) + tinted = Image.new("RGBA", ring.size, color) + tinted.putalpha(ring.getchannel("A")) + image.alpha_composite(tinted, (view["leftmargin"] * scale, view["topmargin"] * scale)) + for key, view in face.items(): + if not isinstance(view, dict) or "textsize" not in view or view.get("visibility") != "visible": + continue + if key in VIEW_PREFS and not settings[VIEW_PREFS[key]]: + continue + if key == "timePeriod" and not hour12: + continue + style = style_for(face, key, settings) + if "image1" in style: + # CWF supports a preference-controlled drawable as TextView background. + drawable = resource_image(style["image1"]).resize((view["width"] * scale, view["height"] * scale), Image.Resampling.LANCZOS) + image.alpha_composite(drawable, ((view["leftmargin"] + style.get("leftOffset1", 0)) * scale, + (view["topmargin"] + style.get("topOffset1", 0)) * scale)) + if key == "loop": + # Approximation only; the ZIP keeps the native grey/green/red loop drawable. + draw = ImageDraw.Draw(image) + x, y, w, h = (view[k] * scale for k in ("leftmargin", "topmargin", "width", "height")) + loop_color = "#888888" if state == "missing" else "#CF0000" if state == "stale" else "#00CF00" + for start in (25, 205): + draw.arc((x + scale, y + scale, x + w - scale, y + h - scale), start, start + 130, fill=loop_color, width=3 * scale) + text_color = color if key == "sgv" else face["reservoirColor"] if key == "reservoir" else "#FF0000" if key == "timestamp" and state in ("stale", "missing") else None + draw_text(image, face, key, samples.get(key, ""), settings, scale, text_color) + if state == "stale" and settings["key_show_bg"]: + bounds = text_bounds(face, "sgv", samples["sgv"], settings) + y = (bounds[1] + bounds[3]) / 2 + ImageDraw.Draw(image).line([(bounds[0] * scale, y * scale), (bounds[2] * scale, y * scale)], fill=color, width=3 * scale) + mask = Image.new("L", image.size) + ImageDraw.Draw(mask).ellipse((0, 0, image.width - 1, image.height - 1), fill=255) + image.putalpha(mask) + return image.resize((400, 400), Image.Resampling.LANCZOS) + + +def preview_bytes(face): + # Only the gallery thumbnail uses an indexed palette. Live field colors and + # trend masks are not quantized. Full-color state sheets remain available. + preview = io.BytesIO() + render(face).quantize(colors=256, method=Image.Quantize.FASTOCTREE, dither=Image.Dither.NONE).save(preview, format="PNG", optimize=True) + return preview.getvalue() + + +def archive_bytes(face): + files = {"CustomWatchface.json": (SOURCE / "CustomWatchface.json").read_bytes(), "CustomWatchface.png": preview_bytes(face)} + files.update({resource_filename(name): resource_bytes(name) for name in RESOURCE_NAMES}) + output = io.BytesIO() + with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for name, data in sorted(files.items()): + entry = zipfile.ZipInfo(name, (2026, 10, 16, 0, 0, 0)) + entry.compress_type = zipfile.ZIP_DEFLATED + entry.external_attr = 0o644 << 16 + archive.writestr(entry, data) + package = output.getvalue() + if len(package) > MAX_PACKAGE_BYTES: + raise ValueError(f"Watchface ZIP is {len(package)} bytes, over the {MAX_PACKAGE_BYTES}-byte transport budget.") + return package + + +def write_sheet(face, path, title, states, columns): + rows = math.ceil(len(states) / columns) + sheet = Image.new("RGB", (24 + columns * 420, 64 + rows * 452), "#0B1014") + draw = ImageDraw.Draw(sheet) + font = font_for({"font": "roboto_condensed_regular"}, 22) + draw.text((24, 14), f"AAPS SPORT / {title} / SYNTHETIC DATA", font=font, fill="#D8E1E7") + for index, (label, kwargs) in enumerate(states): + x, y = 24 + index % columns * 420, 64 + index // columns * 452 + draw.text((x + 8, y), label, font=font, fill="#ABB8C2") + preview = render(face, **kwargs) + sheet.paste(preview, (x, y + 32), preview) + sheet.save(path) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true", help="Check the ZIP against the sources, without writing files") + args = parser.parse_args() + face = load_face() + package = archive_bytes(face) + if args.check: + if not ASSET.exists() or ASSET.read_bytes() != package: + raise SystemExit("AAPS Sport.zip is missing or stale. Run the builder.") + print("AAPS Sport.zip matches its sources.") + return + ASSET.write_bytes(package) + (SOURCE / "CustomWatchface.png").write_bytes(preview_bytes(face)) + write_sheet(face, SOURCE / "preview-states.png", "DESIGN PREVIEW", ( + ("Normal / mg/dL", {}), ("mmol/L / rising", {"state": "mmol", "trend": "Arrow45Up"}), + ("12-hour / detailed IOB", {"detailed": True, "hour12": True}), + ("High / double up", {"state": "high", "trend": "ArrowDoubleUp"}), + ("Low / falling", {"state": "low", "trend": "ArrowSingleDown"}), + ("Old reading / old loop", {"state": "stale"}), + ("Missing reading", {"state": "missing"}), + ("Larger / negative / temp basal", {"values": {"cob2": "120(40)g", "iob2": "-12.34", "timestamp": "60'", "basalRate": "120%"}}), + ("Optional fields off", {"prefs": {key: False for key in VIEW_PREFS.values()}}), + ), 3) + write_sheet(face, SOURCE / "preview-trends.png", "TREND RING", tuple( + (data[0].replace("_", " "), {"trend": name}) for name, data in TREND_ARROWS.items()), 4) + write_sheet(face, SOURCE / "preview-reservoir.png", "RESERVOIR / FULL AT 200 U", ( + ("No amount / native zero", {"reservoir": None}), + ("40 U / 20%", {"reservoir": 40}), ("100 U / 50%", {"reservoir": 100}), + ("160 U / 80%", {"reservoir": 160}), ("200 U / full", {"reservoir": 200}), + ("250 U / capped arc", {"reservoir": 250}), + ), 3) + print(f"Created {ASSET}") + print(f"ZIP size: {len(package):,} bytes; budget: {MAX_PACKAGE_BYTES:,} bytes") + print(f"Synthetic previews: {SOURCE / 'preview-states.png'}") + + +if __name__ == "__main__": + main() diff --git a/wear/watchfaces/sport/preview-reservoir.png b/wear/watchfaces/sport/preview-reservoir.png new file mode 100644 index 000000000000..155ca00c1e45 Binary files /dev/null and b/wear/watchfaces/sport/preview-reservoir.png differ diff --git a/wear/watchfaces/sport/preview-states.png b/wear/watchfaces/sport/preview-states.png new file mode 100644 index 000000000000..43eaf3ef5c04 Binary files /dev/null and b/wear/watchfaces/sport/preview-states.png differ diff --git a/wear/watchfaces/sport/preview-trends.png b/wear/watchfaces/sport/preview-trends.png new file mode 100644 index 000000000000..c4faf223640b Binary files /dev/null and b/wear/watchfaces/sport/preview-trends.png differ diff --git a/wear/watchfaces/sport/requirements.txt b/wear/watchfaces/sport/requirements.txt new file mode 100644 index 000000000000..42dd5e65d7dc --- /dev/null +++ b/wear/watchfaces/sport/requirements.txt @@ -0,0 +1,2 @@ +Pillow==12.1.1 +resvg-py==0.5.0 diff --git a/wear/watchfaces/sport/test_watchface.py b/wear/watchfaces/sport/test_watchface.py new file mode 100644 index 000000000000..58865c610720 --- /dev/null +++ b/wear/watchfaces/sport/test_watchface.py @@ -0,0 +1,732 @@ +"""Static CWF/design tests. These do not run the Android renderer.""" + +import io +import itertools +import json +import math +import re +import unittest +from unittest.mock import patch +import xml.etree.ElementTree as ET +import zipfile + +from PIL import Image, ImageChops, ImageFilter + +import build_watchface as build + + +def strict_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError(f"Duplicate key: {key}") + result[key] = value + return result + + +def contrast_on_black(color): + channels = [int(color[n:n + 2], 16) / 255 for n in (1, 3, 5)] + linear = [c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 for c in channels] + return (sum(a * b for a, b in zip(linear, (0.2126, 0.7152, 0.0722))) + 0.05) / 0.05 + + +class SportWatchfaceTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.face = json.loads((build.SOURCE / "CustomWatchface.json").read_text(encoding="utf-8"), object_pairs_hook=strict_object) + cls.renderer = (build.ROOT / "wear/src/main/kotlin/app/aaps/wear/watchfaces/CustomWatchface.kt").read_text(encoding="utf-8") + cls.shared = build.ROOT / "shared/impl/src/commonMain/kotlin/app/aaps/shared/impl/weardata" + + def test_metadata_and_version_are_accepted_by_the_checkout(self): + self.assertEqual(self.face["metadata"]["name"], "AAPS Sport") + self.assertEqual(self.face["metadata"]["author_version"], "1.18") + supported = (build.ROOT / "core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/ResFormat.kt").read_text(encoding="utf-8") + app_version = re.search(r'CUSTOM_VERSION = "([^"]+)"', supported).group(1) + self.assertLessEqual(int(self.face["metadata"]["cwf_version"].split(".")[0]), int(app_version.split(".")[0])) + self.assertFalse(any(k.startswith("key_") or k == "cwf_authorization" for k in self.face["metadata"])) + + def test_only_supported_views_keys_preferences_and_fonts_are_used(self): + view_keys = dict((key, symbol) for symbol, key in re.findall(r'\b([A-Z0-9_]+)\("([^"]+)"', (build.ROOT / "shared/impl/src/androidMain/kotlin/app/aaps/shared/impl/weardata/ViewKeys.kt").read_text(encoding="utf-8"))) + json_keys = set(re.findall(r'\("([^"]+)"', (self.shared / "JsonKeys.kt").read_text(encoding="utf-8"))) + pref_keys = set(re.findall(r'\("([^"]+)"', (self.shared / "JsonKeyValues.kt").read_text(encoding="utf-8"))) + meta = (build.ROOT / "core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/CwfMetaDataKey.kt").read_text(encoding="utf-8") + pref_keys.update(re.findall(r'\("(key_[^"]+)"', meta)) + for key, view in self.face.items(): + if not isinstance(view, dict) or "width" not in view: + continue + self.assertIn(key, view_keys) + self.assertIn(f"ViewKeys.{view_keys[key]}.key", self.renderer) + self.assertTrue(set(view) <= json_keys, (key, set(view) - json_keys)) + if "font" in view: + self.assertTrue((build.FONTS / f"{view['font']}.ttf").exists()) + self.assertIn(f'("{view["font"]}"', (self.shared / "JsonKeyValues.kt").read_text(encoding="utf-8")) + for rule in self.face["dynPref"].values(): + self.assertIn(rule["prefKey"], pref_keys) + for branch in (rule["true"], rule["false"]): + self.assertTrue({re.sub(r"\d+$", "", k) for k in branch} <= json_keys) + + def test_no_chart_no_battery_no_extra_live_fields(self): + live = {key for key, view in self.face.items() if isinstance(view, dict) and view.get("visibility") == "visible"} + self.assertEqual(live, {"background", "cover_chart", "complication1", "complication2", "complication3", + "direction", "sgv", "timestamp", "delta", "time", "timePeriod", + "day", "month", "cob1", "cob2", "iob1", "iob2", "loop", "reservoir", "basalRate", + "freetext1", "freetext2", "freetext3", "freetext4"}) + self.assertEqual(self.face["chart"]["visibility"], "gone") + self.assertFalse(any("battery" in key for key in self.face)) + self.assertFalse(self.face["enableSecond"]) + + def test_medical_values_and_warnings_stay_native(self): + for key in ("sgv", "timestamp", "direction", "loop", "reservoir"): + for override in ("dynPref", "dynData", "dynValue", "textvalue", "color", "background"): + self.assertNotIn(override, self.face[key], (key, override)) + for key in ("time", "timePeriod", "day", "month", "cob2", "iob1", "iob2", "basalRate"): + self.assertNotIn("textvalue", self.face[key]) + self.assertNotIn("dynValue", self.face[key]) + self.assertIn("binding.direction.setImageDrawable(TrendArrowMap.drawable(singleBg[0]))", self.renderer) + self.assertIn("binding.loop.setBackgroundResource(R.drawable.loop_green_25)", self.renderer) + self.assertIn("binding.reservoir.setTextColor(reservoirColor(0))", self.renderer) + self.assertNotIn("reservoirWarningColor", self.face) + self.assertNotIn("reservoirUrgentColor", self.face) + + def test_reservoir_gauge_uses_native_numeric_data_and_a_200_u_scale(self): + spec = build.ART["reservoir"] + self.assertEqual((spec["maximum"], spec["increment"]), (200, 4)) + self.assertEqual((spec["start"], spec["sweep"]), (90, -90)) + self.assertEqual(spec["color"], "#65DEED") + self.assertEqual(self.face["reservoirColor"], spec["color"]) + style = build.style_for(self.face, "cover_chart", {}) + self.assertEqual(style["valueKey"], "reservoir") + self.assertEqual(style["minData"], 0) + # Native bins have an exclusive upper end. 204 gives 51 bins of 4 U: + # index 1 = 0 U and index 51 starts at exactly 200 U, not below it. + self.assertEqual(style["maxData"], 204) + self.assertEqual(style["invalidImage"], "Empty") + self.assertEqual([style[f"image{n + 1}"] for n in range(51)], list(build.GAUGE_NAMES)) + self.assertEqual(len(build.GAUGE_NAMES), 51) + self.assertIn("ValueMap.RESERVOIR -> cwf.status[0].reservoir", self.renderer) + self.assertIn("get() = dynDrawable.size - 1", self.renderer) + self.assertIn("dataRange.maxData * 0.9999", self.renderer) + for rule in self.face["dynPref"]: + for prefs in ({}, {"key_show_reservoir_level": False}, {"key_show_detailed_iob": True}): + style = build.resolve_pref(self.face, rule, prefs) + self.assertIn(style.get("valueKey"), ("day", "reservoir"), rule) + self.assertNotIn("dynData", self.face) + + def test_native_step_selection_handles_every_boundary_and_caps_at_200(self): + style = build.style_for(self.face, "cover_chart", {}) + samples = [n / 4 for n in range(2001)] + [-1, -0.001, 3.9999, 199.9999, 200, 203.9999, 204, 1000] + for value in samples: + expected = max(0, min(200, math.floor(value / 4) * 4)) + self.assertEqual(build.select_drawable(style, value), f"Reservoir{expected:03d}", value) + self.assertEqual(build.select_drawable(style, None), "Empty") + self.assertEqual(build.select_drawable(style, float("nan")), "Empty") + + def test_reservoir_palette_matches_insulin_without_changing_cob(self): + blue = "#65DEED" + self.assertEqual(build.ART["reservoir"]["color"], blue) + self.assertEqual(build.ART["reservoir"]["track"], "#173238") + self.assertEqual(self.face["reservoirColor"], blue) + for key in ("freetext3", "basalRate", "iob1", "iob2", "freetext4"): + self.assertEqual(self.face[key]["fontColor"], blue, key) + self.assertEqual(build.ART["icons"]["sources"]["IobIcon"]["color"], blue) + for key in ("cob1", "cob2"): + self.assertEqual(self.face[key]["fontColor"], "#FFAB5C", key) + self.assertEqual(build.ART["icons"]["sources"]["CobIcon"]["color"], "#FFAB5C") + # Let native warning/urgent colors override the normal reservoir amount. + self.assertNotIn("fontColor", self.face["reservoir"]) + self.assertNotIn("reservoirWarningColor", self.face) + self.assertNotIn("reservoirUrgentColor", self.face) + + def test_cropped_gauge_images_grow_and_fit_their_view(self): + spec = build.ART["reservoir"] + view = self.face["cover_chart"] + self.assertEqual((view["leftmargin"], view["topmargin"], view["width"], view["height"]), (192, 192, 208, 208)) + self.assertEqual(spec["crop"], [192, 192, 400, 400]) + self.assertEqual(build.resource_image("Empty").getchannel("A").getextrema(), (0, 0)) + fill = tuple(int(spec["color"][n:n + 2], 16) for n in (1, 3, 5)) + track = tuple(int(spec["track"][n:n + 2], 16) for n in (1, 3, 5)) + channel = max(range(3), key=lambda index: fill[index] - track[index]) + threshold = (fill[channel] + track[channel]) / 2 + + def filled_pixels(image): + # Separate bright fill from the dim track without rejecting blended edges. + return sum(1 for pixel in image.get_flattened_data() if pixel[3] > 200 and pixel[channel] > threshold) + + previous = -1 + for name in build.GAUGE_NAMES: + image = build.resource_image(name) + self.assertEqual(image.size, (208, 208)) + bright = filled_pixels(image) + self.assertGreater(bright, previous) + previous = bright + self.assertGreater(previous, 2000) + self.assertEqual(filled_pixels(build.resource_image("Reservoir000")), 0) + for angle in (80, 60, 40, 20, 5): + x, y = build.point(200, spec["radius"], angle) + point = round(x - view["leftmargin"]), round(y - view["topmargin"]) + self.assertGreater(build.resource_image("Reservoir200").getpixel(point)[1], 200) + self.assertLess(build.resource_image("Reservoir000").getpixel(point)[1], 100) + + def test_svg_gauges_preserve_crop_colors_caps_and_all_51_sweeps(self): + spec = build.ART["reservoir"] + ns = "{http://www.w3.org/2000/svg}" + for value, name in zip(build.GAUGE_VALUES, build.GAUGE_NAMES): + root = ET.fromstring(build.resource_bytes(name)) + self.assertEqual(root.tag, ns + "svg") + self.assertEqual(root.attrib, {"width": "208", "height": "208", "viewBox": "192 192 208 208"}) + paths = list(root) + self.assertEqual(len(paths), 1 if value == 0 else 2) + for index, path in enumerate(paths): + self.assertEqual(path.tag, ns + "path") + self.assertEqual(set(path.attrib), {"fill", "stroke", "stroke-width", "stroke-linecap", "d"}) + self.assertEqual(path.attrib["fill"], "none") + self.assertEqual(path.attrib["stroke-linecap"], "round") + self.assertEqual(path.attrib["stroke-width"], str(spec["stroke"])) + self.assertEqual(path.attrib["stroke"], spec["track"] if index == 0 else spec["color"]) + self.assertRegex(path.attrib["d"], r'^M [-\d.]+ [-\d.]+ A \d+ \d+ 0 0 0 [-\d.]+ [-\d.]+$') + numbers = [float(n) for n in re.findall(r"-?\d+(?:\.\d+)?", path.attrib["d"])] + self.assertEqual(numbers[:2], [200, 384]) + self.assertEqual(numbers[2:7], [184, 184, 0, 0, 0]) + sweep = spec["sweep"] if index == 0 else spec["sweep"] * value / spec["maximum"] + expected = build.point(200, spec["radius"], spec["start"] + sweep) + for actual, coordinate in zip(numbers[-2:], expected): + self.assertAlmostEqual(actual, coordinate, places=5) + + def test_gauge_is_lower_right_and_fills_from_bottom_toward_right(self): + spec = build.ART["reservoir"] + view = self.face["cover_chart"] + full = build.render(self.face, reservoir=200) + self.assertEqual(full.getpixel((70, 330)), build.resource_image("Background").getpixel((70, 330))) + self.assertGreater(full.getpixel((330, 330))[1], 200) + for amount in (40, 100, 160): + gauge = build.resource_image(f"Reservoir{amount:03d}") + for fraction, filled in ((amount / 400, True), ((amount + 200) / 400, False)): + angle = 90 - 90 * fraction + x, y = build.point(200, spec["radius"], angle) + pixel = gauge.getpixel((round(x - view["leftmargin"]), round(y - view["topmargin"]))) + self.assertEqual(pixel[1] > 150, filled, (amount, angle)) + + def test_lower_right_gauge_clears_native_text_samples_with_one_pixel_reserve(self): + gauge = Image.new("L", (400, 400)) + view = self.face["cover_chart"] + mask = build.resource_image("Reservoir200").getchannel("A").point(lambda alpha: 255 if alpha > 128 else 0) + gauge.paste(mask, (view["leftmargin"], view["topmargin"])) + gauge = gauge.filter(ImageFilter.MaxFilter(3)) + samples = (("iob1", "-12.34", True), ("iob2", "-12.34", False), ("iob2", "(-10.00|10.00)", True), + ("iob2", "(-10,00|10,00)", True), ("reservoir", "250 U", False), ("freetext3", "", False)) + for key, sample, detailed in samples: + for scale in (1, 3): + text = Image.new("RGBA", (400 * scale, 400 * scale)) + build.draw_text(text, self.face, key, sample, {"key_show_detailed_iob": detailed}, scale) + mask = text.getchannel("A").resize((400, 400), Image.Resampling.LANCZOS).point(lambda alpha: 255 if alpha > 128 else 0) + self.assertIsNone(ImageChops.multiply(mask, gauge).getbbox(), (key, sample, scale)) + + def test_compact_formats_have_native_loader_support_and_keep_png_trend_tinting(self): + loader = (build.ROOT / "shared/impl/src/androidMain/kotlin/app/aaps/shared/impl/weardata/ZipWatchfaceFormat.kt").read_text(encoding="utf-8") + extension = (build.ROOT / "shared/impl/src/androidMain/kotlin/app/aaps/shared/impl/weardata/ResDataExtension.kt").read_text(encoding="utf-8") + self.assertIn('entryName.substringBeforeLast(".")', loader) + self.assertIn("ResFormat.SVG", extension) + self.assertIn("SVG.getFromString(String(value))", extension) + self.assertIn("svg.renderToPicture()", extension) + for name in build.GAUGE_NAMES: + self.assertEqual(build.resource_filename(name), f"{name}.svg") + for name in build.TREND_ARROWS: + self.assertEqual(build.resource_filename(name), f"{name}.png") + Image.open(io.BytesIO(build.resource_bytes(name))).verify() + + def test_complete_zip_fits_single_message_budget_and_oversize_builds_are_rejected(self): + service = (build.ROOT / "plugins/sync/src/androidMain/kotlin/app/aaps/plugins/sync/wear/wearintegration/DataLayerListenerServiceMobile.kt").read_text(encoding="utf-8") + self.assertIn("sendMessage(rxWatchfacePath, it.payload)", service) + self.assertIn(".sendMessage(nodeId, path, data)", service) + self.assertLessEqual(len(build.archive_bytes(self.face)), build.MAX_PACKAGE_BYTES) + self.assertLess(build.MAX_PACKAGE_BYTES, 100_000) + with patch.object(build, "MAX_PACKAGE_BYTES", 1): + with self.assertRaisesRegex(ValueError, "transport budget"): + build.archive_bytes(self.face) + + def test_gallery_thumbnail_is_a_valid_indexed_png_not_the_live_artwork(self): + image = Image.open(io.BytesIO(build.preview_bytes(self.face))) + self.assertEqual(image.format, "PNG") + self.assertEqual(image.mode, "P") + self.assertEqual(image.size, (400, 400)) + self.assertLessEqual(len(image.getcolors()), 256) + self.assertEqual(build.resource_image("ArrowFlat").mode, "RGBA") + + def test_basal_is_live_native_text_not_a_fake_dynamic_arc(self): + self.assertNotIn("cover_plate", self.face) + self.assertNotIn("IobQuarter", build.RESOURCE_NAMES) + self.assertNotIn("CobQuarter", build.RESOURCE_NAMES) + self.assertNotIn("dynPref", self.face["basalRate"]) + self.assertNotIn("textvalue", self.face["basalRate"]) + self.assertNotIn("dynValue", self.face["basalRate"]) + self.assertEqual(self.face["basalRate"]["fontColor"], "#65DEED") + + def test_labels_frames_and_values_follow_visibility_preferences(self): + for pref, frame, label in (("key_show_reservoir_level", "reservoirGauge", "freetext3"), + ("key_show_temp_basal", None, "freetext2"), ("key_show_bg", None, "freetext1")): + if frame: + self.assertEqual(build.resolve_pref(self.face, frame, {pref: False})["image1"], "Empty") + self.assertNotEqual(build.resolve_pref(self.face, frame, {pref: True})["image1"], "Empty") + if label: + self.assertEqual(build.style_for(self.face, label, {pref: False})["textvalue1"], "") + self.assertNotEqual(build.style_for(self.face, label, {pref: True})["textvalue1"], "") + for pref, sample in (("key_show_reservoir_level", (330, 330)),): + visible = build.render(self.face) + hidden = build.render(self.face, prefs={pref: False}) + self.assertNotEqual(visible.getpixel(sample), hidden.getpixel(sample)) + self.assertEqual(hidden.getpixel(sample), (0, 0, 0, 255)) + # COB/IOB switches must not hide the independent reservoir gauge. + for pref in ("key_show_cob", "key_show_iob"): + self.assertEqual(build.render(self.face).getpixel((330, 330)), build.render(self.face, prefs={pref: False}).getpixel((330, 330))) + + def test_iob_total_stays_native_in_both_detail_modes(self): + for detailed in (False, True): + prefs = {"key_show_detailed_iob": detailed} + total = build.style_for(self.face, "iob1", prefs) + value = build.style_for(self.face, "iob2", prefs) + if detailed: + self.assertNotIn("textvalue1", total) + self.assertEqual(self.face["iob1"]["textsize"], 32) + self.assertEqual(value["textsize1"], 12) + self.assertEqual(value["topOffset1"], 38) + self.assertEqual(value["leftOffset1"], -16) + else: + # The ordinary native iob1 is just the heading; total is in iob2. + self.assertEqual(total["textvalue1"], "") + self.assertEqual(value["textsize1"], 32) + self.assertEqual(value["topOffset1"], 0) + self.assertEqual(value["leftOffset1"], 0) + self.assertNotIn("textvalue1", value) + self.assertEqual(build.style_for(self.face, "freetext4", prefs)["image1"], "IobIcon") + self.assertEqual(build.style_for(self.face, "freetext4", prefs)["textvalue1"], "") + + def test_units_follow_the_existing_units_preference(self): + for mgdl, label in ((True, "mg/dL"), (False, "mmol/L")): + self.assertEqual(build.style_for(self.face, "freetext1", {"key_units": mgdl})["textvalue1"], label) + + def test_view_bounds_and_font_line_reserve(self): + for key, view in self.face.items(): + if not isinstance(view, dict) or "width" not in view: + continue + self.assertGreater(view["width"], 0, key) + self.assertGreater(view["height"], 0, key) + self.assertGreaterEqual(view["leftmargin"], 0, key) + self.assertGreaterEqual(view["topmargin"], 0, key) + self.assertLessEqual(view["leftmargin"] + view["width"], 400, key) + for detailed in (False, True): + style = build.style_for(self.face, key, {"key_show_detailed_iob": detailed}) + self.assertGreaterEqual(view["leftmargin"] + style.get("leftOffset1", 0), 0, key) + self.assertLessEqual(view["leftmargin"] + style.get("leftOffset1", 0) + view["width"], 400, key) + self.assertLessEqual(view["topmargin"] + style.get("topOffset1", 0) + view["height"], 400, key) + if "textsize" in view: + size = style.get("textsize1", view["textsize"]) + self.assertGreaterEqual(view["height"], sum(build.font_for(view, size).getmetrics()) + 4, key) + for zoom in (0.9, 0.99, 1, 1.125, 1.2, 1.5): + line = sum(build.font_for(view, round(size * zoom * 100)).getmetrics()) / 100 + self.assertGreaterEqual(int(view["height"] * zoom), line + 4 * zoom, (key, zoom)) + + def test_time_is_large_central_and_larger_than_glucose(self): + time, glucose = self.face["time"], self.face["sgv"] + self.assertEqual(time["leftmargin"] + time["width"] / 2, 200) + self.assertLess(abs(time["topmargin"] + time["height"] / 2 - 200), 20) + self.assertEqual(time["textsize"], 92) + self.assertGreater(time["textsize"], glucose["textsize"] * 2) + self.assertLess(glucose["topmargin"] + glucose["height"], time["topmargin"]) + + def test_cob_and_iob_are_equal_larger_than_basal_and_reservoir(self): + cob, reservoir = self.face["cob2"], self.face["reservoir"] + self.assertEqual(cob["textsize"], 32) + self.assertEqual(reservoir["textsize"], 20) + self.assertGreater(cob["textsize"], reservoir["textsize"]) + self.assertEqual(self.face["basalRate"]["textsize"], reservoir["textsize"]) + self.assertEqual(self.face["freetext2"]["textsize"], self.face["freetext3"]["textsize"]) + self.assertEqual(self.face["freetext2"]["textsize"], 12) + self.assertEqual((cob["leftmargin"], cob["topmargin"]), (100, 286)) + self.assertEqual(self.face["cob1"]["leftmargin"], 72) + self.assertEqual((reservoir["leftmargin"] + reservoir["width"] / 2, reservoir["topmargin"] + reservoir["height"] / 2), (200, 361)) + + def test_cob_iob_rows_have_equal_type_baselines_and_icon_gaps(self): + geometry = ("height", "topmargin", "textsize") + for first, second in (("cob1", "freetext4"), ("cob2", "iob2"), ("cob2", "iob1")): + left, right = self.face[first], self.face[second] + self.assertEqual([left[k] for k in geometry], [right[k] for k in geometry]) + for icon_key, value_key in (("cob1", "cob2"), ("freetext4", "iob1"), ("freetext4", "iob2")): + icon, value = self.face[icon_key], self.face[value_key] + self.assertEqual((icon["width"], icon["height"]), (24, 24)) + self.assertEqual(value["leftmargin"] - icon["leftmargin"] - icon["width"], 4) + self.assertEqual(value["gravity"], "left") + # LEFT is top-aligned natively. The three-pixel field shift keeps + # the total baseline at its old centered-field position. + font = build.font_for(value, value["textsize"]) + self.assertEqual(value["topmargin"] + build.text_baseline(value, font, value["height"]), + 283 + build.baseline_y(font, value["height"])) + self.assertEqual(self.face["freetext4"]["leftmargin"] - self.face["cob2"]["leftmargin"] - self.face["cob2"]["width"], 4) + self.assertEqual(self.face["cob1"]["fontColor"], "#FFAB5C") + self.assertEqual(self.face["cob2"]["fontColor"], "#FFAB5C") + self.assertEqual(self.face["freetext4"]["fontColor"], "#65DEED") + for detailed in (False, True): + key = "iob1" if detailed else "iob2" + style = build.style_for(self.face, key, {"key_show_detailed_iob": detailed}) + self.assertEqual(style.get("textsize1", self.face[key]["textsize"]), self.face["cob2"]["textsize"]) + self.assertEqual(style.get("topOffset1", 0), 0) + + def test_cob_iob_digit_tops_match_without_any_heading_text(self): + for detailed in (False, True): + prefs = {"key_show_detailed_iob": detailed} + key = "iob1" if detailed else "iob2" + for icon in ("cob1", "freetext4"): + self.assertEqual(self.face[icon]["textvalue"], "") + self.assertEqual(build.style_for(self.face, icon, prefs)["textvalue1"], "") + for cob_text, iob_text in (("18g", "2.40"), ("120g", "-12.34"), ("0g", "0.00")): + cob = build.text_bounds(self.face, "cob2", cob_text, prefs) + iob = build.text_bounds(self.face, key, iob_text, prefs) + self.assertEqual(cob[1], iob[1], (detailed, cob_text, iob_text)) + + def test_short_and_long_totals_start_close_to_icons_in_both_iob_modes(self): + self.assertIn("LEFT(JsonKeyValues.LEFT.key, Gravity.START)", self.renderer) + for detailed in (False, True): + prefs = {"key_show_detailed_iob": detailed} + iob_key = "iob1" if detailed else "iob2" + for icon_key, value_key, samples in (("cob1", "cob2", ("0g", "9g", "18g", "120g", "120(40)g", "---")), + ("freetext4", iob_key, ("0.00", "2.40", "12,34", "-12.34", "---"))): + icon, value = self.face[icon_key], self.face[value_key] + right = icon["leftmargin"] + icon["width"] + for sample in samples: + bounds = build.text_bounds(self.face, value_key, sample, prefs) + self.assertEqual(bounds[0] - right, 4, (value_key, sample, detailed)) + self.assertLessEqual(bounds[2], value["leftmargin"] + value["width"]) + for scale in (1, 3): + picture = Image.new("RGBA", (400 * scale, 400 * scale)) + build.draw_text(picture, self.face, value_key, sample, prefs, scale) + ink = picture.getchannel("A").getbbox() + gap = ink[0] / scale - right + self.assertGreaterEqual(gap, 4, (value_key, sample, scale)) + # The digit "1" has extra blank space within its glyph. + self.assertLessEqual(gap, 7, (value_key, sample, scale)) + + def test_preview_digits_do_not_move_when_cob_has_a_descender(self): + for scale in (1, 3): + for key, sample in (("cob2", "18g"), ("iob1", "18"), ("iob2", "18")): + prefs = {"key_show_detailed_iob": key == "iob1"} + picture = Image.new("RGBA", (400 * scale, 400 * scale)) + build.draw_text(picture, self.face, key, sample, prefs, scale) + top = picture.getchannel("A").getbbox()[1] + if key == "cob2": + cob_top = top + else: + self.assertEqual(top, cob_top, (key, scale)) + + def test_entire_cob_iob_row_clears_clock_field_at_native_zoom_factors(self): + clock = self.face["time"] + for zoom in (0.9, 0.99, 1, 1.125, 1.2, 1.5): + clock_bottom = int(clock["topmargin"] * zoom) + int(clock["height"] * zoom) + for key in ("cob1", "cob2", "freetext4", "iob1", "iob2"): + self.assertGreaterEqual(int(self.face[key]["topmargin"] * zoom) - clock_bottom, 6, (key, zoom)) + + def test_aaps_icons_reuse_phone_overview_paths_and_stay_inside_gauge(self): + mappings = (build.ROOT / "core/ui/src/commonMain/kotlin/app/aaps/core/ui/compose/navigation/ElementTypeStyle.kt").read_text(encoding="utf-8") + self.assertRegex(mappings, r"ElementType.COB\s*-> IcCarbs") + self.assertRegex(mappings, r"ElementType.INSULIN\s*-> IcBolus") + commands = {"moveTo": "M", "moveToRelative": "m", "lineTo": "L", "lineToRelative": "l", "curveTo": "C", "curveToRelative": "c", "close": "Z"} + for name, key in (("CobIcon", "cob1"), ("IobIcon", "freetext4")): + source = (build.ROOT / build.ART["icons"]["sources"][name]["file"]).read_text(encoding="utf-8") + root = ET.fromstring(build.resource_bytes(name)) + self.assertEqual(root.attrib, {"width": "24", "height": "24", "viewBox": "0 0 24 24"}) + path = list(root)[0] + self.assertEqual(path.attrib["fill"], self.face[key]["fontColor"]) + original = re.findall(r"^\s*(moveToRelative|lineToRelative|curveToRelative|moveTo|lineTo|curveTo|close)\(([^)]*)\)", source, re.M) + packaged = re.findall(r"([MLCmlcZ])([^MLCmlcZ]*)", path.attrib["d"]) + self.assertEqual(len(original), len(packaged)) + for (operation, numbers), (svg_op, svg_numbers) in zip(original, packaged): + self.assertEqual(svg_op, commands[operation]) + self.assertEqual([float(n.strip().removesuffix("f")) for n in numbers.split(",") if n.strip()], + [float(n) for n in svg_numbers.split()]) + picture, view = build.resource_image(name), self.face[key] + self.assertEqual(picture.size, (24, 24)) + for y in range(24): + for x in range(24): + if picture.getpixel((x, y))[3] > 128: + limit = 178 if name == "CobIcon" else 189 + self.assertLess(math.hypot(view["leftmargin"] + x - 200, view["topmargin"] + y - 200), limit) + + def test_icons_follow_native_cob_iob_visibility_independently(self): + for detailed in (False, True): + for key, pref, name in (("cob1", "key_show_cob", "CobIcon"), ("freetext4", "key_show_iob", "IobIcon")): + shown = {"key_show_detailed_iob": detailed, pref: True} + hidden = shown | {pref: False} + self.assertEqual(build.style_for(self.face, key, shown)["image1"], name) + self.assertEqual(build.style_for(self.face, key, hidden)["image1"], "Empty") + view = self.face[key] + box = (view["leftmargin"], view["topmargin"], view["leftmargin"] + view["width"], view["topmargin"] + view["height"]) + self.assertNotEqual(build.render(self.face, prefs=shown).crop(box).tobytes(), build.render(self.face, prefs=hidden).crop(box).tobytes()) + self.assertIn("view.background = it", self.renderer) + + def test_top_glucose_and_basal_loop_groups_share_mirrored_axes(self): + ring = self.face["direction"] + glucose_axis = ring["leftmargin"] + ring["width"] / 2 + self.assertEqual(glucose_axis, 132) + for key in ("sgv", "delta", "freetext1"): + view = self.face[key] + self.assertEqual(view["leftmargin"] + view["width"] / 2, glucose_axis) + self.assertEqual((self.face["timestamp"]["leftmargin"], self.face["timestamp"]["topmargin"], self.face["timestamp"]["width"], self.face["timestamp"]["height"]), + (self.face["loop"]["leftmargin"], self.face["loop"]["topmargin"], self.face["loop"]["width"], self.face["loop"]["height"])) + self.assertEqual(self.face["loop"]["textsize"], 0) + for key in ("freetext2", "basalRate", "loop"): + view = self.face[key] + self.assertEqual(view["leftmargin"] + view["width"] / 2, 400 - glucose_axis) + self.assertLessEqual(view["topmargin"] + view["height"], self.face["time"]["topmargin"]) + self.assertLessEqual(self.face["freetext2"]["topmargin"] + self.face["freetext2"]["height"], self.face["basalRate"]["topmargin"]) + self.assertLess(self.face["basalRate"]["topmargin"] + self.face["basalRate"]["height"], self.face["loop"]["topmargin"]) + # Test the whole ring envelope after moving it toward the round display edge. + cx, cy = glucose_axis, ring["topmargin"] + ring["height"] / 2 + outer = build.ART["trend"]["radius"] + build.ART["trend"]["stroke"] / 2 - build.ART["trend"]["arrowInset"] + build.ART["trend"]["arrowHeight"] + self.assertLess(math.hypot(cx - 200, cy - 200) + outer, build.ART["edge"]["radius"]) + + def test_grouped_basal_and_loop_keep_independent_visibility_options(self): + normal = build.render(self.face) + no_basal = build.render(self.face, prefs={"key_show_temp_basal": False}) + no_loop = build.render(self.face, prefs={"key_show_loop_status": False}) + loop = self.face["loop"] + loop_box = (loop["leftmargin"], loop["topmargin"], loop["leftmargin"] + loop["width"], loop["topmargin"] + loop["height"]) + basal_box = (198, 40, 338, 92) + self.assertEqual(normal.crop(loop_box).tobytes(), no_basal.crop(loop_box).tobytes()) + self.assertNotEqual(normal.crop(loop_box).tobytes(), no_loop.crop(loop_box).tobytes()) + self.assertEqual(normal.crop(basal_box).tobytes(), no_loop.crop(basal_box).tobytes()) + self.assertNotEqual(normal.crop(basal_box).tobytes(), no_basal.crop(basal_box).tobytes()) + + def test_background_ticks_do_not_clutter_the_glucose_group(self): + background = build.resource_image("Background") + ring = self.face["direction"] + cx, cy = ring["leftmargin"] + ring["width"] / 2, ring["topmargin"] + ring["height"] / 2 + radius = build.ART["trend"]["radius"] - 5 + for x in range(int(cx - radius), int(cx + radius)): + for y in range(int(cy - radius), int(cy + radius)): + if math.hypot(x - cx, y - cy) < radius: + self.assertEqual(background.getpixel((x, y)), (0, 0, 0, 255)) + + def test_date_is_stacked_left_of_clock_without_shrinking_text(self): + day, month, time = (self.face[key] for key in ("day", "month", "time")) + for view in (day, month): + self.assertEqual(view["leftmargin"] + view["width"] / 2, 50) + self.assertEqual(view["textsize"], 18) + self.assertEqual(view["height"], 28) + self.assertEqual(day["topmargin"] + day["height"], month["topmargin"]) + self.assertEqual((day["topmargin"] + month["topmargin"] + month["height"]) / 2, + time["topmargin"] + time["height"] / 2) + for sample in ("00:00", "10:08", "12:59", "23:59", "11:11", "20:48"): + clock = build.text_bounds(self.face, "time", sample, {}) + for key, text in (("day", "31"), ("month", "SEPT"), ("month", "MÄR")): + date = build.text_bounds(self.face, key, text, {}) + self.assertGreaterEqual(clock[0] - date[2], 12, (sample, key, text)) + + def test_reservoir_text_is_centered_without_moving_vertically_or_shrinking(self): + label, amount = self.face["freetext3"], self.face["reservoir"] + self.assertEqual((label["topmargin"], amount["topmargin"]), (323, 342)) + for view in (label, amount): + self.assertEqual(view["leftmargin"] + view["width"] / 2, 200) + self.assertEqual(view["gravity"], "center") + self.assertEqual((label["textsize"], amount["textsize"]), (12, 20)) + self.assertEqual((label["width"], amount["width"]), (108, 136)) + for key, text in (("freetext3", ""), ("reservoir", "250 U")): + bounds = build.text_bounds(self.face, key, text, {}) + for x, y in itertools.product((bounds[0], bounds[2]), (bounds[1], bounds[3])): + self.assertLess(math.hypot(x - 200, y - 200), 178) + + def test_relocated_date_still_follows_its_visibility_setting(self): + shown = build.render(self.face, prefs={"key_show_date": True}) + hidden = build.render(self.face, prefs={"key_show_date": False}) + self.assertFalse(build.PREF_DEFAULTS["key_show_date"]) + for key in ("day", "month"): + view = self.face[key] + box = (view["leftmargin"], view["topmargin"], view["leftmargin"] + view["width"], view["topmargin"] + view["height"]) + self.assertNotEqual(shown.crop(box).tobytes(), hidden.crop(box).tobytes()) + self.assertEqual(shown.crop((90, 159, 342, 275)).tobytes(), hidden.crop((90, 159, 342, 275)).tobytes()) + + def test_text_samples_fit_fields_and_the_round_screen(self): + cases = {"time": ("23:59", "10:08", "12:59"), "timePeriod": ("AM", "PM"), + "sgv": ("106", "400", "22.2", "22,2", "---"), "delta": ("+12", "-12", "+5"), "timestamp": ("18'", "60'", "--"), + "day": ("1", "16", "31"), "month": ("JAN", "FEB", "MÄR", "APR", "MAI", "JUN", "JUL", "AUG", "SEPT", "OKT", "OCT", "NOV", "DEZ"), + "cob2": ("18g", "120g", "120(40)g", "---"), "iob1": ("-12.34", "12,34"), + "iob2": ("-12.34", "12,34"), + "reservoir": ("40 U", "200 U", "250 U", "500U", ""), + "basalRate": ("0.85U/h", "0,85U/h", "12.34U/h", "120%", "1000%", "")} + ring = self.face["direction"] + center = (ring["leftmargin"] + ring["width"] / 2, ring["topmargin"] + ring["height"] / 2) + for detailed in (False, True): + prefs = {"key_show_detailed_iob": detailed} + for key, samples in cases.items(): + if key == "iob2" and detailed: + samples = ("(1.60|0.80)", "(-10.00|10.00)", "(-10,00|10,00)") + for sample in samples: + with self.subTest(key=key, sample=sample, detailed=detailed): + bounds = build.text_bounds(self.face, key, sample, prefs) + self.assertLessEqual(bounds[2] - bounds[0], self.face[key]["width"]) + for x, y in itertools.product((bounds[0], bounds[2]), (bounds[1], bounds[3])): + # Keep the earlier conservative lower-left reserve. + # Actual right-side glyph/gauge clearance is tested separately. + limit = 178 if x < 200 and y > 200 else 189 + self.assertLess(math.hypot(x - 200, y - 200), limit) + if key in ("sgv", "delta"): + self.assertLess(math.hypot(x - center[0], y - center[1]), build.ART["trend"]["radius"] - 5) + + def test_key_text_groups_leave_visible_space(self): + for detailed in (False, True): + prefs = {"key_show_detailed_iob": detailed} + values = build.SAMPLES | ({"iob1": "-12.34", "iob2": "(-10.00|10.00)"} if detailed else {}) + for first, second in (("sgv", "delta"), ("freetext1", "sgv"), ("basalRate", "time"), + ("time", "timePeriod"), ("time", "cob2"), ("day", "month"), + ("cob2", "freetext3"), ("freetext3", "reservoir"), + ("freetext2", "basalRate"), ("basalRate", "loop"), ("loop", "time"), + ("time", "iob1" if detailed else "iob2")): + a = build.text_bounds(self.face, first, values.get(first, ""), prefs) + b = build.text_bounds(self.face, second, values.get(second, ""), prefs) + self.assertGreaterEqual(b[1] - a[3], 5, (first, second, detailed)) + if detailed: + total = build.text_bounds(self.face, "iob1", values["iob1"], prefs) + detail = build.text_bounds(self.face, "iob2", values["iob2"], prefs) + self.assertGreaterEqual(detail[1] - total[3], 5) + + def test_all_text_colors_have_contrast_on_black(self): + for color in (self.face["midColor"], self.face["highColor"], self.face["lowColor"]): + self.assertGreaterEqual(contrast_on_black(color), 4.5) + for view in self.face.values(): + if isinstance(view, dict) and "fontColor" in view: + self.assertGreaterEqual(contrast_on_black(view["fontColor"]), 4.5) + + def test_ring_is_selected_and_tinted_by_native_trend(self): + self.assertEqual(self.face["direction"], {"width": 146, "height": 146, "leftmargin": 59, "topmargin": 24, "visibility": "visible"}) + ring = self.face["direction"] + self.assertEqual((ring["leftmargin"] + ring["width"] / 2, ring["topmargin"] + ring["height"] / 2), (132, 97)) + res_map = (self.shared / "ResFileMap.kt").read_text(encoding="utf-8") + for name in build.TREND_ARROWS: + self.assertIn(f'("{name}")', res_map) + phone = (build.ROOT / "ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/BgInfoSection.kt").read_text(encoding="utf-8") + native = {key: (float(angle), int(count)) for key, angle, count in re.findall( + r'TrendArrow\.(\w+)\s*-> ArcIndicator\(centerAngle = (-?[\d.]+)f, sweepAngle = sweepAngle, triangleCount = (\d+)\)', phone)} + self.assertEqual(build.ART["trend"]["sweep"], float(re.search(r'val sweepAngle = ([\d.]+)f', phone).group(1))) + for _, (key, angle, count) in build.TREND_ARROWS.items(): + if key != "NONE": + self.assertEqual((angle, count), native[key]) + + def test_ring_resources_are_transparent_white_masks_with_correct_highlight(self): + center = build.ART["trend"]["size"] / 2 + radius = build.ART["trend"]["radius"] + for name, (_, angle, count) in build.TREND_ARROWS.items(): + image = build.resource_image(name) + self.assertEqual(image.size, (146, 146)) + self.assertEqual(image.getpixel((73, 73))[3], 0) + self.assertTrue(all((r, g, b) == (255, 255, 255) for r, g, b, a in image.get_flattened_data() if a)) + self.assertEqual(len(build.trend_triangles(name)), count) + for triangle in build.trend_triangles(name): + for x, y in triangle: + # The inset keeps the larger triangle inside its image canvas. + outer = radius + build.ART["trend"]["stroke"] / 2 - build.ART["trend"]["arrowInset"] + build.ART["trend"]["arrowHeight"] + self.assertLessEqual(math.hypot(x - center, y - center), outer + 1e-9) + self.assertLessEqual(outer, center - 2) + if angle is None: + self.assertLess(image.getchannel("A").getextrema()[1], 100) + else: + x, y = build.point(center, radius, angle) + self.assertGreater(image.getpixel((round(x), round(y)))[3], 220) + x, y = build.point(center, radius, angle + 180) + self.assertLess(image.getpixel((round(x), round(y)))[3], 100) + + def test_glucose_ring_is_six_pixels_thick_without_changing_its_radius(self): + spec = build.ART["trend"] + self.assertEqual((spec["size"], spec["radius"], spec["stroke"]), (146, 61, 6)) + image = build.resource_image("ArrowNone") + center = spec["size"] // 2 + width = sum(image.getpixel((x, center))[3] > 30 for x in range(center)) + self.assertEqual(width, 6) + # Compare the rendered track against the previous four-pixel version, + # bypassing the resource cache without editing any source file. + with patch.dict(spec, {"stroke": 4}): + previous = Image.open(io.BytesIO(build.resource_bytes.__wrapped__("ArrowNone"))).convert("RGBA") + previous_width = sum(previous.getpixel((x, center))[3] > 30 for x in range(center)) + self.assertEqual(previous_width, 4) + self.assertGreater(width, previous_width) + + def test_trend_markers_are_larger_without_clipping_or_changing_the_plain_ring(self): + spec = build.ART["trend"] + self.assertEqual((spec["arrowHeight"], spec["arrowHalfBase"], spec["arrowInset"]), (8, 11, 1)) + old_style = {"size": 140, "arrowHeight": 6, "arrowHalfBase": 9, "arrowInset": 1} + for name, (_, angle, count) in build.TREND_ARROWS.items(): + current = build.resource_image(name) + triangles = build.trend_triangles(name) + with patch.dict(spec, old_style): + previous = Image.open(io.BytesIO(build.resource_bytes.__wrapped__(name))).convert("RGBA") + if angle is None: + # Three pixels of extra transparent canvas on each side; + # the visible circle is unchanged at its original screen center. + self.assertEqual(current.crop((3, 3, 143, 143)).tobytes(), previous.tobytes()) + continue + self.assertEqual(len(triangles), count) + for a, b, c in triangles: + area = abs((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) / 2 + self.assertAlmostEqual(area, 88) + self.assertGreater(area, 6 * 9) + self.assertGreater(sum(alpha > 200 for alpha in current.getchannel("A").get_flattened_data()), + sum(alpha > 200 for alpha in previous.getchannel("A").get_flattened_data()), name) + for border in ((0, 0, 146, 1), (0, 145, 146, 146), (0, 0, 1, 146), (145, 0, 146, 146)): + self.assertLess(current.crop(border).getchannel("A").getextrema()[1], 128, name) + + def test_no_direction_is_distinct_from_flat_and_respects_toggle(self): + self.assertNotEqual(build.render(self.face, trend="ArrowNone").tobytes(), build.render(self.face).tobytes()) + self.assertEqual(build.render(self.face, state="missing").tobytes(), build.render(self.face, state="missing", trend="ArrowNone").tobytes()) + for name in build.TREND_ARROWS: + self.assertEqual(build.render(self.face, trend=name, prefs={"key_show_direction": False}).tobytes(), + build.render(self.face, trend="ArrowNone", prefs={"key_show_direction": False}).tobytes()) + + def test_preview_variants_render_and_keep_gauge_independent_of_glucose(self): + baseline = build.render(self.face) + for detailed, hour12 in itertools.product((False, True), repeat=2): + for state in ("normal", "mmol", "high", "low", "stale", "missing"): + image = build.render(self.face, state=state, detailed=detailed, hour12=hour12) + self.assertEqual(image.size, (400, 400)) + for point in ((330, 330), (330, 70)): + self.assertEqual(image.getpixel(point), baseline.getpixel(point)) + for pref in set(build.VIEW_PREFS.values()): + self.assertEqual(build.render(self.face, prefs={pref: False}).size, (400, 400)) + self.assertEqual(build.render(self.face, prefs={pref: False for pref in build.VIEW_PREFS.values()}).size, (400, 400)) + + def test_reservoir_previews_change_length_but_never_cap_the_native_number(self): + pictures = [build.render(self.face, reservoir=value) for value in (0, 40, 100, 160, 200, 250)] + self.assertEqual(len({picture.tobytes() for picture in pictures}), 6) + # Full-screen arc crops are equal above 200, while the native amount differs. + for box in ((370, 192, 400, 400), (192, 376, 300, 400)): + self.assertEqual(pictures[-2].crop(box).tobytes(), pictures[-1].crop(box).tobytes()) + field = self.face["reservoir"] + box = (field["leftmargin"], field["topmargin"], field["leftmargin"] + field["width"], field["topmargin"] + field["height"]) + self.assertNotEqual(pictures[-2].crop(box).tobytes(), pictures[-1].crop(box).tobytes()) + # The phone's unknown value is zero plus an empty native reservoir string. + self.assertEqual(build.render(self.face, reservoir=None).tobytes(), pictures[0].tobytes()) + + def test_zip_is_deterministic_complete_and_current(self): + package = build.archive_bytes(self.face) + self.assertEqual(package, build.archive_bytes(self.face)) + self.assertEqual(package, build.ASSET.read_bytes()) + with zipfile.ZipFile(io.BytesIO(package)) as archive: + self.assertIsNone(archive.testzip()) + expected = {"CustomWatchface.json", "CustomWatchface.png", *(build.resource_filename(name) for name in build.RESOURCE_NAMES)} + self.assertEqual(set(archive.namelist()), expected) + self.assertEqual(len(archive.namelist()), len(expected)) + self.assertEqual(json.loads(archive.read("CustomWatchface.json")), self.face) + self.assertEqual(archive.read("CustomWatchface.png"), (build.SOURCE / "CustomWatchface.png").read_bytes()) + for name in build.RESOURCE_NAMES: + filename = build.resource_filename(name) + self.assertEqual(archive.read(filename), build.resource_bytes(name)) + if filename.endswith(".svg"): + ET.fromstring(archive.read(filename)) + else: + Image.open(io.BytesIO(archive.read(filename))).verify() + for rule in self.face["dynPref"]: + for value in (False, True): + prefs = {self.face["dynPref"][rule]["prefKey"]: value} + style = build.resolve_pref(self.face, rule, prefs) + for key, name in style.items(): + if re.fullmatch(r"image\d+|invalidImage", key): + self.assertIn(build.resource_filename(name), expected) + + +if __name__ == "__main__": + unittest.main()