From 241166e2442e82e7c4a2b06beaee5ad295a584d7 Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Wed, 28 Oct 2026 14:18:44 +0100 Subject: [PATCH 01/27] libkeks: add the KEKS (J-PAKE) authentication code for Dexcom ONE+ / G7 New module :plugins:libkeks. It holds the KEKS J-PAKE / ExtraData handshake that a Dexcom ONE+ / G7 sensor needs before it sends glucose. Nothing uses it yet; the driver module comes in a later commit. Provenance: NightscoutFoundation/xDrip (GPL-3.0), pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15). The 24 Java files were TRANSLATED to Kotlin, they are not a verbatim copy. BouncyCastle and BigInteger are replaced by small Kotlin classes (KeksUInt, KeksP256, KeksEcdsa, KeksDer), Lombok is gone, and random, AES and logging are three expect/actual pairs. NOTICE lists every change. Every file, the tests included, has an SPDX header with the pin: GPL-3.0-only, or MIT for SHA256.kt, which keeps its MIT notice. Targets: Android and JVM only. No iOS targets yet, because nothing on iOS uses the module. commonMain has no project dependencies, no KSP and no Metro. :appshell adds every :plugins:* module to its commonMain. libkeks is a library, not a feature plugin, and has no Apple variant, so it would break every iOS build of :appshell and :ios:shell. It is now left out through a small PLUGIN_LIBRARIES list. How to check the translation: src/commonTest holds golden values recorded from the original Java + BouncyCastle code at the pin, including a full four digit pairing replayed message by message. The same 46 tests run in :plugins:libkeks:jvmTest and :plugins:libkeks:testAndroidHostTest (both are in the unit-tests CI command), and all pass. These are unit tests only; no test on a real sensor is claimed for this branch. Co-Authored-By: Claude Opus 5.5 (1M context) --- appshell/build.gradle.kts | 13 +- plugins/libkeks/NOTICE | 54 ++ plugins/libkeks/README.md | 23 + plugins/libkeks/build.gradle.kts | 51 ++ .../keks/crypto/KeksPlatformAndroid.kt | 55 ++ .../dexdrip/plugin/IPluginDA.kt | 55 ++ .../commonMain/kotlin/jamorham/keks/Calc.kt | 193 ++++++ .../commonMain/kotlin/jamorham/keks/Config.kt | 90 +++ .../kotlin/jamorham/keks/Context.kt | 94 +++ .../commonMain/kotlin/jamorham/keks/Curve.kt | 49 ++ .../kotlin/jamorham/keks/DSAChallenger.kt | 43 ++ .../kotlin/jamorham/keks/JECPoint.kt | 35 ++ .../kotlin/jamorham/keks/KeyPair.kt | 71 +++ .../commonMain/kotlin/jamorham/keks/Packet.kt | 76 +++ .../commonMain/kotlin/jamorham/keks/Plugin.kt | 559 ++++++++++++++++++ .../kotlin/jamorham/keks/Umbilical.kt | 44 ++ .../kotlin/jamorham/keks/crypto/KeksDer.kt | 96 +++ .../kotlin/jamorham/keks/crypto/KeksEcdsa.kt | 113 ++++ .../kotlin/jamorham/keks/crypto/KeksP256.kt | 260 ++++++++ .../jamorham/keks/crypto/KeksPlatform.kt | 91 +++ .../kotlin/jamorham/keks/crypto/KeksReplay.kt | 47 ++ .../kotlin/jamorham/keks/crypto/KeksUInt.kt | 394 ++++++++++++ .../keks/message/AuthChallengeTxMessage.kt | 36 ++ .../keks/message/AuthRequestTxMessage2.kt | 54 ++ .../keks/message/AuthStatusRxMessage.kt | 50 ++ .../jamorham/keks/message/BaseMessage.kt | 46 ++ .../keks/message/CertInfoRxMessage.kt | 54 ++ .../keks/message/CertInfoTxMessage.kt | 43 ++ .../keks/message/SignChallengeTxMessage.kt | 39 ++ .../kotlin/jamorham/keks/util/AESwrapper.kt | 30 + .../jamorham/keks/util/ByteArrayHashMap.kt | 40 ++ .../kotlin/jamorham/keks/util/KeksBuffer.kt | 105 ++++ .../kotlin/jamorham/keks/util/Log.kt | 35 ++ .../kotlin/jamorham/keks/util/Util.kt | 104 ++++ .../kotlin/jamorham/libkeks/Digest.kt | 39 ++ .../kotlin/jamorham/libkeks/SHA256.kt | 167 ++++++ .../kotlin/jamorham/keks/KeksBigIntTest.kt | 156 +++++ .../kotlin/jamorham/keks/KeksCurveTest.kt | 113 ++++ .../kotlin/jamorham/keks/KeksGolden.kt | 553 +++++++++++++++++ .../kotlin/jamorham/keks/KeksHandshakeTest.kt | 117 ++++ .../kotlin/jamorham/keks/KeksMessageTest.kt | 78 +++ .../jamorham/keks/KeksPrimitivesTest.kt | 120 ++++ .../kotlin/jamorham/keks/KeksProofTest.kt | 70 +++ .../kotlin/jamorham/keks/KeksSignatureTest.kt | 110 ++++ .../kotlin/jamorham/keks/KeksTestSupport.kt | 50 ++ .../jamorham/keks/crypto/KeksPlatformJvm.kt | 57 ++ settings.gradle | 1 + 47 files changed, 4772 insertions(+), 1 deletion(-) create mode 100644 plugins/libkeks/NOTICE create mode 100644 plugins/libkeks/README.md create mode 100644 plugins/libkeks/build.gradle.kts create mode 100644 plugins/libkeks/src/androidMain/kotlin/jamorham/keks/crypto/KeksPlatformAndroid.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/com/eveningoutpost/dexdrip/plugin/IPluginDA.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Calc.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Config.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Context.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Curve.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/DSAChallenger.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/JECPoint.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/KeyPair.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Packet.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Plugin.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Umbilical.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksDer.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksEcdsa.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksP256.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksPlatform.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksReplay.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksUInt.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthChallengeTxMessage.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthRequestTxMessage2.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthStatusRxMessage.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/BaseMessage.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoRxMessage.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoTxMessage.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/SignChallengeTxMessage.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/AESwrapper.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/ByteArrayHashMap.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/KeksBuffer.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Log.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Util.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/Digest.kt create mode 100644 plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/SHA256.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksBigIntTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksCurveTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksGolden.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksHandshakeTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksMessageTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksPrimitivesTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksProofTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksSignatureTest.kt create mode 100644 plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksTestSupport.kt create mode 100644 plugins/libkeks/src/jvmMain/kotlin/jamorham/keks/crypto/KeksPlatformJvm.kt diff --git a/appshell/build.gradle.kts b/appshell/build.gradle.kts index a2517e8f9c6c..7e67007082ab 100644 --- a/appshell/build.gradle.kts +++ b/appshell/build.gradle.kts @@ -7,6 +7,17 @@ plugins { alias(libs.plugins.metro) } +/** + * Modules under `:plugins:` that are libraries, not feature plugins. They register nothing into the + * plugin map, so this shell does not need them: the plugin that uses one depends on it directly. + * They are also left out because they have no Apple targets, and listing one in commonMain would make + * every iOS build of this module fail at dependency resolution. + */ +val PLUGIN_LIBRARIES = setOf( + // KEKS authentication for Dexcom ONE+ / G7 (Android and JVM only). + ":plugins:libkeks", +) + /** * The app's shell: navigation and the composable root. * @@ -72,7 +83,7 @@ kotlin { // with the navigation graph that routes to them; `api` so `:app` still builds its // graph against them. Adding or removing a plugin stays an edit in settings.gradle. rootProject.subprojects - .filter { it.path.startsWith(":plugins:") && it.buildFile.exists() } + .filter { it.path.startsWith(":plugins:") && it.buildFile.exists() && it.path !in PLUGIN_LIBRARIES } .forEach { api(project(it.path)) } api(libs.jetbrains.compose.runtime) diff --git a/plugins/libkeks/NOTICE b/plugins/libkeks/NOTICE new file mode 100644 index 000000000000..1f6ec18c2d1f --- /dev/null +++ b/plugins/libkeks/NOTICE @@ -0,0 +1,54 @@ +THIRD-PARTY NOTICE — :plugins:libkeks +===================================== + +This module holds the KEKS J-PAKE / ExtraData authentication code from +NightscoutFoundation/xDrip (GNU GPL v3.0), pin commit +1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15), TRANSLATED from +Java to Kotlin. It is not a verbatim copy of the pin. + +Upstream paths: + - libkeks/src/main/java/jamorham/** + - ipluginda/src/main/java/com/eveningoutpost/dexdrip/plugin/IPluginDA.java + +Authorship per upstream comments: JamOrHam / jamorham. Upstream files carry no +formal per-file "Copyright (C) " line; see the git history of the +pin commit for authorship. No copyright holder is invented here. + +Each translated source file carries an "SPDX-License-Identifier: GPL-3.0-only" +header naming this upstream and pin. + +MODIFICATION NOTICE +------------------- +These sources are a DERIVED WORK of the pin above, not a copy of it. The 24 +Java files were translated into Kotlin so that the handshake can run in shared +(Kotlin Multiplatform) code. The translation keeps the protocol, the state +machine, the message layouts and the upstream comments. A byte for byte diff +against the pin is therefore not possible. + +How to check the translation: + `src/commonTest` holds golden values recorded from the original Java and + BouncyCastle code at the pin, including a whole four digit pairing replayed + message by message (`KeksGolden.kt` says how they were made). The Kotlin code + must reproduce them byte for byte. Run: + ./gradlew :plugins:libkeks:jvmTest :plugins:libkeks:testAndroidHostTest + The same tests run on the JVM and on Android, against each platform's + random, AES and log actuals. + +What the translation replaced, and why: + - BouncyCastle (secp256r1 point arithmetic, ECDSA, ASN.1 key readers) and + java.math.BigInteger have no multiplatform form. They are replaced by + jamorham.keks.crypto: KeksUInt, KeksP256 / KeksEcPoint, KeksEcdsa, KeksDer. + - Project Lombok (@Getter, @val, @RequiredArgsConstructor) is not needed in + Kotlin and is gone, with the annotation processor. + - javax.crypto, java.security.SecureRandom and android.util.Log are now three + `expect` declarations with an actual per platform. + - java.nio.ByteBuffer is replaced by jamorham.keks.util.KeksBuffer, which + copies the three behaviours the message classes depend on. + +SHA256.java carried its own MIT notice (Copyright (c) 2017 Fabian Meyer). That +notice is kept in full at the top of the translated SHA256.kt. + +The combined AndroidAPS APK is distributed under AGPL-3.0-or-later; GPL-3.0 +obligations are honoured for these derived parts (GPLv3 §13 AGPL compatibility). + +Bouncy Castle (bcpkix / bcprov) is not a dependency of this module. diff --git a/plugins/libkeks/README.md b/plugins/libkeks/README.md new file mode 100644 index 000000000000..2c23531effcd --- /dev/null +++ b/plugins/libkeks/README.md @@ -0,0 +1,23 @@ +# `:plugins:libkeks` + +**KEKS** J-PAKE / ExtraData authentication for Dexcom ONE+ / G7, translated to Kotlin from +[NightscoutFoundation/xDrip](https://github.com/NightscoutFoundation/xDrip) at pin +`1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (tag 2026.07.15, GPL-3.0). + +This is a **translation, not a verbatim copy**. The 24 Java files of the pin were rewritten in +Kotlin Multiplatform code; BouncyCastle, Lombok and `javax.crypto` are gone from the shared code. +See `NOTICE` for exactly what changed. + +**How to check it:** `src/commonTest` holds golden values recorded from the original Java and +BouncyCastle code at the pin, including a whole pairing replayed message by message. The Kotlin +code must give the same bytes: + +``` +./gradlew :plugins:libkeks:jvmTest :plugins:libkeks:testAndroidHostTest +``` + +Targets: Android and the JVM (desktop). Only three things are left to the platform, each behind an +`expect` in `crypto/KeksPlatform.kt`: a secure random generator, one AES block in ECB mode, and +where a log line goes. + +Used by the Dexcom ONE+ / G7 driver (`:plugins:dexcom_oneplus`). diff --git a/plugins/libkeks/build.gradle.kts b/plugins/libkeks/build.gradle.kts new file mode 100644 index 000000000000..796b179db519 --- /dev/null +++ b/plugins/libkeks/build.gradle.kts @@ -0,0 +1,51 @@ +plugins { + id("kmp-test-defaults") + kotlin("multiplatform") + // NOT com.android.library. AGP 9 refuses that plugin together with the multiplatform plugin. + // Same reason as the :core modules. + alias(libs.plugins.android.kmp.library) + // No KSP, no Metro and no annotation processor at all. This module is third party code + // translated from xDrip and reached through jamorham.keks.Plugin, never through the + // application graph. Lombok is gone with the Java: Kotlin needs no generated getters. +} + +kotlin { + android { + namespace = "jamorham.libkeks" + compileSdk = Versions.compileSdk + minSdk = Versions.minSdk + // Creates the androidHostTest compilation, which is what makes the golden values run + // against the Android actuals - javax.crypto, SecureRandom and android.util.Log - and not + // only against the JVM ones. isReturnDefaultValues is restated from + // test-module-dependencies, which a multiplatform module cannot apply: the handshake logs + // through android.util.Log, which is a stub on the unit test classpath. + withHostTest { + isReturnDefaultValues = true + } + compilerOptions { jvmTarget.set(Versions.jvmTarget) } + // Restated from android-module-dependencies, which a multiplatform module cannot apply. + lint { + checkReleaseBuilds = false + disable += "MissingTranslation" + disable += "ExtraTranslation" + } + } + + // Desktop, and a second platform the golden values run on. No iOS targets: nothing on iOS uses this module yet. + jvm() + + sourceSets { + // commonMain has no dependencies, on purpose: the translated sources stay easy to compare + // with the upstream pin. + + // Every test is a golden value taken from the Java and BouncyCastle code that shipped on + // Android, so all of them live in commonTest and run on the JVM and on Android. A handshake + // that is right on one platform and wrong on another is the exact failure this module has + // to rule out. + getByName("commonTest") { + dependencies { + implementation(kotlin("test")) + } + } + } +} diff --git a/plugins/libkeks/src/androidMain/kotlin/jamorham/keks/crypto/KeksPlatformAndroid.kt b/plugins/libkeks/src/androidMain/kotlin/jamorham/keks/crypto/KeksPlatformAndroid.kt new file mode 100644 index 000000000000..2917406ef1e4 --- /dev/null +++ b/plugins/libkeks/src/androidMain/kotlin/jamorham/keks/crypto/KeksPlatformAndroid.kt @@ -0,0 +1,55 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +import android.util.Log +import java.security.InvalidParameterException +import java.security.SecureRandom +import java.util.concurrent.locks.ReentrantLock +import javax.crypto.Cipher +import javax.crypto.spec.SecretKeySpec + +private val secureRandom = SecureRandom() + +internal actual fun keksRandomBytes(out: ByteArray) { + secureRandom.nextBytes(out) +} + +/** Byte for byte what the Java `AESwrapper` did, including answering null on any failure. */ +internal actual fun keksAesEcbEncrypt(key: ByteArray, plaintext: ByteArray): ByteArray? = + try { + val aesCipher = Cipher.getInstance("AES/ECB/NoPadding") + val secretKeySpec = SecretKeySpec(key, "AES") + aesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec) + aesCipher.doFinal(plaintext, 0, plaintext.size) + } catch (e: Exception) { + null + } + +internal actual fun keksLogWrite(tag: String, message: String) { + Log.d(tag, message) +} + +internal actual class KeksLock actual constructor() { + private val delegate = ReentrantLock() + actual fun lock() = delegate.lock() + actual fun unlock() = delegate.unlock() +} + +actual typealias KeksSecurityException = SecurityException + +actual typealias KeksInvalidParameterException = InvalidParameterException + +actual typealias KeksArrayIndexOutOfBoundsException = ArrayIndexOutOfBoundsException diff --git a/plugins/libkeks/src/commonMain/kotlin/com/eveningoutpost/dexdrip/plugin/IPluginDA.kt b/plugins/libkeks/src/commonMain/kotlin/com/eveningoutpost/dexdrip/plugin/IPluginDA.kt new file mode 100644 index 000000000000..516377d2e717 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/com/eveningoutpost/dexdrip/plugin/IPluginDA.kt @@ -0,0 +1,55 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package com.eveningoutpost.dexdrip.plugin + +/** + * JamOrHam + * + * Simple plugin data exchange interface + */ +interface IPluginDA { + + fun aNext(): Array? + + fun bNext(): Array? + + fun cNext(): Array? + + fun amConnected() + + fun bondNow(data: ByteArray?): Boolean + + fun receivedResponse(data: ByteArray?): Boolean + + fun receivedResponse2(data: ByteArray?): Boolean + + fun receivedResponse3(data: ByteArray?): Boolean + + fun receivedData(data: ByteArray?): Boolean + + fun receivedData2(data: ByteArray?): Boolean + + fun receivedData3(data: ByteArray?): Boolean + + fun getPersistence(channel: Int): ByteArray? + + fun setPersistence(channel: Int, data: ByteArray?): Boolean + + fun getStatus(): String + + fun getName(): String +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Calc.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Calc.kt new file mode 100644 index 000000000000..ea476e7cd37c --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Calc.kt @@ -0,0 +1,193 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksArrayIndexOutOfBoundsException +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksUInt +import jamorham.keks.util.AESwrapper +import jamorham.keks.util.KeksBuffer +import jamorham.keks.util.Util.arrayReduce +import jamorham.keks.util.Util.intToByteArray +import jamorham.libkeks.Digest +import jamorham.libkeks.SHA256 + +/** + * JamOrHam + * + * For reference see J-PAKE as described in the following papers: + * + * - https://ia.cr/2010/190 + * - http://grouper.ieee.org/groups/1363/Research/contributions/hao-ryan-2008.pdf + * - https://datatracker.ietf.org/doc/html/draft-cragie-tls-ecjpake-01 + */ +object Calc { + + fun getRound12Packet(context: Context, part2: Boolean): Packet { + val key = if (part2) context.KeyB!! else context.keyA!! + val zkp = ZKP(Curve.G, key, context.alice!!) + return Packet(zkp.getProof(), key.publicKey, zkp.getGv()) + } + + fun getRound1Packet(context: Context): Packet = getRound12Packet(context, false) + + fun getRound2Packet(context: Context): Packet = getRound12Packet(context, true) + + fun validateRound1Packet(p: Packet?, party: ByteArray): Boolean { + if (p == null) return false + return validateZeroKnowledgeProof(Curve.G, p.publicKeyPoint1, p.publicKeyPoint2, p.hash, party) + } + + fun validateRound1Packet(context: Context): Boolean = + validateRound1Packet(context.getRound1Packet(), context.bob!!) + + fun validateRound2Packet(context: Context): Boolean = + validateRound1Packet(context.getRound2Packet(), context.bob!!) + + fun getRound3Packet(context: Context): Packet { + val packet1 = context.getRound1Packet()!! + val packet2 = context.getRound2Packet()!! + val x1 = context.keyA!!.publicKey + val x2 = context.KeyB!!.privateKey + val x3 = packet1.publicKeyPoint1 + val x4 = packet2.publicKeyPoint1 + val s = context.getPasswordBigInteger() + val x2s = x2.mulMod(s, Curve.Q) + val x134 = x1.add(x3).add(x4).normalize() + val a = x134.multiply(x2s).normalize() + val zkp = ZKP(x134, KeyPair(x2s, a), context.alice!!) + return Packet(zkp.getProof(), a, zkp.getGv()) + } + + fun validateRound3Packet(context: Context): Boolean { + val packet = context.getRound3Packet() ?: return false + val x1 = context.keyA!!.publicKey + val x2 = context.KeyB!!.publicKey + val x3 = context.getRound1Packet()!!.publicKeyPoint1 + val g = x1.add(x2).add(x3).normalize() + val public1 = packet.publicKeyPoint1 + return validateZeroKnowledgeProof(g, public1, packet.publicKeyPoint2, packet.hash, context.bob!!) + } + + fun getSharedKey(context: Context): ByteArray? { + if (context.getRound3Packet() == null) return null + val point1 = context.getRound3Packet()!!.publicKeyPoint1 + val x2 = context.KeyB!!.privateKey + val x4 = context.getRound2Packet()!!.publicKeyPoint1 + val s = context.getPasswordBigInteger() + val key = point1.subtract(x4.multiply(x2.mulMod(s, Curve.Q))).multiply(x2).normalize() + return SHA256.hash(key.xEncoded()) + } + + fun getShortSharedKey(context: Context): ByteArray? = arrayReduce(getSharedKey(context), 16) + + fun calculateHash(context: Context): ByteArray? { + val data = context.challenge!! + val key = context.savedKey ?: getShortSharedKey(context) + if (key == null) { + return null + } + var bb = KeksBuffer.allocate(16) + bb.put(data) + bb.put(data) + val doubleData = bb.array() + val aesBytes = AESwrapper(key).aes(doubleData)!! + bb = KeksBuffer.allocate(8) + bb.put(aesBytes, 0, 8) + return bb.array() + } + + /** + * A Schnorr proof that the sender knows the secret behind a public point, without sending it. + */ + class ZKP( + private val g: KeksEcPoint, + private val keyPair: KeyPair, + private val party: ByteArray, + ) { + + private val exponent: KeksUInt = Curve.getExponent() + private var gv: KeksEcPoint? = null + + fun getGv(): KeksEcPoint { + var current = gv + if (current == null) { + current = g.multiply(exponent).normalize() + gv = current + } + return current + } + + fun getProof(): KeksUInt = exponent.subMod( + getZeroKnowledgeHash(g, getGv(), keyPair.publicKey, party).mulMod(keyPair.privateKey, Curve.Q), + Curve.Q, + ) + } + + fun validateZeroKnowledgeProof( + g: KeksEcPoint, + publicKey: KeksEcPoint, + gv: KeksEcPoint, + b: KeksUInt, + party: ByteArray, + ): Boolean { + val hash = getZeroKnowledgeHash(g, gv, publicKey, party) + return g.multiply(b) + .add(publicKey.multiply(hash)) + .normalize() == gv + } + + fun getZeroKnowledgeHash( + g: KeksEcPoint, + gv: KeksEcPoint, + gx: KeksEcPoint, + party: ByteArray, + ): KeksUInt { + val digestBytes = ByteArray(32) + val digest = Digest(digestBytes) + updateDigestIncludingSize(digest, g) + updateDigestIncludingSize(digest, gv) + updateDigestIncludingSize(digest, gx) + updateDigestIncludingSize(digest, party) + digest.doFinal() + return KeksUInt.fromBytes(digestBytes).mod(Curve.Q) + } + + private fun updateDigestIncludingSize(digest: Digest, point: KeksEcPoint) { + updateDigestIncludingSize(digest, point.getEncoded(false)) + } + + private fun updateDigestIncludingSize(digest: Digest, byteArray: ByteArray) { + digest.update(intToByteArray(byteArray.size)) + digest.update(byteArray) + } + + fun challenger(bytes: ByteArray, challenge: ByteArray): ByteArray? { + val pchallenge = ByteArray(16) + // The Java copied blind and let System.arraycopy raise on a short packet. The ONE+ driver + // catches that by name to turn an out of step handshake into a failed authentication, so + // the same kind of failure is raised here rather than a quietly padded challenge. + if (challenge.size < 2 + pchallenge.size) { + throw KeksArrayIndexOutOfBoundsException( + "challenge is ${challenge.size} bytes, needs ${2 + pchallenge.size}", + ) + } + challenge.copyInto(pchallenge, 0, 2, 2 + pchallenge.size) + return DSAChallenger(KeyPair.fromBytes(bytes)) + .response(pchallenge) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Config.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Config.kt new file mode 100644 index 000000000000..0683a63be2cc --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Config.kt @@ -0,0 +1,90 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.util.Util.hexStringToByteArray + +/** + * JamOrHam + * + * KEKS configuration + */ +object Config { + + private val KEY1 = arrayOf( + hex( + "039503316070A26884ECD320106080A26884ECD330107030240040A08F620F921D6251ACB39895DB5C49AB3" + + "0033E94D7E61C9EFE8F67107E3E0F5DC4E85FDB3EF05CCAA14C33C30D63F23D51F26A1624619087F06F06743031AEA9", + ), + hex( + "03183920100003316070A26884ECD320106080A26884ECD33010704097037720101040025351C2844410F98" + + "15BE04794FBC0AF098652F1AF232648BADB684F3506FB30D10AA06080A26884ECD33010701A4430240040A08F620F9" + + "21D6251ACB39895DB5C49AB30033E94D7E61C9EFE8F67107E3E0F5DC4E85FDB3EF05CCAA14C33C30D63F23D51F26A1" + + "624619087F06F06743031AEA9", + ), + ) + private val KEY2 = arrayOf( + hex( + "039503316070A26884ECD320106080A26884ECD330107030240040840CCEF4364F4F87D6B0D58F393050FC0" + + "ED7301604CFF5F03EAFF546E5EDAC66E0359991C66A8C9F91DE3F4E7CFD4936E26C593835EFE80951A79AAAACC5B285", + ), + hex( + "03183920100003316070A26884ECD320106080A26884ECD33010704097037720101040028DC3343BBD703B1" + + "D62614568237CC3CD786CA6926D7B492D33A5FCC10590A9CA0AA06080A26884ECD33010701A4430240040840CCEF43" + + "64F4F87D6B0D58F393050FC0ED7301604CFF5F03EAFF546E5EDAC66E0359991C66A8C9F91DE3F4E7CFD4936E26C593" + + "835EFE80951A79AAAACC5B285", + ), + ) + private val REFERENCE_B = hex("1A808807F7E953C754A02E0D3C51FA2D2ED3D7699430A51D910D4FBCBA3EEF2F") + private val ALICE_B = hex("36C69656E647") + private val BOB_B = hex("375627675627") + private val CMD1 = byteArrayOf(0x0A) + private val SPARAMB = byteArrayOf(0x02) + private val TIME_EXTENDEDB = byteArrayOf(0x06, 0x19) + private val TIME_EXTENDED2B = byteArrayOf(0xFF.toByte(), 0x06, 0x01) + private val TIME_EXTENDED3B = byteArrayOf(0x06, 0x00) + private val PREFIX_B = byteArrayOf(0x30, 0x30) + private val ONE_GET_DATA_4E_CMD = byteArrayOf(0x4e, 0x0a, 0xa9.toByte()) + private val GET_DATA_4E_CMD = byteArrayOf(0x4e) + private val CHALLENGE_OUTB = byteArrayOf(0x0d, 0x00, 0x02) + + /** + * `Util.hexStringToByteArray` turns each pair of hex digits around, so these texts are not + * read the way they look. That is upstream's own doing and the sensor expects the result. + */ + private fun hex(text: String): ByteArray = + hexStringToByteArray(text) ?: error("KEKS configuration value is not readable") + + enum class Get(val bytes: ByteArray) { + SPARAM(SPARAMB), + TIME_EXTENDED(TIME_EXTENDEDB), + TIME_EXTENDED2(TIME_EXTENDED2B), + TIME_EXTENDED3(TIME_EXTENDED3B), + PREFIX(PREFIX_B), + KEYCMD(CMD1), + KEY1A(KEY1[0]), + KEY1B(KEY1[1]), + KEY2A(KEY2[0]), + KEY2B(KEY2[1]), + ALICE(ALICE_B), + BOB(BOB_B), + REFERENCE(REFERENCE_B), + GETDATA(ONE_GET_DATA_4E_CMD), + GETDATA2(GET_DATA_4E_CMD), + CHALLENGE_OUT(CHALLENGE_OUTB), + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Context.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Context.kt new file mode 100644 index 000000000000..e8d13747c626 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Context.kt @@ -0,0 +1,94 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.Config.Get.PREFIX +import jamorham.keks.crypto.KeksUInt +import jamorham.keks.util.Log +import jamorham.keks.util.Util.arrayAppend +import kotlin.concurrent.Volatile + +/** + * JamOrHam + * + * KEKS context + */ +class Context { + + @Volatile var keyA: KeyPair? = null + @Volatile var KeyB: KeyPair? = null + @Volatile var password: String? = null + @Volatile var passwordBytes: ByteArray? = null + @Volatile var alice: ByteArray? = null + @Volatile var bob: ByteArray? = null + @Volatile var challenge: ByteArray? = null + @Volatile var savedKey: ByteArray? = null + @Volatile var packet: Array = arrayOfNulls(4) + @Volatile var sequence: Int = 0 + + @Volatile var partA: ByteArray? = null + @Volatile var partB: ByteArray? = null + @Volatile var partC: ByteArray? = null + + fun validateParts(): Boolean { + val a = partA + val b = partB + val c = partC + return a != null && b != null && c != null && a.size > 100 && b.size > 100 && c.size > 100 + } + + fun reset() { + savedKey = null + packet.fill(null) + } + + fun resetIfNotReady() { + sequence = 0 + if (savedKey == null && getRound3Packet() == null) { + reset() + } + } + + /** + * Was `getPasswordBytes()` in the Java. Renamed because [passwordBytes] is now a property of + * its own and the two would be the same method once compiled. + */ + fun ensurePasswordBytes(): ByteArray { + val pw = password + if (pw == null) { + Log.l("Context password not set") + throw RuntimeException() + } + var bytes = passwordBytes + if (bytes == null) { + bytes = pw.encodeToByteArray() + if (pw.length == 6) { + bytes = arrayAppend(PREFIX.bytes, bytes) + } + passwordBytes = bytes + } + return bytes + } + + fun getPasswordBigInteger(): KeksUInt = KeksUInt.fromBytes(ensurePasswordBytes()) + + fun getRound1Packet(): Packet? = packet[1] + + fun getRound2Packet(): Packet? = packet[2] + + fun getRound3Packet(): Packet? = packet[3] +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Curve.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Curve.kt new file mode 100644 index 000000000000..ad007ecd0dbf --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Curve.kt @@ -0,0 +1,49 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksEcdsa +import jamorham.keks.crypto.KeksP256 +import jamorham.keks.crypto.KeksReplay +import jamorham.keks.crypto.KeksUInt + +/** + * JamOrHam + * + * KEKS Elliptic Curve + */ +object Curve { + + const val name = "secp256r1" + + val G: KeksEcPoint get() = KeksP256.G + + /** The order of the base point. */ + val Q: KeksUInt = KeksP256.N + + val QM1: KeksUInt = KeksP256.N - KeksUInt.ONE + + val CURVE_BITS: Int = KeksP256.fieldBits + + val FIELD_SIZE: Int = (CURVE_BITS + 7) / 8 + + val PACKET_SIZE: Int = FIELD_SIZE * 5 + + fun getExponent(): KeksUInt = + KeksReplay.nextExponent() ?: KeksEcdsa.randomInRange(KeksUInt.ONE, QM1) +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/DSAChallenger.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/DSAChallenger.kt new file mode 100644 index 000000000000..60201593b76f --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/DSAChallenger.kt @@ -0,0 +1,43 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksEcdsa +import jamorham.keks.crypto.KeksUInt +import jamorham.keks.util.Log + +/** + * JamOrHam + * + * Signs a challenge from the sensor with the key out of the configuration QR code. + * + * On Android this extended BouncyCastle's `SignatureSpi.ecDSA256`, took the DER sequence it + * produced and immediately pulled the two 32 byte numbers back out of it. The two numbers are all + * that goes on the wire, so this writes them directly and the bytes are the same. + */ +class DSAChallenger(private val key: KeksUInt?) { + + fun response(challenge: ByteArray): ByteArray? { + try { + val privateKey = key ?: return null + return KeksEcdsa.sign(privateKey, challenge) + } catch (e: Exception) { + Log.l("Exception in challenger response: $e") + } + return null + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/JECPoint.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/JECPoint.kt new file mode 100644 index 000000000000..4350384686b8 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/JECPoint.kt @@ -0,0 +1,35 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksUInt +import jamorham.keks.util.Util.arrayAppend + +/** + * JamOrHam + */ +class JECPoint(val point: KeksEcPoint) { + + fun toBytes(): ByteArray = arrayAppend(point.xEncoded(), point.yEncoded()) + + companion object { + + fun pointFromBytes(xBytes: ByteArray, yBytes: ByteArray): KeksEcPoint = + KeksEcPoint.createPoint(KeksUInt.fromBytes(xBytes), KeksUInt.fromBytes(yBytes)) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/KeyPair.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/KeyPair.kt new file mode 100644 index 000000000000..0df2e54568f5 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/KeyPair.kt @@ -0,0 +1,71 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksDer +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksEcdsa +import jamorham.keks.crypto.KeksP256 +import jamorham.keks.crypto.KeksUInt +import jamorham.keks.util.Log + +/** + * JamOrHam + * + * KeyPair data holder + */ +class KeyPair(val privateKey: KeksUInt, val publicKey: KeksEcPoint) { + + /** A pair built from one secret number, with the public point worked out from it. */ + constructor(scalar: KeksUInt) : this(scalar, KeksP256.G.multiply(scalar)) + + /** A fresh pair, with the secret number drawn from the platform's secure generator. */ + constructor() : this(KeksEcdsa.randomInRange(KeksUInt.ONE, Curve.QM1)) + + /** An X.509 public key and a PKCS#8 private key, the way the configuration QR code holds them. */ + constructor(publicBytes: ByteArray, privateBytes: ByteArray) : this( + KeksDer.readPrivateKeyScalar(privateBytes), + KeksDer.readPublicPoint(publicBytes), + ) + + constructor(bytes: Array) : this(bytes[0], bytes[1]) + + companion object { + + fun fromBytes(bytes: Array): KeyPair? { + try { + return KeyPair(bytes[0], bytes[1]) + } catch (e: Exception) { + Log.l("Failure to generate KeyPair from bytes array") + } + return null + } + + /** + * The private number out of a PKCS#8 key. This stands in for `KeyFactorySpi.EC`, and + * answers null on bad input exactly as the Java did, with the same log line. + */ + fun fromBytes(privateBytes: ByteArray): KeksUInt? { + try { + return KeksDer.readPrivateKeyScalar(privateBytes) + } catch (e: Exception) { + Log.l("Failure to generate Key from bytes array") + } + return null + } + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Packet.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Packet.kt new file mode 100644 index 000000000000..d6bbec9a6aae --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Packet.kt @@ -0,0 +1,76 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.Curve.FIELD_SIZE +import jamorham.keks.Curve.PACKET_SIZE +import jamorham.keks.JECPoint.Companion.pointFromBytes +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksUInt +import jamorham.keks.util.ByteArrayHashMap +import jamorham.keks.util.KeksBuffer + +/** + * JamOrHam + * + * Data packet serialization + */ +class Packet( + val hash: KeksUInt, + val publicKeyPoint1: KeksEcPoint, + val publicKeyPoint2: KeksEcPoint, +) { + + constructor(bhm: ByteArrayHashMap) : this( + KeksUInt.fromBytes(bhm.mget(HBYTES1_ID)), + pointFromBytes(bhm.mget(POINT1X_ID), bhm.mget(POINT1Y_ID)), + pointFromBytes(bhm.mget(POINT2X_ID), bhm.mget(POINT2Y_ID)), + ) + + fun output(): ByteArray { + val packet = KeksBuffer.allocate(PACKET_SIZE) + packet.put(JECPoint(publicKeyPoint1).toBytes()) + packet.put(JECPoint(publicKeyPoint2).toBytes()) + packet.put(hash.toBytes(FIELD_SIZE)) + val array = packet.array() + if (array.size != PACKET_SIZE) { + throw RuntimeException("Invalid size") + } + return array + } + + companion object { + + const val POINT1X_ID = 28082 + const val POINT1Y_ID = 37603 + const val POINT2X_ID = 54247 + const val POINT2Y_ID = 40255 + const val HBYTES1_ID = 65535 + + private val ID_LIST = intArrayOf(POINT1X_ID, POINT1Y_ID, POINT2X_ID, POINT2Y_ID, HBYTES1_ID) + + fun parse(packet: ByteArray): Packet? { + if (packet.size < PACKET_SIZE) return null + val bhm = ByteArrayHashMap() + val buf = KeksBuffer.wrap(packet) + for (id in ID_LIST) { + buf.get(bhm.mget(id)) + } + return Packet(bhm) + } + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Plugin.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Plugin.kt new file mode 100644 index 000000000000..b4ceea259bc1 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Plugin.kt @@ -0,0 +1,559 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import com.eveningoutpost.dexdrip.plugin.IPluginDA +import jamorham.keks.Config.Get.ALICE +import jamorham.keks.Config.Get.BOB +import jamorham.keks.Config.Get.GETDATA +import jamorham.keks.Config.Get.GETDATA2 +import jamorham.keks.Config.Get.KEYCMD +import jamorham.keks.Config.Get.SPARAM +import jamorham.keks.crypto.KeksArrayIndexOutOfBoundsException +import jamorham.keks.crypto.KeksInvalidParameterException +import jamorham.keks.crypto.KeksLock +import jamorham.keks.crypto.KeksSecurityException +import jamorham.keks.crypto.withLock +import jamorham.keks.message.AuthChallengeTxMessage +import jamorham.keks.message.AuthRequestTxMessage2 +import jamorham.keks.message.AuthStatusRxMessage +import jamorham.keks.message.CertInfoRxMessage +import jamorham.keks.message.CertInfoTxMessage.Companion.expectMyCert1 +import jamorham.keks.message.CertInfoTxMessage.Companion.expectMyCert2 +import jamorham.keks.message.SignChallengeTxMessage +import jamorham.keks.util.Log +import jamorham.keks.util.Util.arrayAppend +import jamorham.keks.util.Util.bytesToHex +import kotlin.concurrent.Volatile + +/** + * JamOrHam + * + * KEKS Plugin + */ +class Plugin : IPluginDA { + + val context = Context() + + @Volatile private var lastAuthTx2: AuthRequestTxMessage2? = null + + @Volatile private var state = 0 + + @Volatile private var accumulator = ByteArray(0) + + @Volatile private var newFwchal = ByteArray(0) + + @Volatile private var keyToTestAgainst: ByteArray? = null + + private var expectedSize = 0 + + private var presponse: ByteArray? = null + + private var alt = false + + private val stateLock = KeksLock() + + init { + context.alice = ALICE.bytes + context.bob = BOB.bytes + context.keyA = KeyPair() + context.KeyB = KeyPair() + } + + constructor(password: String) { + context.password = password + context.ensurePasswordBytes() + } + + constructor() + + private fun changeState(newState: Int) = stateLock.withLock { + Log.d(TAG, "Changing state: " + stateToName(state) + " - > " + stateToName(newState)) + if (!dontClearAccumulator.contains(newState)) { + accumulator = EMPTY + } + state = newState + } + + override fun amConnected() { + context.resetIfNotReady() + changeState(RoundStart) + } + + override fun bondNow(data: ByteArray?): Boolean = + data.contentEquals(TIME_EXTENDED) || + data.contentEquals(TIME_EXTENDED2) || + data.contentEquals(TIME_EXTENDED3) + + private fun positionFromState(): Int = when (state) { + Round1 -> 1 + Round2 -> 2 + Round3 -> 3 + else -> 0 + } + + private fun parameterFromState(): Byte = when (state) { + Round1 -> 0 + Round2 -> 1 + Round3 -> 2 + else -> -1 + } + + private fun expectedBytesForState(): Int = when (state) { + Round1, Round2, Round3 -> Curve.PACKET_SIZE + SendCertificate1, SendCertificate1out, SendCertificate2, SendCertificate2out -> + if (expectedSize > 0) expectedSize else 0x179005 + SendKeyChallenge -> 64 + else -> 0x602910 + } + + private fun fill(data: ByteArray): Boolean { + accumulator = arrayAppend(accumulator, data) + val expected = expectedBytesForState() + Log.d( + TAG, + "Expected byte size for state: " + stateToName(state) + " -> " + expected + + " so far " + accumulator.size, + ) + return accumulator.size >= expectedBytesForState() + } + + // Return true if we want to emit based on our state + override fun receivedResponse(data: ByteArray?): Boolean { + Log.d(TAG, "Received remote response: " + bytesToHex(data) + " when in " + stateToName(state)) + when (state) { + RequestAuth -> { + if (!verifyChallenge(data!!)) { + context.reset() + if (context.sequence > 1) { + throw KeksSecurityException("Mismatch - wait") + } else { + return false + } + } + val challenge = ByteArray(8) + // Checked here and not earlier: a packet too short to hold a challenge still has + // to go through verifyChallenge first, because that is what reaches the "Mismatch + // - wait" recovery the ONE+ driver relies on. + requireLength(data, 9 + challenge.size) + data.copyInto(challenge, 0, 9, 9 + challenge.size) + context.challenge = challenge + return true + } + + ChallengeReply -> { + val status = AuthStatusRxMessage(data!!) + if (status.needsRefresh()) { + context.reset() + } + if (!status.isAuthenticated()) { + Log.d(TAG, "Could not authenticate!") + context.reset() + if (!status.isBonded()) { + changeState(BondFailure) + } else { + changeState(Unknown) + } + return true + } else { + if (status.isBonded()) { + Log.d(TAG, "Full success") + if (context.passwordBytes!!.size > 4) { + changeState(GetData) + } else { + changeState(GetData2) + } + return true + } else { + expectedSize = 0 + presponse = null + if (context.passwordBytes!!.size > 4) { + changeState(Pairing) + } else { + if (context.validateParts()) { + changeState(SendCertificate0) + } else { + throw KeksInvalidParameterException("Missing QR code") + } + } + return true + } + } + } + + Pairing -> return true + + SendCertificate1 -> { + val rep = CertInfoRxMessage(data!!) + if (rep.valid()) { + expectedSize = rep.size + changeState(SendCertificate1) + return true + } else { + throw KeksInvalidParameterException("Invalid QR code 1") + } + } + + SendCertificate2 -> { + val rep2 = CertInfoRxMessage(data!!) + if (rep2.valid()) { + expectedSize = rep2.size + changeState(SendCertificate2) + return true + } else { + throw KeksInvalidParameterException("Invalid QR code 2") + } + } + + SendKeyChallenge -> { + if (data!!.size > 2 && data[1].toInt() != 0) { + throw KeksInvalidParameterException("Invalid QR code 3") + } + presponse = Calc.challenger(context.partC!!, data) + return true + } + + SendKeyChallengeOut -> return true + } + + return false + } + + override fun receivedResponse2(data: ByteArray?): Boolean = false + + override fun receivedResponse3(data: ByteArray?): Boolean = false + + private fun getAuthRequestTx2(): AuthRequestTxMessage2 { + val message = AuthRequestTxMessage2(8, alt, newFwchal) + lastAuthTx2 = message + return message + } + + override fun aNext(): Array? { + Log.d(TAG, "Processing anext in state: " + stateToName(state)) + when (state) { + RoundStart -> + return if (context.getRound3Packet() != null || context.savedKey != null) { + state = RequestAuth + arrayOf(getAuthRequestTx2().byteSequence, null) + } else { + state = Round1 + sequencePacket(null) + } + + Round1 -> { + state = Round2 + return sequencePacket(Calc.getRound1Packet(context).output()) + } + + Round2 -> { + state = Round3 + return sequencePacket(Calc.getRound2Packet(context).output()) + } + + Round3 -> { + state = RequestAuth + // Written in this order on purpose: the auth request draws the single use token + // first, then round 3 draws its own random number. Swapping the two would change + // which random value lands where. + val auth = getAuthRequestTx2().byteSequence + return arrayOf(auth, Calc.getRound3Packet(context).output()) + } + + RequestAuth -> { + state = ChallengeReply + return arrayOf(AuthChallengeTxMessage(Calc.calculateHash(context)!!).byteSequence, null) + } + + ChallengeReply -> { + state = Unknown + return arrayOf(TIME_EXTENDED, null) + } + + SendCertificate0 -> { + state = SendCertificate1 + return arrayOf(expectMyCert1(this), null) + } + + SendCertificate1 -> { + state = SendCertificate1out + return arrayOf(null, context.partA) + } + + SendCertificate1out -> { + state = SendCertificate2 + return arrayOf(expectMyCert2(this), null) + } + + SendCertificate2 -> { + state = SendCertificate2out + return arrayOf(null, context.partB) + } + + SendCertificate2out -> { + state = SendKeyChallenge + return arrayOf(SignChallengeTxMessage().byteSequence, null) + } + + SendKeyChallenge -> { + state = SendKeyChallengeOut + return arrayOf(CHALLENGE_OUT, presponse) + } + + SendKeyChallengeOut -> { + state = GetData + return arrayOf(TIME_EXTENDED, null) + } + + Pairing -> { + state = GetData + return arrayOf(TIME_EXTENDED, null) + } + + GetData -> { + state = Unknown + return arrayOf(GETDATA.bytes) + } + + GetData2 -> { + state = Unknown + return arrayOf(GETDATA2.bytes) + } + + BondFailure -> { + state = Unknown + return arrayOf(GETDATA.bytes, null, null) + } + } + return null + } + + override fun bNext(): Array = arrayOf() + + override fun cNext(): Array = arrayOf() + + override fun receivedData(data: ByteArray?): Boolean { + Log.d(TAG, "Received data stream: " + bytesToHex(data)) + val full = fill(data!!) + if (full) { + context.packet[positionFromState()] = Packet.parse(accumulator) + accumulator = EMPTY + if (!validate()) { + Log.d(TAG, "Failed validation " + stateToName(state)) + context.packet[positionFromState()] = null + return false + } + } + return full + } + + override fun receivedData2(data: ByteArray?): Boolean = false + + override fun receivedData3(data: ByteArray?): Boolean = false + + override fun getPersistence(channel: Int): ByteArray? { + return if (channel == 1) { + val key = getSharedKey() + key ?: ByteArray(0) + } else if (channel == 3) { + // The three tests are written out rather than hoisted, because getSharedKey() can + // create context.savedKey as a side effect and the Java never reached it when there + // was nothing to test against. + if (keyToTestAgainst != null && getSharedKey() != null && + getSharedKey().contentEquals(keyToTestAgainst) + ) { + ByteArray(0) + } else { + null + } + } else { + ByteArray(0) + } + } + + override fun setPersistence(channel: Int, data: ByteArray?): Boolean { + if (channel == 1) { + keyToTestAgainst = data + return true + } + if (channel == 2) { + if (data != null && data.size != 16) { + return false + } + if (context.savedKey == null) { + Log.d(TAG, "Updating saved key from loaded persistence data") + context.savedKey = data + return true + } else { + return false + } + } + if (channel == 3 || channel == 4) { + instance = null + } + if (channel == 6) { + alt = data.contentEquals(SPARAM.bytes) + newFwchal = data ?: EMPTY + } + if (channel == 7) { + dontClearAccumulator.clear() + } + if (channel == 8) { + context.partA = data + } + if (channel == 9) { + context.partB = data + } + if (channel == 10) { + context.partC = data + } + return false + } + + override fun getStatus(): String = "" + + override fun getName(): String = "keks" + + private fun validate(): Boolean { + val p = context.packet[positionFromState()] + if (p == null) { + Log.d(TAG, "Packet is null") + return false + } + when (state) { + Round1 -> return Calc.validateRound1Packet(context) + Round2 -> return Calc.validateRound2Packet(context) + Round3 -> return Calc.validateRound3Packet(context) + SendCertificate1out, SendCertificate2out -> return true + } + Log.d(TAG, "Invalid state for validation: " + stateToName(state)) + return false + } + + /** + * The Java read straight past the end of a short packet and let `System.arraycopy` raise. + * The ONE+ driver catches that type by name, so the same kind of failure is raised here. + */ + private fun requireLength(data: ByteArray, needed: Int) { + if (data.size < needed) { + throw KeksArrayIndexOutOfBoundsException("packet is ${data.size} bytes, needs $needed") + } + } + + private fun verifyChallenge(data: ByteArray): Boolean { + if (context.savedKey != null) return true + context.challenge = lastAuthTx2!!.singleUseToken + val h = Calc.calculateHash(context) ?: return false + requireLength(data, 9) + for (i in 0 until 8) { + if (h[i] != data[i + 1]) return false + } + return true + } + + private fun sequencePacket(packet: ByteArray?): Array { + context.sequence++ + val param = parameterFromState() + val command = if (param < 0) null else byteArrayOf(KEYCMD.bytes[0], param) + return arrayOf(command, packet) + } + + private fun getSharedKey(): ByteArray? { + if (context.savedKey == null) { + context.savedKey = Calc.getShortSharedKey(context) + } + return context.savedKey + } + + companion object { + + private val dontClearAccumulator = HashSet() + private const val TAG = "KEKS-Plugin" + private val EMPTY = ByteArray(0) + private val TIME_EXTENDED = Config.Get.TIME_EXTENDED.bytes + private val TIME_EXTENDED2 = Config.Get.TIME_EXTENDED2.bytes + private val TIME_EXTENDED3 = Config.Get.TIME_EXTENDED3.bytes + private val CHALLENGE_OUT = Config.Get.CHALLENGE_OUT.bytes + + private const val Init = 0 + private const val Unknown = 370018 + private const val Scanning = 448130 + private const val Connecting = 432753 + private const val RoundStart = 789035 + private const val Pairing = 804167 + private const val Round1 = 674667 + private const val Round2 = 189857 + private const val Round3 = 588648 + private const val BondFailure = 162087 + private const val RequestAuth = 125320 + private const val ChallengeReply = 766662 + private const val SendCertificate0 = 975913 + private const val SendCertificate1 = 694702 + private const val SendCertificate2 = 230995 + private const val SendCertificate1out = 842681 + private const val SendCertificate2out = 558830 + private const val SendKeyChallenge = 486262 + private const val SendKeyChallengeOut = 327604 + private const val GetData = 734275 + private const val GetData2 = 199434 + + private val instanceLock = KeksLock() + + @Volatile private var instance: Plugin? = null + + init { + dontClearAccumulator.add(SendCertificate1) + dontClearAccumulator.add(SendCertificate1out) + dontClearAccumulator.add(SendCertificate2) + dontClearAccumulator.add(SendCertificate2out) + } + + private fun stateToName(state: Int): String = when (state) { + Init -> "Init" + Unknown -> "Unknown" + Scanning -> "Scanning" + Connecting -> "Connecting" + RoundStart -> "Round Start" + Round1 -> "Round 1" + Round2 -> "Round 2" + Round3 -> "Round 3" + BondFailure -> "Bond Failure" + Pairing -> "Pairing" + RequestAuth -> "Request Auth" + SendCertificate0 -> "Send Certificate 0" + SendCertificate1 -> "Send Certificate 1" + SendCertificate2 -> "Send Certificate 2" + SendCertificate1out -> "Send Certificate 1 Out" + SendCertificate2out -> "Send Certificate 2 Out" + SendKeyChallenge -> "Send Key Challenge" + SendKeyChallengeOut -> "Send Key Challenge Out" + ChallengeReply -> "Challenge Reply" + GetData -> "Get Data" + GetData2 -> "Get Data 2" + else -> "Error $state" + } + + fun getInstance(password: String): Plugin = instanceLock.withLock { + val current = instance + if (current == null || current.context.password != password) { + Log.d(TAG, "Creating new instance") + instance = Plugin(password) + } + instance!! + } + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Umbilical.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Umbilical.kt new file mode 100644 index 000000000000..0beb3ad3fdc2 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/Umbilical.kt @@ -0,0 +1,44 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +/** + * JamOrHam + * + * Coverage test harness + */ +class Umbilical { + + fun unitTest() { + val s = Plugin.getInstance("") + s.amConnected() + s.receivedResponse(null) + s.receivedResponse2(null) + s.receivedResponse3(null) + s.bondNow(null) + s.receivedData(null) + s.receivedData2(null) + s.receivedData3(null) + s.aNext() + s.bNext() + s.cNext() + s.getStatus() + s.getName() + s.getPersistence(0) + s.setPersistence(0, null) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksDer.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksDer.kt new file mode 100644 index 000000000000..b7e063541b22 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksDer.kt @@ -0,0 +1,96 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Shared replacement for the BouncyCastle key readers the translated KEKS sources use. + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +/** + * Just enough DER to read the two key shapes KEKS is handed. + * + * On Android this was `KeyFactorySpi.EC.generatePrivate(PrivateKeyInfo)` and + * `generatePublic(SubjectPublicKeyInfo)`. Only the key material is taken out; the algorithm + * identifier is walked past but not checked, which is what the old code did too - it always got + * these bytes from the xDrip configuration QR code, never from the sensor. + */ +object KeksDer { + + private const val TAG_INTEGER = 0x02 + private const val TAG_BIT_STRING = 0x03 + private const val TAG_OCTET_STRING = 0x04 + private const val TAG_SEQUENCE = 0x30 + + /** + * The private number d out of a PKCS#8 PrivateKeyInfo that wraps an RFC 5915 EC private key. + * + * Shape: SEQUENCE { INTEGER version, SEQUENCE algorithm, OCTET STRING { SEQUENCE { INTEGER 1, + * OCTET STRING d, ... } } }. + */ + fun readPrivateKeyScalar(pkcs8: ByteArray): KeksUInt { + val outer = Reader(pkcs8).sequence() + outer.skip(TAG_INTEGER) + outer.skip(TAG_SEQUENCE) + val inner = Reader(outer.read(TAG_OCTET_STRING)).sequence() + inner.skip(TAG_INTEGER) + val d = inner.read(TAG_OCTET_STRING) + return KeksUInt.fromBytes(d) + } + + /** + * The public point out of an X.509 SubjectPublicKeyInfo. + * + * Shape: SEQUENCE { SEQUENCE algorithm, BIT STRING point }. The bit string's first byte is the + * count of unused bits, which is always zero here. + */ + fun readPublicPoint(spki: ByteArray): KeksEcPoint { + val outer = Reader(spki).sequence() + outer.skip(TAG_SEQUENCE) + val bits = outer.read(TAG_BIT_STRING) + require(bits.isNotEmpty() && bits[0].toInt() == 0) { "unexpected unused bits in a key" } + return KeksEcPoint.decodePoint(bits.copyOfRange(1, bits.size)) + } + + private class Reader(private val bytes: ByteArray, private var at: Int = 0, private val end: Int = bytes.size) { + + fun sequence(): Reader { + val body = read(TAG_SEQUENCE) + return Reader(body) + } + + fun skip(expectedTag: Int) { + read(expectedTag) + } + + fun read(expectedTag: Int): ByteArray { + require(at < end) { "DER ran out of bytes" } + val tag = bytes[at].toInt() and 0xFF + require(tag == expectedTag) { "DER expected tag $expectedTag but found $tag" } + at++ + var length = bytes[at].toInt() and 0xFF + at++ + if (length and 0x80 != 0) { + val count = length and 0x7F + require(count in 1..4) { "DER length is too long" } + length = 0 + for (i in 0 until count) { + length = (length shl 8) or (bytes[at].toInt() and 0xFF) + at++ + } + } + require(length >= 0 && at + length <= end) { "DER length runs past the end" } + val body = bytes.copyOfRange(at, at + length) + at += length + return body + } + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksEcdsa.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksEcdsa.kt new file mode 100644 index 000000000000..235ee97b5520 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksEcdsa.kt @@ -0,0 +1,113 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Shared replacement for the BouncyCastle ECDSA signer the translated KEKS sources use. + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +import jamorham.libkeks.SHA256 + +/** + * ECDSA over secp256r1 with SHA-256, which is what `SignatureSpi.ecDSA256` gave on Android. + * + * The signature is written as r then s, each padded to 32 bytes. The Java code reached the same + * shape the long way round - BouncyCastle produced a DER sequence and `DSAChallenger` immediately + * took it apart again into two 32 byte numbers - so nothing on the wire changes. + * + * **The one value in this whole port that cannot be pinned to the Java is k**, the per signature + * random number. BouncyCastle drew it at random, so two signatures over the same challenge were + * already different bytes on Android. The test instead pins k to the value recovered from a real + * Java signature and checks the port then writes that same signature out. + */ +object KeksEcdsa { + + /** The 32 byte halves a KEKS signature is made of. */ + const val BYTES_PER_INTEGER = 32 + + /** + * The digest read as a whole number, the way BouncyCastle's `ECDSASigner.calculateE` does it: + * a 256 bit digest against a 256 bit group order needs no shortening and is **not** reduced. + */ + private fun messageValue(message: ByteArray): KeksUInt { + val digest = SHA256.hash(message) + val digestBits = digest.size * 8 + val orderBits = KeksP256.N.bitLength + val value = KeksUInt.fromBytes(digest) + return if (orderBits < digestBits) value.shr(digestBits - orderBits) else value + } + + /** Signs with a caller supplied k. Used by the tests to reproduce a known Java signature. */ + fun signWith(privateKey: KeksUInt, message: ByteArray, k: KeksUInt): ByteArray? { + val n = KeksP256.N + if (k.isZero || k >= n) return null + val point = KeksP256.G.multiply(k) + if (point.isInfinity) return null + val r = point.x.mod(n) + if (r.isZero) return null + val e = messageValue(message) + val s = k.modInverse(n).mulMod(e.addMod(r.mulMod(privateKey, n), n), n) + if (s.isZero) return null + return r.toBytes(BYTES_PER_INTEGER) + s.toBytes(BYTES_PER_INTEGER) + } + + /** Signs with a fresh random k, as BouncyCastle's `ecDSA256` did. */ + fun sign(privateKey: KeksUInt, message: ByteArray): ByteArray? { + repeat(MAX_ATTEMPTS) { + val signature = signWith(privateKey, message, randomInRange(KeksUInt.ONE, KeksP256.N - KeksUInt.ONE)) + if (signature != null) return signature + } + return null + } + + /** + * Checks a signature. The handshake itself never verifies - the sensor does that - but the + * tests need it to show that what this port signs is the same thing BouncyCastle signed. + */ + fun verify(publicKey: KeksEcPoint, message: ByteArray, signature: ByteArray): Boolean { + if (signature.size != BYTES_PER_INTEGER * 2) return false + val n = KeksP256.N + val r = KeksUInt.fromBytes(signature, 0, BYTES_PER_INTEGER) + val s = KeksUInt.fromBytes(signature, BYTES_PER_INTEGER, BYTES_PER_INTEGER) + if (r.isZero || r >= n || s.isZero || s >= n) return false + val e = messageValue(message) + val w = s.modInverse(n) + val u1 = e.mulMod(w, n) + val u2 = r.mulMod(w, n) + val point = KeksP256.G.multiply(u1).add(publicKey.multiply(u2)) + if (point.isInfinity) return false + return point.x.mod(n) == r + } + + /** + * A random whole number between [min] and [max], both ends included. This is + * `BigIntegers.createRandomInRange`: draw and try again, so the result is evenly spread. + */ + fun randomInRange(min: KeksUInt, max: KeksUInt): KeksUInt { + require(min <= max) { "empty range" } + val span = max - min + val bits = span.bitLength + if (bits == 0) return min + val byteCount = (bits + 7) / 8 + val extraBits = byteCount * 8 - bits + repeat(MAX_ATTEMPTS) { + val bytes = ByteArray(byteCount) + keksRandomBytes(bytes) + if (extraBits > 0) bytes[0] = (bytes[0].toInt() and (0xFF ushr extraBits)).toByte() + val candidate = KeksUInt.fromBytes(bytes) + if (candidate <= span) return min + candidate + } + throw IllegalStateException("could not draw a random number in range") + } + + private const val MAX_ATTEMPTS = 1000 +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksP256.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksP256.kt new file mode 100644 index 000000000000..f6d447c1576a --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksP256.kt @@ -0,0 +1,260 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Shared replacement for the BouncyCastle secp256r1 point arithmetic the translated KEKS sources + * use. Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +/** + * The curve secp256r1 (also called P-256 or prime256v1), the only curve KEKS uses. + * + * The numbers are the published ones. They are written here as text so a reader can compare them + * with the standard, and `KeksCurveTest` checks them against the values BouncyCastle gave on + * Android. + */ +object KeksP256 { + + /** The field prime. */ + val P: KeksUInt = KeksUInt.fromHex("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff") + + /** The order of the base point, called Q by the KEKS sources. */ + val N: KeksUInt = KeksUInt.fromHex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551") + + /** The curve's a, which is p - 3. The point doubling below relies on that. */ + val A: KeksUInt = KeksUInt.fromHex("ffffffff00000001000000000000000000000000fffffffffffffffffffffffc") + + val B: KeksUInt = KeksUInt.fromHex("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b") + + /** Bits in the field, as `ECCurve.getFieldSize()` reports it. */ + val fieldBits: Int = P.bitLength + + /** Bytes one coordinate takes, which is what the KEKS packet layout is built on. */ + val fieldSize: Int = (fieldBits + 7) / 8 + + /** + * The base point. Built lazily so that reading it cannot run while this object is still + * setting [P] and [fieldSize] up, which is what it needs to be built at all. + */ + val G: KeksEcPoint by lazy { + KeksEcPoint.createPoint( + KeksUInt.fromHex("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), + KeksUInt.fromHex("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), + ) + } + + /** Is this pair of numbers a point of the curve? */ + fun isOnCurve(x: KeksUInt, y: KeksUInt): Boolean { + val left = y.mulMod(y, P) + val right = x.mulMod(x, P).mulMod(x, P).addMod(A.mulMod(x, P), P).addMod(B, P) + return left == right + } +} + +/** + * A point of secp256r1, held the plain way: an x and a y, or the point at infinity. + * + * This takes the place of `org.bouncycastle.math.ec.ECPoint`, and copies two of its behaviours on + * purpose, because the KEKS code and its caller both depend on them: + * + * - Building a point does **not** check that it lies on the curve, exactly as + * `ECCurve.createPoint` does not. A coordinate outside the field is still refused, with the same + * `IllegalArgumentException`. + * - [multiply] checks the answer and throws `IllegalStateException("Invalid result")` when it is + * not a point of the curve. That is BouncyCastle's own `implCheckResult`, and the ONE+ driver + * catches that exception by name to turn a packet from an out of step handshake into a failed + * authentication rather than a crash. + */ +class KeksEcPoint private constructor( + val x: KeksUInt, + val y: KeksUInt, + val isInfinity: Boolean, +) { + + /** Kept so the ported code reads like the Java it came from. Points here are always affine. */ + fun normalize(): KeksEcPoint = this + + fun negate(): KeksEcPoint = + if (isInfinity) this else KeksEcPoint(x, if (y.isZero) y else KeksP256.P - y, false) + + fun add(other: KeksEcPoint): KeksEcPoint { + if (isInfinity) return other + if (other.isInfinity) return this + return jacobianAdd( + x, y, KeksUInt.ONE, + other.x, other.y, KeksUInt.ONE, + ).toAffine() + } + + fun subtract(other: KeksEcPoint): KeksEcPoint = add(other.negate()) + + fun twice(): KeksEcPoint { + if (isInfinity) return this + return jacobianDouble(x, y, KeksUInt.ONE).toAffine() + } + + /** + * Scalar multiplication, left to right over the bits of [k]. + * + * A zero scalar gives the point at infinity, which is what BouncyCastle answers too. + */ + fun multiply(k: KeksUInt): KeksEcPoint { + if (isInfinity || k.isZero) return INFINITY + var r = Jacobian(KeksUInt.ONE, KeksUInt.ONE, KeksUInt.ZERO) + for (i in k.bitLength - 1 downTo 0) { + r = jacobianDouble(r.x, r.y, r.z) + if (k.testBit(i)) r = jacobianAdd(r.x, r.y, r.z, x, y, KeksUInt.ONE) + } + val result = r.toAffine() + // BouncyCastle's ECAlgorithms.implCheckResult, kept because the caller depends on it. + if (!result.isInfinity && !KeksP256.isOnCurve(result.x, result.y)) { + throw IllegalStateException("Invalid result") + } + return result + } + + /** + * The point written out, as `ECPoint.getEncoded(false)` writes it: a 0x04 marker then x then + * y, each padded to the field size. Infinity is a single zero byte, again as BouncyCastle. + */ + fun getEncoded(compressed: Boolean = false): ByteArray { + require(!compressed) { "KEKS never sends a compressed point" } + if (isInfinity) return ByteArray(1) + val size = KeksP256.fieldSize + val out = ByteArray(1 + size * 2) + out[0] = 0x04 + x.toBytes(size).copyInto(out, 1) + y.toBytes(size).copyInto(out, 1 + size) + return out + } + + /** + * `getXCoord().getEncoded()` - the x padded to the field size. + * + * Infinity has no coordinate, so this raises, the way BouncyCastle's `getXCoord()` answered + * null and the caller then raised on it. The ONE+ driver catches that and calls the handshake + * failed rather than deriving a key from zeros. + */ + fun xEncoded(): ByteArray { + if (isInfinity) throw NullPointerException("the point at infinity has no x") + return x.toBytes(KeksP256.fieldSize) + } + + /** `getYCoord().getEncoded()` - the y padded to the field size. */ + fun yEncoded(): ByteArray { + if (isInfinity) throw NullPointerException("the point at infinity has no y") + return y.toBytes(KeksP256.fieldSize) + } + + override fun equals(other: Any?): Boolean { + if (other !is KeksEcPoint) return false + if (isInfinity || other.isInfinity) return isInfinity && other.isInfinity + return x == other.x && y == other.y + } + + override fun hashCode(): Int = if (isInfinity) 0 else x.hashCode() * 31 + y.hashCode() + + override fun toString(): String = if (isInfinity) "INF" else "(${x.toHex()},${y.toHex()})" + + private class Jacobian(val x: KeksUInt, val y: KeksUInt, val z: KeksUInt) { + fun toAffine(): KeksEcPoint { + if (z.isZero) return INFINITY + val zInv = z.modInverse(KeksP256.P) + val zInv2 = zInv.mulMod(zInv, KeksP256.P) + val zInv3 = zInv2.mulMod(zInv, KeksP256.P) + return KeksEcPoint(x.mulMod(zInv2, KeksP256.P), y.mulMod(zInv3, KeksP256.P), false) + } + } + + companion object { + + val INFINITY = KeksEcPoint(KeksUInt.ZERO, KeksUInt.ZERO, true) + + /** + * `ECCurve.createPoint(x, y)`. The coordinates have to be inside the field; whether they + * are a point of the curve is **not** checked here, exactly as in BouncyCastle. + */ + fun createPoint(x: KeksUInt, y: KeksUInt): KeksEcPoint { + require(x < KeksP256.P) { "x value invalid for SecP256R1FieldElement" } + require(y < KeksP256.P) { "y value invalid for SecP256R1FieldElement" } + return KeksEcPoint(x, y, false) + } + + /** Reads a 0x04 marked uncompressed point, or a single zero byte for infinity. */ + fun decodePoint(bytes: ByteArray): KeksEcPoint { + val size = KeksP256.fieldSize + if (bytes.size == 1 && bytes[0].toInt() == 0) return INFINITY + require(bytes.size == 1 + size * 2 && bytes[0].toInt() == 0x04) { + "not an uncompressed secp256r1 point" + } + return createPoint( + KeksUInt.fromBytes(bytes, 1, size), + KeksUInt.fromBytes(bytes, 1 + size, size), + ) + } + + private val THREE = KeksUInt.of(3) + private val FOUR = KeksUInt.of(4) + private val EIGHT = KeksUInt.of(8) + + /** "dbl-2001-b", which is the usual doubling for a curve whose a is p - 3. */ + private fun jacobianDouble(x: KeksUInt, y: KeksUInt, z: KeksUInt): Jacobian { + val p = KeksP256.P + if (z.isZero || y.isZero) return Jacobian(KeksUInt.ONE, KeksUInt.ONE, KeksUInt.ZERO) + val delta = z.mulMod(z, p) + val gamma = y.mulMod(y, p) + val beta = x.mulMod(gamma, p) + val alpha = THREE.mulMod(x.subMod(delta, p).mulMod(x.addMod(delta, p), p), p) + val x3 = alpha.mulMod(alpha, p).subMod(EIGHT.mulMod(beta, p), p) + val yz = y.addMod(z, p) + val z3 = yz.mulMod(yz, p).subMod(gamma, p).subMod(delta, p) + val y3 = alpha.mulMod(FOUR.mulMod(beta, p).subMod(x3, p), p) + .subMod(EIGHT.mulMod(gamma.mulMod(gamma, p), p), p) + return Jacobian(x3, y3, z3) + } + + /** "add-2007-bl". */ + private fun jacobianAdd( + x1: KeksUInt, y1: KeksUInt, z1: KeksUInt, + x2: KeksUInt, y2: KeksUInt, z2: KeksUInt, + ): Jacobian { + val p = KeksP256.P + if (z1.isZero) return Jacobian(x2, y2, z2) + if (z2.isZero) return Jacobian(x1, y1, z1) + val z1z1 = z1.mulMod(z1, p) + val z2z2 = z2.mulMod(z2, p) + val u1 = x1.mulMod(z2z2, p) + val u2 = x2.mulMod(z1z1, p) + val s1 = y1.mulMod(z2, p).mulMod(z2z2, p) + val s2 = y2.mulMod(z1, p).mulMod(z1z1, p) + if (u1 == u2) { + return if (s1 == s2) { + jacobianDouble(x1, y1, z1) + } else { + Jacobian(KeksUInt.ONE, KeksUInt.ONE, KeksUInt.ZERO) + } + } + val h = u2.subMod(u1, p) + val twoH = h.addMod(h, p) + val i = twoH.mulMod(twoH, p) + val j = h.mulMod(i, p) + val r = s2.subMod(s1, p).let { it.addMod(it, p) } + val v = u1.mulMod(i, p) + val x3 = r.mulMod(r, p).subMod(j, p).subMod(v.addMod(v, p), p) + val s1j = s1.mulMod(j, p) + val y3 = r.mulMod(v.subMod(x3, p), p).subMod(s1j.addMod(s1j, p), p) + val zz = z1.addMod(z2, p) + val z3 = zz.mulMod(zz, p).subMod(z1z1, p).subMod(z2z2, p).mulMod(h, p) + return Jacobian(x3, y3, z3) + } + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksPlatform.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksPlatform.kt new file mode 100644 index 000000000000..4d68cd2c2918 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksPlatform.kt @@ -0,0 +1,91 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * The handful of things the KEKS sources need from the platform underneath them. + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +/** + * Fills [out] with bytes from the platform's own secure generator. + * + * On Android this is the same `java.security.SecureRandom` the Java code used. + */ +internal expect fun keksRandomBytes(out: ByteArray) + +/** + * One or more AES blocks encrypted in ECB mode with no padding. + * + * Returns null when the platform refuses, which is what the Java `AESwrapper` did: it caught + * everything and answered null, and `Calc.calculateHash` turns that null into a failed handshake. + * + * AES is a fixed answer, so this is a real implementation on every platform and never a stub. + */ +internal expect fun keksAesEcbEncrypt(key: ByteArray, plaintext: ByteArray): ByteArray? + +/** Writes one KEKS log line on the platform the handshake is running on. */ +internal expect fun keksLogWrite(tag: String, message: String) + +/** + * A lock that the same thread may take again, standing in for Java's `synchronized`. + * + * This module has no project dependencies on purpose - it is third party code translated from xDrip - so it + * carries its own two line lock rather than reaching for `AapsLock` in `:core:interfaces`. + */ +internal expect class KeksLock() { + fun lock() + fun unlock() +} + +internal inline fun KeksLock.withLock(block: () -> T): T { + lock() + try { + return block() + } finally { + unlock() + } +} + +/* + * The three exceptions below are the only public part of this file. Everything else here is + * internal, because it is machinery the handshake uses on itself. These three leave the module: + * `OnePlusSessionAuthKeks` in `:plugins:dexcom_oneplus` names each of them in a `catch` and turns + * it into an auth failure the session retry can act on. That driver is shared code now, so it + * cannot fall back to the Android type names the way it did while it was Android only. + */ + +/** + * The exception the handshake raises when a reply does not match the challenge it answers. + * + * On Android this really is `java.lang.SecurityException`, because the ONE+ driver catches that + * type by name and turns it into "mismatch, wait" rather than a crash. + */ +expect class KeksSecurityException(message: String) : RuntimeException + +/** + * The exception the handshake raises when the certificate material is missing or wrong. + * + * On Android this really is `java.security.InvalidParameterException`, for the same reason: the + * ONE+ driver catches that type by name, and reads "Missing QR" out of its message to decide + * whether to throw the stored shared key away. + */ +expect class KeksInvalidParameterException(message: String) : IllegalArgumentException + +/** + * The exception a short packet raises where a challenge was expected. + * + * On Android this really is `java.lang.ArrayIndexOutOfBoundsException`, which is the type the Java + * `System.arraycopy` raised and which the ONE+ driver catches by name. Only the message differs: + * the one here names the lengths rather than repeating the JVM's wording, and the driver puts that + * message in a log line and nowhere else. + */ +expect class KeksArrayIndexOutOfBoundsException(message: String) : IndexOutOfBoundsException diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksReplay.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksReplay.kt new file mode 100644 index 000000000000..074c341a6545 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksReplay.kt @@ -0,0 +1,47 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +/** + * The two random draws of a handshake, held back so a recorded one can be played again. + * + * **This is for this module's own tests and nothing else.** It is `internal`, so no other module + * can reach it, and both queues are empty unless a test fills them. When a queue is empty the real + * secure generator is used, which is the only path production ever takes. + * + * It exists because the proof this port needs is a handshake reproduced byte for byte against one + * the Java and BouncyCastle code produced on Android, and a handshake is only reproducible if the + * random numbers in it are the same ones. + * + * Never fill these outside a test. A handshake with a known random number is a handshake anyone + * watching can work the shared key out of. + */ +internal object KeksReplay { + + /** Values `Curve.getExponent` hands out instead of drawing, oldest first. */ + val exponents: ArrayDeque = ArrayDeque() + + /** Values `Util.getRandomKey` hands out instead of drawing, oldest first. */ + val randomKeys: ArrayDeque = ArrayDeque() + + fun nextExponent(): KeksUInt? = exponents.removeFirstOrNull() + + fun nextRandomKey(): ByteArray? = randomKeys.removeFirstOrNull() + + fun clear() { + exponents.clear() + randomKeys.clear() + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksUInt.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksUInt.kt new file mode 100644 index 000000000000..448bfa0365a8 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/crypto/KeksUInt.kt @@ -0,0 +1,394 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Shared replacement for java.math.BigInteger, written for this port. The KEKS sources it serves + * are translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +/** + * A whole number that is never negative, stored as 32 bit words, least significant word first. + * + * This exists because Kotlin has no shared `BigInteger`. It is deliberately small: it does only + * what the KEKS handshake asks of `java.math.BigInteger`, and every operation is pinned by golden + * values taken from the Java code that ships on Android today (see `KeksBigIntTest`). + * + * Values are immutable. The word array is normalised, so the last word is never zero and the + * number zero is an empty array. + */ +class KeksUInt private constructor(private val w: IntArray) : Comparable { + + val isZero: Boolean get() = w.isEmpty() + + val isOne: Boolean get() = w.size == 1 && w[0] == 1 + + val isEven: Boolean get() = w.isEmpty() || (w[0] and 1) == 0 + + /** Number of bits needed to write this value, so zero is 0 and one is 1. */ + val bitLength: Int + get() = if (w.isEmpty()) 0 else w.size * 32 - w[w.size - 1].countLeadingZeroBits() + + fun testBit(index: Int): Boolean { + if (index < 0) return false + val word = index ushr 5 + if (word >= w.size) return false + return (w[word] ushr (index and 31)) and 1 == 1 + } + + override fun compareTo(other: KeksUInt): Int { + if (w.size != other.w.size) return if (w.size < other.w.size) -1 else 1 + for (i in w.indices.reversed()) { + val a = w[i].lo() + val b = other.w[i].lo() + if (a != b) return if (a < b) -1 else 1 + } + return 0 + } + + override fun equals(other: Any?): Boolean = other is KeksUInt && compareTo(other) == 0 + + override fun hashCode(): Int = w.contentHashCode() + + operator fun plus(other: KeksUInt): KeksUInt { + val a = w + val b = other.w + val size = maxOf(a.size, b.size) + 1 + val out = IntArray(size) + var carry = 0L + for (i in 0 until size) { + val sum = (if (i < a.size) a[i].lo() else 0L) + (if (i < b.size) b[i].lo() else 0L) + carry + out[i] = sum.toInt() + carry = sum ushr 32 + } + return of(out) + } + + /** Subtraction. The caller must have checked that this is not smaller than [other]. */ + operator fun minus(other: KeksUInt): KeksUInt { + require(this >= other) { "KeksUInt cannot go below zero" } + val a = w + val b = other.w + val out = IntArray(a.size) + var borrow = 0L + for (i in a.indices) { + val diff = a[i].lo() - (if (i < b.size) b[i].lo() else 0L) - borrow + out[i] = diff.toInt() + borrow = if (diff < 0) 1L else 0L + } + return of(out) + } + + operator fun times(other: KeksUInt): KeksUInt { + if (isZero || other.isZero) return ZERO + val a = w + val b = other.w + val out = IntArray(a.size + b.size) + for (i in a.indices) { + var carry = 0L + val ai = a[i].lo() + for (j in b.indices) { + val t = ai * b[j].lo() + out[i + j].lo() + carry + out[i + j] = t.toInt() + carry = t ushr 32 + } + out[i + b.size] = carry.toInt() + } + return of(out) + } + + fun shl(bits: Int): KeksUInt { + require(bits >= 0) + if (isZero || bits == 0) return this + val words = bits ushr 5 + val rest = bits and 31 + val out = IntArray(w.size + words + 1) + if (rest == 0) { + for (i in w.indices) out[i + words] = w[i] + } else { + for (i in w.indices) { + out[i + words] = out[i + words] or (w[i] shl rest) + out[i + words + 1] = w[i] ushr (32 - rest) + } + } + return of(out) + } + + fun shr(bits: Int): KeksUInt { + require(bits >= 0) + if (isZero || bits == 0) return this + val words = bits ushr 5 + if (words >= w.size) return ZERO + val rest = bits and 31 + val out = IntArray(w.size - words) + if (rest == 0) { + for (i in out.indices) out[i] = w[i + words] + } else { + for (i in out.indices) { + var v = w[i + words] ushr rest + if (i + words + 1 < w.size) v = v or (w[i + words + 1] shl (32 - rest)) + out[i] = v + } + } + return of(out) + } + + /** + * Quotient and remainder, by Knuth's algorithm D (the schoolbook long division every big + * number library uses). The single word divisor is a separate, simpler path, exactly as in + * the published algorithm. + */ + fun divRem(divisor: KeksUInt): Pair { + require(!divisor.isZero) { "KeksUInt division by zero" } + if (this < divisor) return ZERO to this + val n = divisor.w.size + val m = w.size + if (n == 1) { + val d = divisor.w[0].toUInt().toULong() + val q = IntArray(m) + var k = 0UL + for (j in m - 1 downTo 0) { + val cur = (k shl 32) or w[j].toUInt().toULong() + q[j] = (cur / d).toInt() + k = cur % d + } + return of(q) to of(intArrayOf(k.toInt())) + } + + // Normalise so the top word of the divisor has its high bit set; that is what makes the + // two word estimate of each quotient digit good enough. + val shift = divisor.w[n - 1].countLeadingZeroBits() + val vn = IntArray(n) + if (shift == 0) { + divisor.w.copyInto(vn) + } else { + for (i in n - 1 downTo 1) vn[i] = (divisor.w[i] shl shift) or (divisor.w[i - 1] ushr (32 - shift)) + vn[0] = divisor.w[0] shl shift + } + val un = IntArray(m + 1) + if (shift == 0) { + w.copyInto(un) + } else { + un[m] = w[m - 1] ushr (32 - shift) + for (i in m - 1 downTo 1) un[i] = (w[i] shl shift) or (w[i - 1] ushr (32 - shift)) + un[0] = w[0] shl shift + } + + val base = 1UL shl 32 + val q = IntArray(m - n + 1) + val top = vn[n - 1].toUInt().toULong() + val second = vn[n - 2].toUInt().toULong() + for (j in m - n downTo 0) { + val numerator = (un[j + n].toUInt().toULong() shl 32) or un[j + n - 1].toUInt().toULong() + var qhat = numerator / top + var rhat = numerator % top + while (qhat >= base || qhat * second > (rhat shl 32) + un[j + n - 2].toUInt().toULong()) { + qhat-- + rhat += top + if (rhat >= base) break + } + + // Multiply the divisor by the estimate and take it away from the running remainder. + var carry = 0UL + var borrow = 0L + for (i in 0 until n) { + val p = qhat * vn[i].toUInt().toULong() + carry + carry = p shr 32 + val diff = un[i + j].lo() - (p and 0xFFFFFFFFUL).toLong() - borrow + un[i + j] = diff.toInt() + borrow = if (diff < 0) 1L else 0L + } + val last = un[j + n].lo() - carry.toLong() - borrow + un[j + n] = last.toInt() + q[j] = qhat.toInt() + + if (last < 0) { + // The estimate was one too big, which the algorithm says happens very rarely. + q[j] = q[j] - 1 + var addCarry = 0L + for (i in 0 until n) { + val t = un[i + j].lo() + vn[i].lo() + addCarry + un[i + j] = t.toInt() + addCarry = t ushr 32 + } + un[j + n] = (un[j + n].lo() + addCarry).toInt() + } + } + + val rem = IntArray(n) + if (shift == 0) { + un.copyInto(rem, 0, 0, n) + } else { + for (i in 0 until n) rem[i] = (un[i] ushr shift) or (un[i + 1] shl (32 - shift)) + } + return of(q) to of(rem) + } + + fun mod(modulus: KeksUInt): KeksUInt = divRem(modulus).second + + fun addMod(other: KeksUInt, modulus: KeksUInt): KeksUInt { + val sum = this + other + // Both sides are nearly always already reduced, so one compare usually replaces a divide. + if (sum < modulus) return sum + val once = sum - modulus + return if (once < modulus) once else sum.mod(modulus) + } + + fun subMod(other: KeksUInt, modulus: KeksUInt): KeksUInt { + val a = mod(modulus) + val b = other.mod(modulus) + return if (a >= b) a - b else a + modulus - b + } + + fun mulMod(other: KeksUInt, modulus: KeksUInt): KeksUInt = (this * other).mod(modulus) + + /** + * The value that multiplies this back to one, modulo an **odd** [modulus]. Both numbers KEKS + * works with - the field prime and the group order of secp256r1 - are odd primes. + * + * Throws when there is no inverse, the way `BigInteger.modInverse` does, because a silent + * wrong answer here would pair with the sensor and then read glucose through a wrong key. + */ + fun modInverse(modulus: KeksUInt): KeksUInt { + require(!modulus.isEven) { "KeksUInt.modInverse needs an odd modulus" } + var u = mod(modulus) + require(!u.isZero) { "KeksUInt has no inverse: zero" } + var v = modulus + var x1 = ONE + var x2 = ZERO + while (!u.isOne && !v.isOne) { + while (u.isEven) { + u = u.shr(1) + x1 = if (x1.isEven) x1.shr(1) else (x1 + modulus).shr(1) + } + while (v.isEven) { + v = v.shr(1) + x2 = if (x2.isEven) x2.shr(1) else (x2 + modulus).shr(1) + } + if (u >= v) { + u -= v + x1 = x1.subMod(x2, modulus) + } else { + v -= u + x2 = x2.subMod(x1, modulus) + } + // Either side reaching zero means the two numbers share a factor, so there is no + // inverse. Without this the halving loop above would spin on zero for ever. + require(!u.isZero && !v.isZero) { "KeksUInt has no inverse" } + } + val answer = if (u.isOne) x1.mod(modulus) else x2.mod(modulus) + require(mulMod(answer, modulus).isOne) { "KeksUInt has no inverse" } + return answer + } + + /** Square and multiply. Only the tests use it; the handshake itself never needs a power. */ + fun modPow(exponent: KeksUInt, modulus: KeksUInt): KeksUInt { + if (modulus.isOne) return ZERO + var result = ONE + var base = mod(modulus) + for (i in 0 until exponent.bitLength) { + if (exponent.testBit(i)) result = result.mulMod(base, modulus) + base = base.mulMod(base, modulus) + } + return result + } + + /** + * Big endian bytes, left padded with zeros to exactly [length]. + * + * This is `BigIntegers.asUnsignedByteArray(length, value)`, including its refusal to shorten a + * value that does not fit. + */ + fun toBytes(length: Int): ByteArray { + val out = ByteArray(length) + for (i in w.indices) { + val word = w[i] + for (b in 0 until 4) { + val index = length - 1 - (i * 4 + b) + val byte = ((word ushr (b * 8)) and 0xFF).toByte() + if (index < 0) { + require(byte.toInt() == 0) { "standard length exceeded for value" } + } else { + out[index] = byte + } + } + } + return out + } + + /** Lower case, no leading zeros, "0" for zero - what `BigInteger.toString(16)` gives. */ + fun toHex(): String { + if (isZero) return "0" + val sb = StringBuilder() + for (i in w.indices.reversed()) { + val part = w[i].toUInt().toString(16) + if (sb.isEmpty()) sb.append(part) else sb.append(part.padStart(8, '0')) + } + return sb.toString() + } + + override fun toString(): String = toHex() + + companion object { + + val ZERO = KeksUInt(IntArray(0)) + val ONE = KeksUInt(intArrayOf(1)) + val TWO = KeksUInt(intArrayOf(2)) + + private fun of(words: IntArray): KeksUInt { + var size = words.size + while (size > 0 && words[size - 1] == 0) size-- + if (size == 0) return ZERO + return KeksUInt(if (size == words.size) words else words.copyOf(size)) + } + + fun of(value: Int): KeksUInt { + require(value >= 0) { "KeksUInt is never negative" } + return if (value == 0) ZERO else KeksUInt(intArrayOf(value)) + } + + /** `BigIntegers.fromUnsignedByteArray` - big endian, no sign bit. */ + fun fromBytes(bytes: ByteArray, offset: Int = 0, length: Int = bytes.size - offset): KeksUInt { + require(offset >= 0 && length >= 0 && offset + length <= bytes.size) { + "KeksUInt.fromBytes out of range" + } + if (length == 0) return ZERO + val words = IntArray((length + 3) / 4) + for (i in 0 until length) { + val value = bytes[offset + length - 1 - i].toInt() and 0xFF + words[i ushr 2] = words[i ushr 2] or (value shl ((i and 3) * 8)) + } + return of(words) + } + + fun fromHex(text: String): KeksUInt { + if (text.isEmpty()) return ZERO + val padded = if (text.length % 2 == 0) text else "0$text" + val bytes = ByteArray(padded.length / 2) + for (i in bytes.indices) { + val high = hexDigit(padded[i * 2]) + val low = hexDigit(padded[i * 2 + 1]) + bytes[i] = ((high shl 4) or low).toByte() + } + return fromBytes(bytes) + } + + private fun hexDigit(c: Char): Int = when (c) { + in '0'..'9' -> c - '0' + in 'a'..'f' -> c - 'a' + 10 + in 'A'..'F' -> c - 'A' + 10 + else -> throw IllegalArgumentException("not a hex digit: $c") + } + } +} + +/** The word read as an unsigned 32 bit number. */ +private fun Int.lo(): Long = toLong() and 0xFFFFFFFFL diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthChallengeTxMessage.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthChallengeTxMessage.kt new file mode 100644 index 000000000000..867826348ec4 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthChallengeTxMessage.kt @@ -0,0 +1,36 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.util.KeksBuffer + +/** + * JamOrHam + */ +class AuthChallengeTxMessage(challenge: ByteArray) : BaseMessage() { + + val opcode: Byte = 0x04 + val challengeHash: ByteArray = challenge + + init { + val buffer = KeksBuffer.allocate(9) + buffer.put(opcode) + buffer.put(challengeHash) + data = buffer + byteSequence = buffer.array() + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthRequestTxMessage2.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthRequestTxMessage2.kt new file mode 100644 index 000000000000..1b52c136b159 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthRequestTxMessage2.kt @@ -0,0 +1,54 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.util.KeksBuffer +import jamorham.keks.util.Util.getRandomKey + +/** + * JamOrHam + */ +class AuthRequestTxMessage2 : BaseMessage { + + val opcode: Byte = 0x02 + + var singleUseToken: ByteArray = ByteArray(0) + + constructor(tokenSize: Int) : this(tokenSize, false, ByteArray(0)) + + constructor(tokenSize: Int, alt: Boolean, chal: ByteArray) : this( + tokenSize, + (if (alt) endByteAlt else endByteStd).toInt() + (if (chal.size > 2) chal[2].toInt() else 0), + ) + + constructor(tokenSize: Int, slot: Int) : super() { + init(opcode, tokenSize + 2) + val randomBytes = getRandomKey() + val bb = KeksBuffer.allocate(tokenSize) + bb.put(randomBytes, 0, tokenSize) + singleUseToken = bb.array() + data!!.put(singleUseToken) + data!!.put(slot.toByte()) + byteSequence = data!!.array() + } + + companion object { + + private const val endByteStd: Byte = 0x2 + private const val endByteAlt: Byte = 0x1 + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthStatusRxMessage.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthStatusRxMessage.kt new file mode 100644 index 000000000000..8e0b68573c91 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/AuthStatusRxMessage.kt @@ -0,0 +1,50 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.util.KeksBuffer + +/** + * JamOrHam + */ +class AuthStatusRxMessage(packet: ByteArray) : BaseMessage() { + + var authenticated: Int = 0 + var bonded: Int = 0 + + init { + if (packet.size >= 3) { + if (packet[0].toInt() == opcode) { + val buffer = KeksBuffer.wrap(packet) + data = buffer + authenticated = buffer.get(1).toInt() + bonded = buffer.get(2).toInt() + } + } + } + + fun isAuthenticated(): Boolean = authenticated == 1 + + fun isBonded(): Boolean = bonded == 1 + + fun needsRefresh(): Boolean = bonded == 3 + + companion object { + + const val opcode = 0x5 + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/BaseMessage.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/BaseMessage.kt new file mode 100644 index 000000000000..7bc4fa149a57 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/BaseMessage.kt @@ -0,0 +1,46 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.util.KeksBuffer +import kotlin.concurrent.Volatile + +/** + * JamOrHam + */ +open class BaseMessage { + + var data: KeksBuffer? = null + + @Volatile + var byteSequence: ByteArray? = null + + internal fun init(opcode: Byte, length: Int) { + data = KeksBuffer.allocate(length, littleEndian = true) + data!!.put(opcode) + if (length == 1) { + fillByteSequence() + } + } + + /** Was `getByteSequence()` in the Java; renamed because [byteSequence] now has its own one. */ + fun fillByteSequence(): ByteArray { + val array = data!!.array() + byteSequence = array + return array + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoRxMessage.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoRxMessage.kt new file mode 100644 index 000000000000..be7358c8349b --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoRxMessage.kt @@ -0,0 +1,54 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.util.KeksBuffer + +/** + * JamOrHam + */ +class CertInfoRxMessage(packet: ByteArray) : BaseMessage() { + + var size: Int = -1 + private set + + var which: Int = -1 + private set + + var state: Int = 0 + private set + + init { + val buffer = KeksBuffer.wrap(packet, littleEndian = true) + data = buffer + if (packet.size == 7) { + if (buffer.get().toInt() == opcode.toInt()) { + state = buffer.get().toInt() + which = buffer.get().toInt() + // might be an int but just ignore later bytes + size = buffer.getShort().toInt() + } + } + } + + fun valid(): Boolean = size > 0 && state == 0 && which >= 0 + + companion object { + + const val opcode: Byte = 0x0b + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoTxMessage.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoTxMessage.kt new file mode 100644 index 000000000000..798a2fe89c34 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/CertInfoTxMessage.kt @@ -0,0 +1,43 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.Plugin + +/** + * JamOrHam + */ +class CertInfoTxMessage : BaseMessage() { + + companion object { + + const val opcode: Byte = 0x0b + + fun expectMyCert(plugin: Plugin, which: Int): ByteArray { + val p = CertInfoTxMessage() + val c = plugin.context + p.init(opcode, 6) + p.data!!.put(which.toByte()) + p.data!!.putInt(if (which == 0) c.partA!!.size else c.partB!!.size) + return p.fillByteSequence() + } + + fun expectMyCert1(plugin: Plugin): ByteArray = expectMyCert(plugin, 0) + + fun expectMyCert2(plugin: Plugin): ByteArray = expectMyCert(plugin, 1) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/SignChallengeTxMessage.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/SignChallengeTxMessage.kt new file mode 100644 index 000000000000..52b7195cccc6 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/message/SignChallengeTxMessage.kt @@ -0,0 +1,39 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.message + +import jamorham.keks.util.KeksBuffer +import jamorham.keks.util.Util.getRandomKey + +/** + * JamOrHam + */ +class SignChallengeTxMessage(challenge: ByteArray) : BaseMessage() { + + val opcode: Byte = 0x0c + val challengeHash: ByteArray = challenge + + init { + val buffer = KeksBuffer.allocate(17) + buffer.put(opcode) + buffer.put(challengeHash) + data = buffer + byteSequence = buffer.array() + } + + constructor() : this(getRandomKey()) +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/AESwrapper.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/AESwrapper.kt new file mode 100644 index 000000000000..5efe1fd5fd58 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/AESwrapper.kt @@ -0,0 +1,30 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.util + +import jamorham.keks.crypto.keksAesEcbEncrypt + +/** + * JamOrHam + * + * AES in ECB mode with no padding. Answers null on any failure, which the KEKS code relies on: + * `Calc.calculateHash` turns a null here into a handshake that does not complete. + */ +class AESwrapper(private val key: ByteArray) { + + fun aes(plaintext: ByteArray): ByteArray? = keksAesEcbEncrypt(key, plaintext) +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/ByteArrayHashMap.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/ByteArrayHashMap.kt new file mode 100644 index 000000000000..67661377092b --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/ByteArrayHashMap.kt @@ -0,0 +1,40 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.util + +import jamorham.keks.Curve + +/** + * JamOrHam + * + * A map that hands out a fresh, field sized, zero filled array for any key it has not seen. + * [mget] returns the stored array itself, so the caller can read bytes straight into it. + */ +class ByteArrayHashMap { + + private val backing = HashMap() + + fun mget(key: Int): ByteArray { + val v = backing[key] + if (v == null) { + val fresh = ByteArray(Curve.FIELD_SIZE) + backing[key] = fresh + return fresh + } + return v + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/KeksBuffer.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/KeksBuffer.kt new file mode 100644 index 000000000000..bf4b427ca331 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/KeksBuffer.kt @@ -0,0 +1,105 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.util + +/** + * The small part of `java.nio.ByteBuffer` the KEKS messages use. + * + * Three of its behaviours are copied on purpose, because the message classes depend on them: + * a fresh buffer is zero filled, [array] hands back the whole buffer however far writing got, and + * reading or writing past the end throws rather than answering a quiet zero. A short packet that + * read as zeros would look like a real reading. + */ +class KeksBuffer private constructor( + private val backing: ByteArray, + private val littleEndian: Boolean, +) { + + private var position = 0 + + fun put(value: Byte): KeksBuffer { + checkRoom(1) + backing[position++] = value + return this + } + + fun put(values: ByteArray): KeksBuffer = put(values, 0, values.size) + + fun put(values: ByteArray, offset: Int, length: Int): KeksBuffer { + checkRoom(length) + values.copyInto(backing, position, offset, offset + length) + position += length + return this + } + + fun putInt(value: Int): KeksBuffer { + checkRoom(4) + if (littleEndian) { + for (shift in 0..24 step 8) backing[position++] = (value ushr shift).toByte() + } else { + for (shift in 24 downTo 0 step 8) backing[position++] = (value ushr shift).toByte() + } + return this + } + + fun get(): Byte { + checkRoom(1) + return backing[position++] + } + + fun get(index: Int): Byte { + if (index < 0 || index >= backing.size) { + throw IndexOutOfBoundsException("KeksBuffer read at $index of ${backing.size}") + } + return backing[index] + } + + fun get(destination: ByteArray): KeksBuffer { + checkRoom(destination.size) + backing.copyInto(destination, 0, position, position + destination.size) + position += destination.size + return this + } + + fun getShort(): Short { + checkRoom(2) + val a = backing[position].toInt() and 0xFF + val b = backing[position + 1].toInt() and 0xFF + position += 2 + return (if (littleEndian) (b shl 8) or a else (a shl 8) or b).toShort() + } + + fun array(): ByteArray = backing + + private fun checkRoom(count: Int) { + if (position + count > backing.size) { + throw IndexOutOfBoundsException( + "KeksBuffer needs $count bytes at $position of ${backing.size}", + ) + } + } + + companion object { + + fun allocate(length: Int, littleEndian: Boolean = false): KeksBuffer = + KeksBuffer(ByteArray(length), littleEndian) + + /** Backs onto the array it is given, the way `ByteBuffer.wrap` does - no copy. */ + fun wrap(bytes: ByteArray, littleEndian: Boolean = false): KeksBuffer = + KeksBuffer(bytes, littleEndian) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Log.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Log.kt new file mode 100644 index 000000000000..0d7f8d2c4fba --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Log.kt @@ -0,0 +1,35 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.util + +import jamorham.keks.crypto.keksLogWrite + +/** + * JamOrHam - logging bridge for AAPS (was System.out in upstream libkeks). + * + * Where a line ends up is the only part of this that is platform specific. + */ +object Log { + + fun d(tag: String, msg: String) { + keksLogWrite(tag, msg) + } + + fun l(msg: String) { + d("KEKS-Plugin", msg) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Util.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Util.kt new file mode 100644 index 000000000000..79195965d221 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/keks/util/Util.kt @@ -0,0 +1,104 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.util + +import jamorham.keks.crypto.KeksReplay +import jamorham.keks.crypto.keksRandomBytes + +/** + * JamOrHam + * + * Generic utility methods + */ +object Util { + + private val hexArray = "0123456789ABCDEF".toCharArray() + + fun bytesToHex(bytes: ByteArray?): String { + if (bytes == null) return "" + val hexChars = CharArray(bytes.size * 2) + for (j in bytes.indices) { + val v = bytes[j].toInt() and 0xFF + hexChars[j * 2] = hexArray[v ushr 4] + hexChars[j * 2 + 1] = hexArray[v and 0x0F] + } + return hexChars.concatToString() + } + + fun arrayAppend(existing: ByteArray, addon: ByteArray): ByteArray { + val bigger = existing.copyOf(existing.size + addon.size) + addon.copyInto(bigger, existing.size, 0, addon.size) + return bigger + } + + fun arrayReduce(existing: ByteArray?, length: Int): ByteArray? { + if (existing == null) return null + val dest = ByteArray(length) + existing.copyInto(dest, 0, 0, length) + return dest + } + + fun tolerantHexStringToByteArray(str: String): ByteArray? = + hexStringToByteArray(Regex("[^A-F0-9]").replace(str.uppercase(), "")) + + /** + * Hex text to bytes, **with the two halves of each byte the other way round**. + * + * That swap is deliberate upstream, not a slip: it is what makes the KEKS party labels in + * `Config` read as "client" and "server". Anything that is not a hex digit counts as -1, so + * "zz" gives 0xEF rather than an error, and a text of an odd length ends up running off the + * end and answering null. All of that is relied on, so it is kept exactly. + */ + fun hexStringToByteArray(str: String): ByteArray? { + return try { + val text = str.uppercase().trim() + if (text.isEmpty()) return null + val len = text.length + val data = ByteArray(len / 2) + var i = 0 + while (i < len) { + data[i / 2] = ((digit(text[i + 1]) shl 4) + digit(text[i])).toByte() + i += 2 + } + data + } catch (e: Exception) { + null + } + } + + /** Java's `Character.digit(c, 16)`, which answers -1 for anything that is not a hex digit. */ + private fun digit(c: Char): Int = when (c) { + in '0'..'9' -> c - '0' + in 'A'..'F' -> c - 'A' + 10 + in 'a'..'f' -> c - 'a' + 10 + else -> -1 + } + + fun intToByteArray(value: Int): ByteArray = byteArrayOf( + (value ushr 24).toByte(), + (value ushr 16).toByte(), + (value ushr 8).toByte(), + value.toByte(), + ) + + fun getRandomKey(): ByteArray { + KeksReplay.nextRandomKey()?.let { return it } + val keybytes = ByteArray(16) + keksRandomBytes(keybytes) + return keybytes + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/Digest.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/Digest.kt new file mode 100644 index 000000000000..5bc0d35838a8 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/Digest.kt @@ -0,0 +1,39 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * Authorship per upstream comments: JamOrHam / jamorham. Upstream carries no + * formal per-file "Copyright (C) " line; none is asserted or + * invented here. See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.libkeks + +/** + * JamOrHam + * + * Collects everything it is given and writes the SHA-256 of the lot into [destination]. + */ +class Digest(private val destination: ByteArray) { + + private var store = ByteArray(0) + + fun update(data: ByteArray) { + val n = ByteArray(store.size + data.size) + data.copyInto(n, store.size, 0, data.size) + store.copyInto(n, 0, 0, store.size) + store = n + } + + fun doFinal() { + val result = SHA256.hash(store) + result.copyInto(destination, 0, 0, destination.size) + } +} diff --git a/plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/SHA256.kt b/plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/SHA256.kt new file mode 100644 index 000000000000..ee51ae0e1471 --- /dev/null +++ b/plugins/libkeks/src/commonMain/kotlin/jamorham/libkeks/SHA256.kt @@ -0,0 +1,167 @@ +/* + * MIT License + * + * Copyright (c) 2017 Fabian Meyer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + * Translated to Kotlin from SHA256.java in NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. The algorithm is unchanged. The two working arrays that were shared + * statics guarded by `synchronized` are now local to each call: same result, no lock needed. + * + * SPDX-License-Identifier: MIT + */ +package jamorham.libkeks + +object SHA256 { + + private val K = intArrayOf( + 0x428a2f98u.toInt(), 0x71374491u.toInt(), 0xb5c0fbcfu.toInt(), 0xe9b5dba5u.toInt(), + 0x3956c25bu.toInt(), 0x59f111f1u.toInt(), 0x923f82a4u.toInt(), 0xab1c5ed5u.toInt(), + 0xd807aa98u.toInt(), 0x12835b01u.toInt(), 0x243185beu.toInt(), 0x550c7dc3u.toInt(), + 0x72be5d74u.toInt(), 0x80deb1feu.toInt(), 0x9bdc06a7u.toInt(), 0xc19bf174u.toInt(), + 0xe49b69c1u.toInt(), 0xefbe4786u.toInt(), 0x0fc19dc6u.toInt(), 0x240ca1ccu.toInt(), + 0x2de92c6fu.toInt(), 0x4a7484aau.toInt(), 0x5cb0a9dcu.toInt(), 0x76f988dau.toInt(), + 0x983e5152u.toInt(), 0xa831c66du.toInt(), 0xb00327c8u.toInt(), 0xbf597fc7u.toInt(), + 0xc6e00bf3u.toInt(), 0xd5a79147u.toInt(), 0x06ca6351u.toInt(), 0x14292967u.toInt(), + 0x27b70a85u.toInt(), 0x2e1b2138u.toInt(), 0x4d2c6dfcu.toInt(), 0x53380d13u.toInt(), + 0x650a7354u.toInt(), 0x766a0abbu.toInt(), 0x81c2c92eu.toInt(), 0x92722c85u.toInt(), + 0xa2bfe8a1u.toInt(), 0xa81a664bu.toInt(), 0xc24b8b70u.toInt(), 0xc76c51a3u.toInt(), + 0xd192e819u.toInt(), 0xd6990624u.toInt(), 0xf40e3585u.toInt(), 0x106aa070u.toInt(), + 0x19a4c116u.toInt(), 0x1e376c08u.toInt(), 0x2748774cu.toInt(), 0x34b0bcb5u.toInt(), + 0x391c0cb3u.toInt(), 0x4ed8aa4au.toInt(), 0x5b9cca4fu.toInt(), 0x682e6ff3u.toInt(), + 0x748f82eeu.toInt(), 0x78a5636fu.toInt(), 0x84c87814u.toInt(), 0x8cc70208u.toInt(), + 0x90befffau.toInt(), 0xa4506cebu.toInt(), 0xbef9a3f7u.toInt(), 0xc67178f2u.toInt(), + 0x6a09e667u.toInt(), 0xbb67ae85u.toInt(), 0x3c6ef372u.toInt(), 0xa54ff53au.toInt(), + 0x510e527fu.toInt(), 0x9b05688cu.toInt(), 0x1f83d9abu.toInt(), 0x5be0cd19u.toInt(), + ) + + private const val BLOCK_BITS = 512 + private const val BLOCK_BYTES = BLOCK_BITS / 8 + + fun hash(message: ByteArray): ByteArray { + val h = IntArray(8) + val w = IntArray(64) + val temp = IntArray(8) + // let H = H0, which this table keeps as its own last eight entries + K.copyInto(h, 0, K.size - 8, K.size) + val words = pad(message) + // enumerate all blocks (each containing 16 words) + var i = 0 + val n = words.size / 16 + while (i < n) { + + // initialize W from the block's words + words.copyInto(w, 0, i * 16, i * 16 + 16) + for (t in 16 until w.size) { + w[t] = smallSig1(w[t - 2]) + w[t - 7] + smallSig0(w[t - 15]) + w[t - 16] + } + + // let TEMP = H + h.copyInto(temp, 0, 0, h.size) + + // operate on TEMP + for (t in w.indices) { + val t1 = temp[7] + bigSig1(temp[4]) + ch(temp[4], temp[5], temp[6]) + K[t] + w[t] + val t2 = bigSig0(temp[0]) + maj(temp[0], temp[1], temp[2]) + temp.copyInto(temp, 1, 0, temp.size - 1) + temp[4] += t1 + temp[0] = t1 + t2 + } + + // add values in TEMP to values in H + for (t in h.indices) { + h[t] += temp[t] + } + i++ + } + return toByteArray(h) + } + + /** + * **Internal method, no need to call.** Pads the given message to have a length + * that is a multiple of 512 bits (64 bytes), including the addition of a + * 1-bit, k 0-bits, and the message length as a 64-bit integer. + * The result is a 32-bit integer array with big-endian byte representation. + * + * @param message The message to pad. + * @return A new array with the padded message bytes. + */ + private fun pad(message: ByteArray): IntArray { + // new message length: original + 1-bit and padding + 8-byte length + // --> block count: whole blocks + (padding + length rounded up) + val finalBlockLength = message.size % BLOCK_BYTES + val blockCount = message.size / BLOCK_BYTES + if (finalBlockLength + 1 + 8 > BLOCK_BYTES) 2 else 1 + val result = IntArray(blockCount * (BLOCK_BYTES / 4)) + + // copy as much of the message as possible + val wholeWords = message.size / 4 + for (i in 0 until wholeWords) { + result[i] = intAt(message, i * 4) + } + // copy the remaining bytes (less than 4) and append 1 bit (rest is zero) + val remainder = ByteArray(4) + val left = message.size - wholeWords * 4 + for (i in 0 until left) remainder[i] = message[wholeWords * 4 + i] + remainder[left] = 0b10000000.toByte() + result[wholeWords] = intAt(remainder, 0) + + // ignore however many pad bytes (implicitly calculated in the beginning) + // place original message length as 64-bit integer at the end + val msgLength = message.size * 8L + result[result.size - 2] = (msgLength ushr 32).toInt() + result[result.size - 1] = msgLength.toInt() + return result + } + + private fun intAt(bytes: ByteArray, offset: Int): Int = + ((bytes[offset].toInt() and 0xFF) shl 24) or + ((bytes[offset + 1].toInt() and 0xFF) shl 16) or + ((bytes[offset + 2].toInt() and 0xFF) shl 8) or + (bytes[offset + 3].toInt() and 0xFF) + + /** + * Converts the given int array into a byte array via big-endian conversion + * (1 int becomes 4 bytes). + */ + private fun toByteArray(ints: IntArray): ByteArray { + val out = ByteArray(ints.size * 4) + for (i in ints.indices) { + out[i * 4] = (ints[i] ushr 24).toByte() + out[i * 4 + 1] = (ints[i] ushr 16).toByte() + out[i * 4 + 2] = (ints[i] ushr 8).toByte() + out[i * 4 + 3] = ints[i].toByte() + } + return out + } + + private fun ch(x: Int, y: Int, z: Int): Int = (x and y) or (x.inv() and z) + + private fun maj(x: Int, y: Int, z: Int): Int = (x and y) or (x and z) or (y and z) + + private fun bigSig0(x: Int): Int = x.rotateRight(2) xor x.rotateRight(13) xor x.rotateRight(22) + + private fun bigSig1(x: Int): Int = x.rotateRight(6) xor x.rotateRight(11) xor x.rotateRight(25) + + private fun smallSig0(x: Int): Int = x.rotateRight(7) xor x.rotateRight(18) xor (x ushr 3) + + private fun smallSig1(x: Int): Int = x.rotateRight(17) xor x.rotateRight(19) xor (x ushr 10) +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksBigIntTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksBigIntTest.kt new file mode 100644 index 000000000000..f8c56aab6145 --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksBigIntTest.kt @@ -0,0 +1,156 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksP256 +import jamorham.keks.crypto.KeksUInt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * The shared whole number type against values taken from `java.math.BigInteger` on the JVM. + * + * This is the layer the rest of the handshake stands on, so it is checked hardest: every row here + * was produced by the Java that ships on Android today. + */ +class KeksBigIntTest { + + private val p = KeksP256.P + private val q = KeksP256.N + + @Test + fun modulusAgreesWithJava() { + for (row in KeksGolden.bigMod) { + val a = bigOf(row[0]) + assertEquals(row[1], a.mod(p).toHex(), "mod P of ${row[0]}") + assertEquals(row[2], a.mod(q).toHex(), "mod Q of ${row[0]}") + } + assertTrue(KeksGolden.bigMod.size >= 60, "not enough rows to be worth anything") + } + + @Test + fun arithmeticAgreesWithJava() { + for (row in KeksGolden.bigArith) { + val a = bigOf(row[0]) + val b = bigOf(row[1]) + assertEquals(row[2], (a * b).toHex(), "product") + assertEquals(row[3], a.mulMod(b, p).toHex(), "product mod P") + assertEquals(row[4], a.mulMod(b, q).toHex(), "product mod Q") + assertEquals(row[5], (a + b).toHex(), "sum") + assertEquals(row[6], a.addMod(b, p).toHex(), "sum mod P") + assertEquals(row[7], a.subMod(b, p).toHex(), "difference mod P") + assertEquals(row[8], a.subMod(b, q).toHex(), "difference mod Q") + } + } + + @Test + fun inverseAgreesWithJava() { + for (row in KeksGolden.bigInverse) { + val a = bigOf(row[0]) + if (row[1].isEmpty()) { + assertFailsWith("zero has no inverse mod P") { + a.mod(p).modInverse(p) + } + } else { + assertEquals(row[1], a.mod(p).modInverse(p).toHex(), "inverse mod P of ${row[0]}") + } + if (row[2].isEmpty()) { + assertFailsWith("zero has no inverse mod Q") { + a.mod(q).modInverse(q) + } + } else { + assertEquals(row[2], a.mod(q).modInverse(q).toHex(), "inverse mod Q of ${row[0]}") + } + } + } + + @Test + fun powerAgreesWithJava() { + for (row in KeksGolden.bigModPow) { + val a = bigOf(row[0]) + val e = bigOf(row[1]) + assertEquals(row[2], a.modPow(e, p).toHex(), "power mod P") + assertEquals(row[3], a.modPow(e, q).toHex(), "power mod Q") + } + } + + @Test + fun bytesRoundTrip() { + for (row in KeksGolden.bigMod) { + val reduced = bigOf(row[1]) + val bytes = reduced.toBytes(32) + assertEquals(32, bytes.size) + assertEquals(reduced.toHex(), KeksUInt.fromBytes(bytes).toHex()) + } + } + + @Test + fun tooBigForTheRequestedLengthIsRefused() { + assertFailsWith { + KeksUInt.fromHex("ff00000000000000000000000000000000").toBytes(16) + } + } + + @Test + fun shiftsMatchTheObviousAnswer() { + val value = bigOf("123456789abcdef0fedcba9876543210") + for (bits in 0..130) { + val up = value.shl(bits) + assertEquals(value.toHex(), up.shr(bits).toHex(), "shift by $bits and back") + } + assertEquals("0", value.shr(1000).toHex()) + } + + @Test + fun divisionIsRightForDivisorsTheHandshakeNeverUses() { + // Every value above divides by P or by Q, and both of those are eight words long with the + // top bit set. That leaves two branches of the divider untouched: the single word divisor, + // and the normalising shift. They are checked here against the definition of division + // rather than against Java, because Java was never asked these questions. + val divisors = listOf( + "1", "2", "3", "ff", "100", "ffffffff", "100000000", "7fffffff", + "0001000000000000", "123456789", "8000000000000000", "0fffffffffffffffffffffffffffffff", + ).map { bigOf(it) } + val values = KeksGolden.bigMod.map { bigOf(it[0]) } + listOf(KeksUInt.ZERO, KeksUInt.ONE, p, q) + for (value in values) { + for (divisor in divisors) { + val (quotient, remainder) = value.divRem(divisor) + assertTrue(remainder < divisor, "remainder of ${value.toHex()} / ${divisor.toHex()}") + assertEquals( + value.toHex(), + (quotient * divisor + remainder).toHex(), + "quotient times divisor plus remainder for ${value.toHex()} / ${divisor.toHex()}", + ) + } + } + } + + @Test + fun dividingByZeroIsRefused() { + assertFailsWith { bigOf("ff").divRem(KeksUInt.ZERO) } + } + + @Test + fun comparisonIsByValue() { + assertTrue(bigOf("ff") < bigOf("100")) + assertTrue(bigOf("100") > bigOf("ff")) + assertEquals(bigOf("0"), KeksUInt.ZERO) + assertTrue(KeksUInt.ZERO.isZero) + assertTrue(KeksUInt.ONE.isOne) + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksCurveTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksCurveTest.kt new file mode 100644 index 000000000000..fdbbae277753 --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksCurveTest.kt @@ -0,0 +1,113 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksP256 +import jamorham.keks.crypto.KeksUInt +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue + +/** + * The secp256r1 point arithmetic against values BouncyCastle gave on Android. + */ +class KeksCurveTest { + + @Test + fun curveNumbersMatchBouncyCastle() { + assertEquals(KeksGolden.curveQ, KeksP256.N.toHex()) + assertEquals(KeksGolden.curveQM1, Curve.QM1.toHex()) + assertEquals(KeksGolden.curveP, KeksP256.P.toHex()) + assertEquals(KeksGolden.curveA, KeksP256.A.toHex()) + assertEquals(KeksGolden.curveB, KeksP256.B.toHex()) + assertEquals(KeksGolden.curveG, KeksP256.G.getEncoded().hex()) + assertEquals(KeksGolden.curveBits, Curve.CURVE_BITS) + assertEquals(KeksGolden.fieldSize, Curve.FIELD_SIZE) + assertEquals(KeksGolden.packetSize, Curve.PACKET_SIZE) + assertEquals("secp256r1", Curve.name) + } + + @Test + fun baseScalarMultiplicationMatches() { + for (row in KeksGolden.scalarMulG) { + assertEquals(row[1], KeksP256.G.multiply(bigOf(row[0])).getEncoded().hex(), "k=${row[0]}") + } + } + + @Test + fun additionMatches() { + for (row in KeksGolden.pointAdd) { + assertEquals(row[2], pointOf(row[0]).add(pointOf(row[1])).getEncoded().hex()) + } + } + + @Test + fun subtractionMatches() { + for (row in KeksGolden.pointSubtract) { + assertEquals(row[2], pointOf(row[0]).subtract(pointOf(row[1])).getEncoded().hex()) + } + } + + @Test + fun multiplicationOfAnyPointMatches() { + for (row in KeksGolden.pointMultiply) { + assertEquals(row[2], pointOf(row[0]).multiply(bigOf(row[1])).getEncoded().hex()) + } + } + + @Test + fun coordinateBytesMatch() { + for (row in KeksGolden.jecPointBytes) { + assertEquals(row[1], JECPoint(pointOf(row[0])).toBytes().hex()) + } + } + + @Test + fun infinityBehavesTheWayBouncyCastleDid() { + val g = KeksP256.G + assertTrue(g.multiply(KeksUInt.ZERO).isInfinity) + assertTrue(g.add(g.negate()).isInfinity) + assertEquals(g.getEncoded().hex(), g.add(KeksEcPoint.INFINITY).getEncoded().hex()) + assertEquals("00", KeksEcPoint.INFINITY.getEncoded().hex()) + assertFailsWith { KeksEcPoint.INFINITY.xEncoded() } + } + + @Test + fun doublingAgreesWithAddingToItself() { + for (row in KeksGolden.scalarMulG) { + val point = pointOf(row[1]) + assertEquals(point.add(point).getEncoded().hex(), point.twice().getEncoded().hex()) + } + } + + @Test + fun aPointOffTheCurveIsOnlyRefusedWhenItIsUsed() { + // BouncyCastle's createPoint did not check, and multiply did. The ONE+ driver depends on + // that: it catches IllegalStateException to call an out of step handshake a failed one. + val good = pointOf(KeksGolden.curveG) + val bent = KeksEcPoint.createPoint(good.x, good.y.subMod(KeksUInt.ONE, KeksP256.P)) + assertFailsWith { bent.multiply(KeksUInt.of(5)) } + } + + @Test + fun aCoordinateOutsideTheFieldIsRefused() { + assertFailsWith { + KeksEcPoint.createPoint(KeksP256.P, KeksUInt.ONE) + } + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksGolden.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksGolden.kt new file mode 100644 index 000000000000..d9c1a02213ca --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksGolden.kt @@ -0,0 +1,553 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +// GENERATED. Do not edit by hand. +// +// Every value here was produced by running the ORIGINAL Java libkeks - the 24 Java files taken from +// NightscoutFoundation/xDrip at pin 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f - against +// BouncyCastle bcprov/bcpkix 1.81 on a JDK 21, before any of it was translated. The Kotlin port +// has to reproduce them byte for byte. +// +// To make it again from the pin: take the Java sources, let a test driver poll pinned values in +// Curve.getExponent(), new KeyPair() and Util.getRandomKey() when a queue is not empty, then drive +// jamorham.keks.Plugin against a second jamorham.keks.Context standing in for the sensor (its +// alice and bob labels swapped) and write down every message. The three values that no amount of +// pinning fixes are noted where they are used: BouncyCastle's ECDSA drew its own random number, so +// the `ecdsaSign` rows carry the number recovered from each signature instead. +package jamorham.keks + +@Suppress("MaxLineLength") +internal object KeksGolden { + + val config: List> = listOf( + arrayOf("SPARAM", "02"), + arrayOf("TIME_EXTENDED", "0619"), + arrayOf("TIME_EXTENDED2", "ff0601"), + arrayOf("TIME_EXTENDED3", "0600"), + arrayOf("PREFIX", "3030"), + arrayOf("KEYCMD", "0a"), + arrayOf("KEY1A", "3059301306072a8648ce3d020106082a8648ce3d030107034200040af826f029d12615ca3b8959bdc594ba0330e3497d6ec1e9eff87601e7e3f0d54c8ef5bde30fc5ac1ac4333cd0362fd3152fa661421609780ff660470313ea9a"), + arrayOf("KEY1B", "308193020100301306072a8648ce3d020106082a8648ce3d03010704793077020101042035152c4844019f18b50e7449bf0cfa9068251ffa326284abbd86f45360bf031da00a06082a8648ce3d030107a144034200040af826f029d12615ca3b8959bdc594ba0330e3497d6ec1e9eff87601e7e3f0d54c8ef5bde30fc5ac1ac4333cd0362fd3152fa661421609780ff660470313ea9a"), + arrayOf("KEY2A", "3059301306072a8648ce3d020106082a8648ce3d0301070342000448c0ec4f63f4f4786d0b5df8930305cfe07d036140fc5f0fe3fa5f645edeca660e5399196ca6c8f919edf3e4c7df94632ec6958353fe8e90157aa9aaca5c2b58"), + arrayOf("KEY2B", "308193020100301306072a8648ce3d020106082a8648ce3d030107047930770201010420d83c43b3db07b3d12616548632c73cdc87c66a29d6b794d2335acf1c50099aaca00a06082a8648ce3d030107a1440342000448c0ec4f63f4f4786d0b5df8930305cfe07d036140fc5f0fe3fa5f645edeca660e5399196ca6c8f919edf3e4c7df94632ec6958353fe8e90157aa9aaca5c2b58"), + arrayOf("ALICE", "636c69656e74"), + arrayOf("BOB", "736572766572"), + arrayOf("REFERENCE", "a10888707f9e357c450ae2d0c315afd2e23d7d9649035ad119d0f4cbabe3fef2"), + arrayOf("GETDATA", "4e0aa9"), + arrayOf("GETDATA2", "4e"), + arrayOf("CHALLENGE_OUT", "0d0002"), + ) + + val intToByteArray: List> = listOf( + arrayOf("0", "00000000"), + arrayOf("1", "00000001"), + arrayOf("65", "00000041"), + arrayOf("97", "00000061"), + arrayOf("255", "000000ff"), + arrayOf("256", "00000100"), + arrayOf("65535", "0000ffff"), + arrayOf("2147483647", "7fffffff"), + arrayOf("-1", "ffffffff"), + arrayOf("-2", "fffffffe"), + ) + + val hexStringToByteArray: List> = listOf( + arrayOf("", "null"), + arrayOf("00", "00"), + arrayOf("0f", "f0"), + arrayOf("ff", "ff"), + arrayOf("0123456789abcdef", "1032547698badcfe"), + arrayOf("A1B2", "1a2b"), + arrayOf("zz", "ef"), + arrayOf("0", "null"), + arrayOf("abc", "null"), + ) + + val tolerantHexStringToByteArray: List> = listOf( + arrayOf("", "null"), + arrayOf("hello", "null"), + arrayOf("DE AD-be:ef", "eddaebfe"), + arrayOf("0x12 0x34", "100243"), + ) + + val bytesToHex: List> = listOf( + arrayOf("", ""), + arrayOf("00", "00"), + arrayOf("00ff10", "00FF10"), + arrayOf("deadbeef", "DEADBEEF"), + ) + + val sha256: List> = listOf( + arrayOf("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), + arrayOf("99", "fd9528b920d6d3956e9e16114523e1889c751e8c1e040182116d4c906b43f558"), + arrayOf("1834", "9603a94c58e72cbd81d486f0fddd1ab05ea5e10eee5c44914646f160a89dbef8"), + arrayOf("5a94c9", "347d6dc36224ffee4900070e5126245cb5e08c32e3ba33e1a09c357b943194fc"), + arrayOf("390b7702", "6b2c63ed198c392bcb91de88e9dbc1f7f08ea904a43c21624bbceee8a99a16a3"), + arrayOf("09d32a595d4a987d41f4b3e592471abe05194bb55dcab3910016175aa147e1", "32e6044bba5953678c114cd9400ad69f0269865f1bd349832f7206d88f04af5d"), + arrayOf("e98ee81edf7fae40bfe793d9fced52b202e34d15e5c4caaf166fc2edcea4fb1b", "3601bf4eb05cf3fc912ff8370bca2edf3b3dfeb20c4b0337ff5bd88d18038c1b"), + arrayOf("65e240a4e944b31d0705e6c8b71cf8bdfc97c696693058b22edd1479f1953297e1c82141a6a46d99364cf461b317c99fee614cc5a74b02", "b96eb06c76ace7070f75df7823152b3578a228debd98d8a61531c61903e32803"), + arrayOf("8f814e38d93995b694aa2150847891d75da8ddddc46434afeb50781ae04364f9b3a3f3707eab79470ba3c885b66c499800da641a22a420ee", "03e5ad10e01a7d86ebb199fd9fcd72c4feeb119f525ce0aef8b0ea27654ad9b4"), + arrayOf("9989ec985901e416c9c38fbf7ae22a00a4174c64b5144dc69831c2d5e9f8c7dcb1c3a276da03c5c5347dd8728b234273149eb6e9bb0ff5f411", "7e83ef92a9f3dec65797f759513ff8483e5a7909be8fb2a4d718e1c217259731"), + arrayOf("9a0168a981181c9a324f0aec09395a3213018ebde232b69b463dffe94c73ba9c9960c80b6a214cc7b067f90295b0180a98eba8fce9bf8a819b01f5529ebc20", "73233ccde163b6a95ed3a9701ac7db08f3cfe425025efa8658a55f9c60300d7f"), + arrayOf("acd4d95a6166595aac5e505cd63fcdf74452a17edaf2ce71419a6512500fcbc182e1ef30721c8d57fcee80eefd07ad4165535585b7631557828266251de9a592", "b60d1f964f998fa76d5dd391365bd9fa29de448d3ad67b83a3d41c4a7741944d"), + arrayOf("2a08574138340c697fa982fdf2e1e031eefc636a590b94b3ede70bfeb7c6e8d2988f49d867b8331c96310e56cf20194df51cd6eaec0958b9d72ecb53418e134a23", "43c62a73867505e834e7368c518cf4d848b722395eb0ee5da54499990d2539ce"), + arrayOf("437cb251a58953f96424e7bd33a2e0636ebdbbc1d586f9d6d6c93e220a5d0110261aba5c976f7d07b2bbc679878c62d4332819cc438fd8e801b24847eafa8ebbfe41e1be58c9936f70570198736d008963a7f2f0c00be3754308a9a9492a58e7cc5791c758218f6b8a0cd56d9d78ff727bf90b64b0a84b", "ecd4e08f7001b11b431acdb02c08520e3f755d9ff659052ec44ca3edd3247400"), + arrayOf("91c1f5840f7f8dc02662199f0e33af179c6689465024424cc8942db5b9cfdf14d380620108d6bbd2b548c06e738766847b0a5cf9f95908d5ef4d8c7c468cc00866e1c466630d8f49b862706883216d7aac286f32aa3655aa684e0f850780a35a9b91e79e364d03868055d669c03accc8ebbf23ff9a5b1c6e", "27141801e9dee0d9e10e39aa6e7d4a86f88b9935f15a67148f6f5c708c493cce"), + arrayOf("fe5aeed36fe78d7e363d36f4f7df46f0f2420dd8af0ff55ca6af8911a2ce983c516a62a235ae3be7ef470cd1049bce150848321a58bc3495809acf39c16a6fb4548b627bd393a4e4f45730c31cd75ed1504b79caca281736ce98dcc79ae07e29cf1ba7340a6051cb66b0462ee4f80a716b1b9d4e95058b2b1dbb7de2f1467f", "cadd4bdaa9a3f430d634e6f01e5520991b0c9eb4852089ebd03cab3c5745bb27"), + arrayOf("dd4e6d675c277308d75b44e764896d8c8fddc4094ed8d8c6aa5cd164323bd3336f03b562919fee92d2262d6a87de9a8306cc38c30e18bf7ae845da7dea912cbcc8eaf24d3384cd3d536aa67a9e53906dad44802ef359452ffe9e64214b97e66900ff7058110bc8cc4ba628c7de1122937627c3ba9e8d182746b2a654addf377e", "0cfb1fa462b87731f3549d9837ff6c883dfee8fb118c558bd466da9ec3ad1edf"), + arrayOf("8149d75ec068d84f1eecd995dd68a971e68488f0b4498218d07e478407a89d358df9966515650a3724195b9919b7f5a6979c2cae5d284d8cdd1ab55c7ac6224fb5ca31a4acfff8c32be111cb71e24116b72ba884c83328cd64e6f410c72a64ce63bb97a26524acfaf3a8b98faa60300c880b834fa5625bb2908d5797d3ee74dc52131517e16fc8f7b130457aebcf0f26de1f0ce4a924df583fdbba262af7034e10ba8ac80904439e8d0e5bb8411fea46a495305d0eff286e855b432a7a2365ff83ddeab5886c0be323f9f6921c4720f357718c1a10393f0827ceb7f4130f60e961e833294c935d9906e2f974d0919401896d8e027198e5262169e8b76e61e68bb6c8632909c5ad8638e0b2981574a5af5f29c9f8f52df5e121ebcba7a3ae130e62861df4b5c560b1b4eaaad488f57acb14a7cbc2e73131f9097e3cbcf1e7183d9829fbc40df5c151e5623dff28a968d6741a1bc793f02af270697e373a5cf56561f1c5350f83e9882c6fc707d93566b76207282bcac606312295faf284481fe017da0ef07eb484055d257833e46ee0d352b058d6612e34819cdbd67679f87d01ea73e13d6237b20a42850be375fc642bcfd482c9b1da6a53912c560ce776571e5e098b44858764e11743fae51c94ea60f7bf6e0b19e57e8e677f2a4e42ce132acb15b059f662fc980c62e8a64dc1b772faa63d247809de30ba9522351dd9f787dc0b2af08a4e0d20c79e5c6ce03d2a409e57cdc2b3f2c728d98ddd42b5a2399d116c670f562a7e2adfa90a8091dae0e2be3673b0359793b944456e37665710c03d2b482536d6770e62323a4e81f7094fc68ea8a86aa5937c348b18b233c5a1310869b0474ae6d3bd50c01476b38cd8a4392e820343006c8c13239238426cefea6e764ba87367fd451d5fe45290c2611b2b560d63b54beab1ff9671635e1f25273e2c3912dbb375cc33188dbd641a6573c8f8ebbc3989b3794cdab4597434ebbf9b919fc66a576fd26d3dcba4de26c16ecb47ca2a4ec458f2ffbb895816459ea27fd25af2510431a69e8300a294d496df079387e5f3cea4725329c2bffb7e8edf338645448397324d08ed99df7d425d80e2762cb02d0e353038409efe7d84a816d945d3e0372d26dee583587d752a68ecd55a08c18756af9ecf31d6c719dd294fe292f70c68455f36e2e4061ebcd9a2beed3f90e88dd82688eff40d27f3f5429a980d936f55f849329f99657177b981124ddfd84e501d828fa3c81c6d4fb2c83a95fbe0b5013be4143043585c2e676c61aa18c6a1e512f455aa86d26b198c576e4a1e9fbcb4336b969f949dd84c5d22fdcdb049f7e628daccf6c524255e448a5e7ad9e91c789eae26671d9cc4a32bdc3515604bf8ef7c91552ecdede4d1232633bca906219c41bc4b", "824dae766cf2d078b4beed1677b836de82fabb0c46a71c23631ee3e7cfbb3de8"), + arrayOf("616263", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"), + ) + + val digest: List> = listOf( + arrayOf("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"), + arrayOf("00|", "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d"), + arrayOf("0102|030405|", "74f81fe167d99b4cb41d6d0ccda82278caee9f3e2f25d5e5a3936ff3dcec60d0"), + arrayOf("deadbeef||cafe|0011223344556677889900aabbccddeeff|", "02c107e036feae468e14ce3eb08e65a01232e98a7fb3ba4f9eb326e2d06fab7f"), + ) + + val aesEcb: List> = listOf( + arrayOf("e59bf7ba9862f4b62fa0666d872ec936", "22df26a1366d3b66f8f8c106fbcaf7e8", "f6a1ec7e30d1a5375cfff0e612c83bbe"), + arrayOf("63976330474e35491d77230bbd66708d", "46f54e6fa2485770d4ad85ab2c6c49fb", "83f424e934ff2069f3ae05b028f97719"), + arrayOf("a5edf25ab734f83cf1117ee9f5698f5a", "2b3868218bdd26859b2cc4a8b86153e8", "67cff0c252ae008814cb61d6bd18546f"), + arrayOf("2b23c52d00aa1a5a42c5ec67ecdcfc0a", "ac5005885a162fb8d036599bffebadb4", "32f2b833b9307700e946b24e5feb1387"), + arrayOf("c8b007fefec15ec71e64aa58c073c59d", "354dc12e7b153b47a9ff0952016d6e4b", "a159a6c9e851a129785f99680d8ace86"), + arrayOf("24ba98ebcec4a905851a94b677faf0d3", "4940c78ee1b18114902e5643e57864be", "0058ea4bb25016adf9dea6f5c6fb7e56"), + arrayOf("3a14da4d55f3b4dbeb17f8f579edaf73", "fd2e3f3680034e2ca6b1766a7676b85d", "daae86ea0ef4dd953c4ec2e61a4a7da2"), + arrayOf("db9b6e3cb95b6268ba099fef12a273cd", "7a4ffa7dd2ff7c7d3b6074f5a1cf8dfb", "5482205f61d2486231060ef17438b0ec"), + arrayOf("000102030405060708090a0b0c0d0e0f", "00112233445566778899aabbccddeeff", "69c4e0d86a7b0430d8cdb78070b4c55a"), + arrayOf("000102030405060708090a0b0c0d0e0f", "00112233445566778899aabbccddeeff000102030405060708090a0b0c0d0e0f", "69c4e0d86a7b0430d8cdb78070b4c55a0a940bb5416ef045f1c39458c653ea5a"), + ) + + val calculateHash: List> = listOf( + arrayOf("2adcdbc8e5bd2766cd659a44f2feb23f", "7e97f877532662c4", "d36e5b3c2f610c5e"), + arrayOf("576d80c1f8b18ae21f054a63098041c6", "f784a1a0acc45d8c", "6140564da9766c10"), + arrayOf("dc9aa1ba053de54735aaf85d325f6740", "0432dc3118b39f2e", "2786e4be02638f82"), + arrayOf("7a8d07703a664071f7b9ca8ded1ceb70", "c298c131a80de707", "bb857b4408e2d8e2"), + arrayOf("faff5ad74927bf91902d94757771da1a", "4ba0e4c7948e5b74", "04fd26af6019d5fd"), + arrayOf("224ee069da58dc9775742b439790e00b", "e625c92ba48769b7", "724972d04a956433"), + ) + + val passwordBytes: List> = listOf( + arrayOf("1234", "31323334", "31323334"), + arrayOf("123456", "3030313233343536", "3030313233343536"), + arrayOf("", "", "0"), + arrayOf("abcdef", "3030616263646566", "3030616263646566"), + arrayOf("12345", "3132333435", "3132333435"), + arrayOf("1234567", "31323334353637", "31323334353637"), + ) + + const val curveQ = "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551" + const val curveQM1 = "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550" + const val curveP = "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff" + const val curveA = "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc" + const val curveB = "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b" + const val curveG = "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" + const val curveBits = 256 + const val fieldSize = 32 + const val packetSize = 160 + + val scalarMulG: List> = listOf( + arrayOf("1", "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), + arrayOf("2", "047cf27b188d034f7e8a52380304b51ac3c08969e277f21b35a60b48fc4766997807775510db8ed040293d9ac69f7430dbba7dade63ce982299e04b79d227873d1"), + arrayOf("3", "045ecbe4d1a6330a44c8f7ef951d4bf165e6c6b721efada985fb41661bc6e7fd6c8734640c4998ff7e374b06ce1a64a2ecd82ab036384fb83d9a79b127a27d5032"), + arrayOf("ff", "04f44b39759a2e6db723a6f90249972dfd08e95380f1fca470eacd1d03e5edf214befafccf223ca065f0a0db4eea93ff06a2116fca81f7a4a9436a8d917a02dede"), + arrayOf("10001", "041a32b7207dface203fdee0ce2a4c7e1d33d4003d227b23a5404751a0106a9bb75b09abf820d0206b43e965bfc80eaed843f80e06c545a705f400133a6c55bce4"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550", "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296b01cbd1c01e58065711814b583f061e9d431cca994cea1313449bf97c840ae0a"), + arrayOf("5862d4ba58283054ee31d2717d63440547f1200d7c2130c30a0057b81a10442a", "049c1efdf81c643be29726ee4014f9696b0a7a6ba9caf6736c033ac8ae60dbd11387e673fd61f1594ad8f3f9a5e7d4e27473314fd0fdf1ef252e550d204cf5e08f"), + arrayOf("f1540869259477dcc908b6146815c7f3d28ee8e7c675d4b7f45670667429bb69", "04d216e9fecc73f3a813b50a98b3ff5dc78e0098044827244fd000056102ea79dce8b65a80971c8ad1db5abd693f03535635e7f01ee288a60bf80c8acc5b0abbf6"), + arrayOf("997d6ac3725cbc90398617e3b0116d38d63823dd7d425420f96791f83b49dca8", "043167daea5b410483a1cd8c96b4d49aa4b3d74477f3bfed90bff1f364016cce27175af1146724c675cf84fcecc109f6538c48388b900c02ec51feeabe7f9d5ad9"), + arrayOf("f1f342106360be5560a1304e6447ac385d9c5af2e74051e6b6967071702a05d5", "0411b01c51c0f43b42243533ec4e88b2ab6aef6748d556234282efd578b849f5992db6c439285a1648878bcb263041f4526bf650710b7edf14d405eafc577635a7"), + arrayOf("ea720537f73e983f43734899bca8d7828c1b0fcef80b9ee9a824c805c79c5b6", "04e914a9019e8239301bda381ec83caca66a340e58f1fe8020fd8274b19571ec1a376fd306324f3db2e548a3828c34f5f09f65f849e5a8aa901bf94ba9a8f06eef"), + arrayOf("f857492533061298bfcc049fedf0a3a6272c451ca119d64e692dc0000a38ca77", "043938d3156ad6230e3826d66a4fab05778581a1304c09eb5c3fb1b152f2ea4a96ca0cf30c3cac0130ba1e8f84db040a3657b26d8b79c32c7962826ce8d69a0e55"), + arrayOf("2c643edd4f5eee021e9694c7f87df7a002d22bf1b1694f45ba718549c8322120", "0427c3d0e7fe948144e4c546f05f53dd60775855df4c6ba18674b9d51bce7f50ab154f6f71d8cd64095d67fa4807fe358be4113b916e5e3164903af5fe099ef310"), + arrayOf("1b6020e5875f4edc83dcc8aadcdfbd5493d95f5cf5e748ca7ac99fbbaa84c6f7", "04ae6a12567828b35116e63a853fdd00d049ec4f53111eb4be3e130e9ba0e6723a84cac42e55fdfc150ca773cd0fd68ebb8db237c543c9da1dbaa0102f8257d50e"), + arrayOf("a981fb8ef3e3531df3a8fa5fc07bea026a2e5cc2e783f60b6864a9f8072caea5", "04ec4402854d5df68f00039f91a1fdb0ec41e9143741c1061502d98e942423c1691f32a1d3c337e82582feefd651bb78e113c092735c8f33af1f174171b151bd0e"), + arrayOf("aeda46cd8fa42d6b89c36e024b0aede348e3431024964db7968e3c84faaebb19", "04d5cad836557d2b79e0533763294c10062289ed85d4dfff6be9f389989e3403846b0e0d084f2e873b6a60b8c6feb60a488e27b85209ceda041f012742eb4dd9e5"), + ) + + val pointAdd: List> = listOf( + arrayOf("04614f930b9766f5a6f2fcf006118e706f6e8aebb5169356906316a2285f5e87dc594986449b1510c5b877ae172f7105afec868c3a7b03e1645d6bd171a52433d8", "04e4bbcc82a659bf6ec8044c55470f55ca49c3b9cc5f3dce4b652f177a57869d26b66b8d378421307ac9678835d06f128d2b1ab6f7fb8b5787630301eec9f77462", "0434eb90d49ac07d68d1b9ce2cdd11abc3711be4ee9f512d35ff9776b96a13785ec81ec6fa1c310070eb48b852f1b4a5222a86de83646b5f4e2a6e6f382f302c32"), + arrayOf("04cdf7b22675ca384ef7acfa769b3fa61a507ab6717afccf15b75ab3092702fc16362d6160083b12695d927b3bcd713e062b3be0be8437babfbe2093e68136aec4", "045a0d2dd4bb1b18cd5e2ea21598f8d8419678f6883d07afcb6094644fe3527c9ef6045736cbbd16fa522a06953d30b90fd1aec3bf27fd9a99d39579c25e01b811", "04a031c87917b8ae5a0fecd0221a08da5bf94e254a2b562e32cad6ce05b346b9438db6fe13f115e51625aac642503b5ffa26c702b745d90f0bce2392abeb84527e"), + arrayOf("04449a9d882c59c641deee390ad094c27a917f7c51f63df498a4d602c9f22cd9489307bbc3115bf7890d0ed44f0137ef6051979dda9aff6a077107e24dd229e45b", "041c0c4a7a99e6e08db7f3d196f9181af7f2eac826620b65d1c5dc39e067a44464cff00879481b4b5a0a812f237225477edf9966ea0c1455b47e2afc0e4ec5179a", "04ffbe690a23ffd5286e39699d88b411513170ebcc86d82a6e025f5c71e9dd4dec34d05cac580c66ad6fd37891edaeca4d770002e03b6419eaf98cb3b28fcec731"), + arrayOf("0417cd956903981a8a533d5eecb6c8a25406966fa61f5e5c14df4a0998600712d1d9815cce040deba70218bb38967cc63873beff15534d21f953e3f6e07d459ed7", "04e6928d7c9da05cb7ec25c337193a408188e43d65248c9b1e12e4a2c9a5c78f192d356071e7f5f30c2defa8f769a91152881a21fa5072d0a2e517902b5f7c8e62", "04e8ef247588f5cc2765232e0060da0021135aa995b3b2257289d4ae85d8d4fc0718419139c7e478e605509a3c9e87c63688b6ccf4ef4bf090fca43b74879e7ce2"), + arrayOf("04905be72cc75724ba1e291ee216c908496da4a6f3a2f8eedbe448210a94a5942df6711aec399deaa54799e83d213fd537db0a4475ca9e804b7eca40f6885ebd62", "04303291deb5d5cc7e718fa46f59a6638783e402b1188a2bbd110726308b218c9da7c96e9d8315d67c65bd2367feb2d14532087208f1df7b95d05232bbe94508c5", "04642882b62a3e556c7413ac56ac7f697599d7ef7306bb4de3e5ea43540e15a687ea1428fe3896fa763493020ecee8d0f6ecec5bc05a22b811aaeca9f0030e67d4"), + arrayOf("04504e0167093ba23e46283322be113cc6c99084fa6990e7eb0d4dc57a943bf2011e1886a603f7346139eaaa19c65397fe8f91d348777f478a41466335e2bf75cb", "0492ce55a9017c8d9d6ed70b8342de0538b96f0ae8960a58e9bba9f7ad95b27769487fcd7e2aea46e43c9288c03b03ea3ffa90dec21549d4bbbcbd526783ee24be", "04e8acf279d54c2cf97ed710e7a4194ef4aa7feb396b6eedc1d1bb1a9f89f3d0410f59a4091ebd7921a5afa348e31becb618e6ff3f150cce07a3faa4f123e3c175"), + arrayOf("04fd140f1a54a1448e1ad3b83f0ba6075b815a05b6df22f5abcd9cc77d74bca359dcedef2397d08e9850390a5493aec01132f15c411c578367641f4b97107de271", "0408991962fa4568ac1b593b79b59704f5e37d82e2c7511f9f44cc4e652a77a67b0705a777bf36f2ff98bf546284d2d06c987d1fcd5b141c6c0a6d5c6907cc1307", "04954c84292e69445ef971ae52ea1420e36de4066077554985b02fe64f380b8eae6298970f861ab508c5ded73b80d4840a5bb4421ca0e51b55968dc6f7604dda01"), + arrayOf("04d3756efa870a64de2dc21ba6b764f897f11ad7a50d5a315a1b4b36dc652870f7f241b85cbd9ed102c8041f71fd8b403d052dab9682a7b4d058ac96e115ae54e4", "042e37610c045a706babb2ee645f2f154e0ae54320ce413b953a4755fc5b1c0a1206d7cfa39145249cc7c2cb2d3ffc842215db90e8b41e56372ca37c4225281fe8", "04706084813df295348c0b625d5a360c03fb7f28c7dd26155aad92bf00e5cdc1e902bff29c2b5b5620072a163c13cb5d69afdf5c63405c5573b2f0e9b941be3353"), + ) + + val pointSubtract: List> = listOf( + arrayOf("04614f930b9766f5a6f2fcf006118e706f6e8aebb5169356906316a2285f5e87dc594986449b1510c5b877ae172f7105afec868c3a7b03e1645d6bd171a52433d8", "04e4bbcc82a659bf6ec8044c55470f55ca49c3b9cc5f3dce4b652f177a57869d26b66b8d378421307ac9678835d06f128d2b1ab6f7fb8b5787630301eec9f77462", "047031ba8492b59fb5f9657c25da0dfef26c015ea4abfd16cea27a878294c596f7671afecc1952fc993cf92af7314da32420dd1445499961be520f90fb8c281a6a"), + arrayOf("04cdf7b22675ca384ef7acfa769b3fa61a507ab6717afccf15b75ab3092702fc16362d6160083b12695d927b3bcd713e062b3be0be8437babfbe2093e68136aec4", "045a0d2dd4bb1b18cd5e2ea21598f8d8419678f6883d07afcb6094644fe3527c9ef6045736cbbd16fa522a06953d30b90fd1aec3bf27fd9a99d39579c25e01b811", "0461d384ca21568c935831ade4863977db64aab2953529fd5434d0eebacadc55e8f160257441659e0f7f228fdedaba2d5aa33615db9ff06b5d5517928e4e5d90a3"), + arrayOf("04449a9d882c59c641deee390ad094c27a917f7c51f63df498a4d602c9f22cd9489307bbc3115bf7890d0ed44f0137ef6051979dda9aff6a077107e24dd229e45b", "041c0c4a7a99e6e08db7f3d196f9181af7f2eac826620b65d1c5dc39e067a44464cff00879481b4b5a0a812f237225477edf9966ea0c1455b47e2afc0e4ec5179a", "0401ea99a345ae8861329322317631565eab9dc1389fe7ad03df4515a3e65b19a3f22dda6cf2a0ef2aa0f15970eb4a34baa640a64ab2faa2d2336a0da4471cede3"), + arrayOf("0417cd956903981a8a533d5eecb6c8a25406966fa61f5e5c14df4a0998600712d1d9815cce040deba70218bb38967cc63873beff15534d21f953e3f6e07d459ed7", "04e6928d7c9da05cb7ec25c337193a408188e43d65248c9b1e12e4a2c9a5c78f192d356071e7f5f30c2defa8f769a91152881a21fa5072d0a2e517902b5f7c8e62", "04b9e598dd195723c55e352f4f55493f875c0807221e491925d1f8662f99dc1b89546e25307800f960abc16c8ca2786fb2b4498c9d20bcfadf1bec0401b70bd1cd"), + arrayOf("04905be72cc75724ba1e291ee216c908496da4a6f3a2f8eedbe448210a94a5942df6711aec399deaa54799e83d213fd537db0a4475ca9e804b7eca40f6885ebd62", "04303291deb5d5cc7e718fa46f59a6638783e402b1188a2bbd110726308b218c9da7c96e9d8315d67c65bd2367feb2d14532087208f1df7b95d05232bbe94508c5", "049d581f29e69504041254e27f563aaffcf13ae95f2ac3fa95af6e9fb7cfd9653195defa68c3e0400ba85dd0c07c6c9aaf4e58d3868687fd2c9f87b5449801c180"), + arrayOf("04504e0167093ba23e46283322be113cc6c99084fa6990e7eb0d4dc57a943bf2011e1886a603f7346139eaaa19c65397fe8f91d348777f478a41466335e2bf75cb", "0492ce55a9017c8d9d6ed70b8342de0538b96f0ae8960a58e9bba9f7ad95b27769487fcd7e2aea46e43c9288c03b03ea3ffa90dec21549d4bbbcbd526783ee24be", "041027bae45a0b2b4a204dbedc2d1491333494346a2c02a86ab27990853961b4a4a23aa4a1d519ba45db943e1863a859eda9e9ed54211cf6749686f97898bc0c89"), + arrayOf("04fd140f1a54a1448e1ad3b83f0ba6075b815a05b6df22f5abcd9cc77d74bca359dcedef2397d08e9850390a5493aec01132f15c411c578367641f4b97107de271", "0408991962fa4568ac1b593b79b59704f5e37d82e2c7511f9f44cc4e652a77a67b0705a777bf36f2ff98bf546284d2d06c987d1fcd5b141c6c0a6d5c6907cc1307", "0438b3da757b1d64caf5fff2b3ab8972c0599e192a33bf2eb0647c647569da79a8ec008c051f78d3433e7907c8cba99a8abe08a7e5351ff47b5214a85512ed45cb"), + arrayOf("04d3756efa870a64de2dc21ba6b764f897f11ad7a50d5a315a1b4b36dc652870f7f241b85cbd9ed102c8041f71fd8b403d052dab9682a7b4d058ac96e115ae54e4", "042e37610c045a706babb2ee645f2f154e0ae54320ce413b953a4755fc5b1c0a1206d7cfa39145249cc7c2cb2d3ffc842215db90e8b41e56372ca37c4225281fe8", "045b951c4c52c1106e0c80b492c9a6fcd0d488563f95f1df35f57911782a0ba7582c292103895882d6ea42fff126c80c005679af9817cd03405791ea2522979665"), + ) + + val pointMultiply: List> = listOf( + arrayOf("04614f930b9766f5a6f2fcf006118e706f6e8aebb5169356906316a2285f5e87dc594986449b1510c5b877ae172f7105afec868c3a7b03e1645d6bd171a52433d8", "d0545a8a3b6b6d21d48ba522b3d7f12a361eeb556cacc523dc325ea062cd55ae", "04d62a799cc3fecebf52779386e3753c047bd113fa332368b96b2bd695d252439b4e931ed4dcf3c57896062380d2b9d5bbe675862bcc558c548d038346105fa700"), + arrayOf("04cdf7b22675ca384ef7acfa769b3fa61a507ab6717afccf15b75ab3092702fc16362d6160083b12695d927b3bcd713e062b3be0be8437babfbe2093e68136aec4", "1f9d84078e01cc7d87834c504cb7503f47bd6a321b78f6fbb027d0db60baa852", "045a3820fe2dc53e65b647f735ed7f3da5a2fd14875c6d85fd0c10235c82d607509b20a2eddb091a73d2cd080238bdffec47d74884a0038050280afdf71c953eb0"), + arrayOf("04449a9d882c59c641deee390ad094c27a917f7c51f63df498a4d602c9f22cd9489307bbc3115bf7890d0ed44f0137ef6051979dda9aff6a077107e24dd229e45b", "db924f74673fa00effc47cc373ed5aeaea260a1fa7b3c4fd4dc5ef1dd985514c", "048f8e82d6e76a505697388ee1f858d4fe925968d5c6a110feb4a2ccebfabb9a701f656f99ebf1385a5d09ed6953a406ff93e15436ca22b16222ace5e22fedfcdb"), + arrayOf("0417cd956903981a8a533d5eecb6c8a25406966fa61f5e5c14df4a0998600712d1d9815cce040deba70218bb38967cc63873beff15534d21f953e3f6e07d459ed7", "7ac101f2cb063daaea13ec5c4a4fa771017d6f6be921c5b081cec7c9b698f4ef", "043021ad146a5d29126197b5219bad4f83897e3da1153eb765812a5083824094350f8aab1d3c0abef079a95856b2ba71c24a2f2f379b1e745665c0ca3c1704e40d"), + arrayOf("04905be72cc75724ba1e291ee216c908496da4a6f3a2f8eedbe448210a94a5942df6711aec399deaa54799e83d213fd537db0a4475ca9e804b7eca40f6885ebd62", "2448d99a5fd502d9ced020ba39f0f557657c71de9eb765782e1ce0b662babe3f", "048c0262ccb7d9c91cae48b4772d1c9b4a0a3aa6a802e66cf94b774d1e51673f5fbbd2c0d489c9f46796c9b35a1bcab94a9e2a0468ca4f5106e920a578252268d6"), + arrayOf("04504e0167093ba23e46283322be113cc6c99084fa6990e7eb0d4dc57a943bf2011e1886a603f7346139eaaa19c65397fe8f91d348777f478a41466335e2bf75cb", "3611b1daf065952d81bc60d5695f7e335eaca8f2e7d46b98c918a5844ea66941", "045c7e59d54705d164f279fc56ef7510b53436b463bd8c4624cee76030be40944a12e014881270d12543b038602af6a8588a97a0ab91636ac04a4d73e881947c4c"), + arrayOf("04fd140f1a54a1448e1ad3b83f0ba6075b815a05b6df22f5abcd9cc77d74bca359dcedef2397d08e9850390a5493aec01132f15c411c578367641f4b97107de271", "c159be7fed614b97af8bb81a4975ae6a2ede4d12cb8e3d23dd0ba5a96f312a27", "044c72217766078968bb4a56324064cabf48ad7d1ed14634d9e2de6c584dd46b30bf2afac80aba30d74ed66c281f16f38abdf96b80dda6a2a1319392518c6e09a1"), + arrayOf("04d3756efa870a64de2dc21ba6b764f897f11ad7a50d5a315a1b4b36dc652870f7f241b85cbd9ed102c8041f71fd8b403d052dab9682a7b4d058ac96e115ae54e4", "a895449ea222ec9594aba6c0bb19f0085fc3349b208ac7b86352105bdff2d03", "04734a8c572f9eaa5f9adb4dc12d474ebb4c4ed360916ae442242b3d00acaccd57fe676053c183a632ebac15ce1822a425a5c5140ab8de29b3e0a28ee66172db9a"), + ) + + val jecPointBytes: List> = listOf( + arrayOf("04614f930b9766f5a6f2fcf006118e706f6e8aebb5169356906316a2285f5e87dc594986449b1510c5b877ae172f7105afec868c3a7b03e1645d6bd171a52433d8", "614f930b9766f5a6f2fcf006118e706f6e8aebb5169356906316a2285f5e87dc594986449b1510c5b877ae172f7105afec868c3a7b03e1645d6bd171a52433d8"), + arrayOf("04cdf7b22675ca384ef7acfa769b3fa61a507ab6717afccf15b75ab3092702fc16362d6160083b12695d927b3bcd713e062b3be0be8437babfbe2093e68136aec4", "cdf7b22675ca384ef7acfa769b3fa61a507ab6717afccf15b75ab3092702fc16362d6160083b12695d927b3bcd713e062b3be0be8437babfbe2093e68136aec4"), + arrayOf("04449a9d882c59c641deee390ad094c27a917f7c51f63df498a4d602c9f22cd9489307bbc3115bf7890d0ed44f0137ef6051979dda9aff6a077107e24dd229e45b", "449a9d882c59c641deee390ad094c27a917f7c51f63df498a4d602c9f22cd9489307bbc3115bf7890d0ed44f0137ef6051979dda9aff6a077107e24dd229e45b"), + arrayOf("0417cd956903981a8a533d5eecb6c8a25406966fa61f5e5c14df4a0998600712d1d9815cce040deba70218bb38967cc63873beff15534d21f953e3f6e07d459ed7", "17cd956903981a8a533d5eecb6c8a25406966fa61f5e5c14df4a0998600712d1d9815cce040deba70218bb38967cc63873beff15534d21f953e3f6e07d459ed7"), + arrayOf("04905be72cc75724ba1e291ee216c908496da4a6f3a2f8eedbe448210a94a5942df6711aec399deaa54799e83d213fd537db0a4475ca9e804b7eca40f6885ebd62", "905be72cc75724ba1e291ee216c908496da4a6f3a2f8eedbe448210a94a5942df6711aec399deaa54799e83d213fd537db0a4475ca9e804b7eca40f6885ebd62"), + arrayOf("04504e0167093ba23e46283322be113cc6c99084fa6990e7eb0d4dc57a943bf2011e1886a603f7346139eaaa19c65397fe8f91d348777f478a41466335e2bf75cb", "504e0167093ba23e46283322be113cc6c99084fa6990e7eb0d4dc57a943bf2011e1886a603f7346139eaaa19c65397fe8f91d348777f478a41466335e2bf75cb"), + arrayOf("04fd140f1a54a1448e1ad3b83f0ba6075b815a05b6df22f5abcd9cc77d74bca359dcedef2397d08e9850390a5493aec01132f15c411c578367641f4b97107de271", "fd140f1a54a1448e1ad3b83f0ba6075b815a05b6df22f5abcd9cc77d74bca359dcedef2397d08e9850390a5493aec01132f15c411c578367641f4b97107de271"), + arrayOf("04d3756efa870a64de2dc21ba6b764f897f11ad7a50d5a315a1b4b36dc652870f7f241b85cbd9ed102c8041f71fd8b403d052dab9682a7b4d058ac96e115ae54e4", "d3756efa870a64de2dc21ba6b764f897f11ad7a50d5a315a1b4b36dc652870f7f241b85cbd9ed102c8041f71fd8b403d052dab9682a7b4d058ac96e115ae54e4"), + ) + + val zeroKnowledgeHash: List> = listOf( + arrayOf("0466715325e5d2261ec5ead4b3a68d584ff859274debdc53108e387d33be0df91dc985e9a90d499847c2af4c6dc53daeb2412206e7a9544cae94bd259832c470ea", "046645a4b72841893b9317cb0135fddc80fb5ce366c586002f34024389f718b35e9470f11b4a7a13eee89be9a49f6a7c6aa01f3c66d094903741f42da8c38b925c", "04fd4211c8675661f97a5f7f41b512c019d480a3fea69b3de0b002cdb348cc603e49c991c0931961ff210eeaa4e966db2cc8828a1fe057332fc956d9caa6e80855", "636c69656e74", "8d58e1e302acfd7b0551808b61f2dcd479b836ced7e55c9bcb7e609b790a8dd9"), + arrayOf("04996fcad039acffada112ab1bb073ecc61677311cd37628d10be9fc404ebfc7421e7d1757fd9d392d71031401f57e05d098bcb9ad0f47cbeb4b66d33d6266f1e5", "04c5545df85adb89195d8de788c87009d57e516cf03504be2ae309e5379adf0905ece09135c096000c863684659f258959831be4838b83e0b0172408b9e54c652a", "04b6952723fe37fb574c0fe018eb3c9fbb3181b4d7633752edb809c1b10876cfa0cb77bb6fa57479443eebc039bcc8c1b146425e8b08cc1ef7fc6037ff1640da4d", "736572766572", "b631d11b9f65e7dd6cdac1fa2b66738483156ee51cc73acf5aeb140c9e5883f5"), + arrayOf("04f2fcc5666813c0d799391e9e2850ca63d50a6d8e9a06fcf4931590ae5e96b9311dcc10ad6771257a4ddace62d83b839236d4362a9fd76c0164081904fcb94cf4", "048122c884b4ed77cc733c7e8e7bc068e8d58b817728ccb73984367b288eade7c852cee6c060e2a45add6ba0b575637f3d213e37b9ec34b748f24674e84d069bb2", "04c6db92249d0c8e73abf57ee8d1774c019db937101fc4c48b749fe49be4206daefd9a0c7ec4e1000e670014d862f9de352dea79c28510577d167d4fd34cc48635", "", "cb402a475797dc88d2add451b50d78db07dc92f70bab460eca15062aba50be63"), + arrayOf("0435f7ff16efb0054ad01d8149d3e27ce09be4053f4095a00466cbe94fa113e8cb0430686ad148f7a36ea98cee53606fe40a4f925817f435ea67328c3004c8fd4d", "04fdbc359c57bca1c7c1a7972d88460c8d5b5b51d3d8a621ad13d6a9ab2e78a69b676f88e8420e369c0f75e3732f95f18aea622cfc4476e615142d768d97b0b2e9", "044ef094570a6c5ce7c320369220cc41e09e9778f1bf49ae39aca7c8a2864a7ff3b5ac2e2a380dfa20f21223fe6a59b40db28514ed6f802832bdb9c1db99d5ecf6", "010203", "fc8d9352907294cd89f4559d9c9e573357d5d3b0ddc2985e0d3ab0c349d24f9a"), + arrayOf("04cb3d6a5cd007a3eed6d09828282012149b672d074d4c00e0200623dda24e700973c1d791b5124bcf2266c47a723a88d6cc1765db182862fc80514a90dd342b4c", "044324babd5c717eda1050e348fde2093ec3159ba3767b46bd37c35ad9a12a9c8ba2c1f8b71548e110a808d8cd10f18e4eb5659ab80fee4a56d4bcdeea5ba8400f", "045bf307667813255400943df4402ab278e27d6685829705c59adcdc5949b901f1e535a160c53db6d6ec34c5fca171071c4221d482a3eb39dfb5e24ce1bb03a173", "636c69656e74", "56858cc0608a547ac8fcc2afe453cae8f6f3e9011501b2128cffb74f376eb85a"), + arrayOf("0461d14775ad9e0db1694d4efe20d3f20beeb6111a45dfc103967b70914dda35df7cbe17c9bd6d547cc3ce922d8a1043d3b1c2beb566c123da332425872f33be40", "04fc2a529a2ae8717472db234481882c4b3317ed47dc8c9460ca3d22d119fda681a5f0db32a88b65767119e451daccc2c4f28eef0cfa91d4f8b976ab2ea230cbc8", "046132664371156ee3f1c64a98e0dc6c7fef8c32bb23aeaa2787171176af3d9bf135cf6f0fa3e86d4e40fa26b6d1efc93599918fa15679598c9f340e4d9e6e9b33", "736572766572", "70df3579b601ca41de8fa32b6b6950ba47a7b617e99fd1404ae80ac8df363865"), + ) + + val zeroKnowledgeProof: List> = listOf( + arrayOf("046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", "04d3f9b7fc73aafaf1dc0eca0acccf427d1daedf192346994af57c8510cef05f797b6cd095994e091cadc3eb03c3195fbe2986b3d0576a8632a7a523eaf9e69144", "0449904ee56888438d745cd32a2561d19146dce23e1f859c9e26f118491319013e9682e2916a2054dec62fde2d10a0bb6ae086fe0335d1e1161fad8b7c4662164c", "b7a63cdeec1fcec26ef1900913cc91d772af0b889a1f8d37fa00fff488760761", "636c69656e74", "true", "false"), + arrayOf("046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", "043ffb60aae5eda0d56d15ff0ffc7dc46644d25af2214222a9a8d99a0619e13e41a47e655315be5f46c48d34639a88f43cd7f2fbf425f20fbb642f0a5102d9fbcc", "04d62a6afdd087d2b74d5efb1cb3dc00f416c9461a6b03a562e6563b4360016a1caccf07aa440f595bc6d5be335cdf30fae99457f350c6c3c9996221e00a2ef103", "84bd598f042256c3d468c57a36aa5baed0c065b0ee6d3eb89a2d13c22623e182", "636c69656e74", "true", "false"), + arrayOf("046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", "04b200b94e90de6c03051440967f107a3cca72ecdfc666e00ce4f454d338048f5fc05e3ccf82aa9e4867fcdb0a7283be32279ae228c989874a5ed4efd8f222e726", "04bb61ea8c31f390954f20a4f045d5e4e25568d2dad47f05e05f1e28517339ca7add939473dee3b895c138c511f0eec7580bdb732a5130de0000781d7194c2938e", "332ceb455a847f0f5bfdb3acd93c7883b3decd81d282e6f3ca979ae6bd03a878", "636c69656e74", "true", "false"), + arrayOf("046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", "04bc3856ca0cffe74044ed27a38d122c230252804f69005a930ecb83e57ad85a55f3fe1e12c675ebfd37897f733a7a496216f0b619544c9e8d4222cd5e7e198db9", "0487e8cb9d3b77e307b3f13225d1e4c319b933544d56e3ecf422313d2b643b8886019dd93d051c2c2a11f948e612709bb9edc61cfc7c04bccdb96691d8adabee6b", "e2a34a2ef082927085a28c98850d242e8c86c6593b2ce69926e84a073d71b743", "636c69656e74", "true", "false"), + ) + + val packet: List> = listOf( + arrayOf("1b8284bb994b05423159b85bb05adcfc8c963ef11e9c68f2addc6d4082b6c6e7", "04a1e7315e622808be0ca7d1a56fbc94abfbf68cd05cccbfe4a551ad6a56a5801e6a1cf58cc859c46bfb24f773dd47972ff9daa0146db64a79096c7b8950294362", "0499d4b30d87c34226529af124d14c05457c61471b99842d3a4a9bd34e646c372a63bd3ec34ca5d162c630a88de8904d8b14d692549db250728d255396d8eaf024", "a1e7315e622808be0ca7d1a56fbc94abfbf68cd05cccbfe4a551ad6a56a5801e6a1cf58cc859c46bfb24f773dd47972ff9daa0146db64a79096c7b895029436299d4b30d87c34226529af124d14c05457c61471b99842d3a4a9bd34e646c372a63bd3ec34ca5d162c630a88de8904d8b14d692549db250728d255396d8eaf0241b8284bb994b05423159b85bb05adcfc8c963ef11e9c68f2addc6d4082b6c6e7", "1b8284bb994b05423159b85bb05adcfc8c963ef11e9c68f2addc6d4082b6c6e7", "04a1e7315e622808be0ca7d1a56fbc94abfbf68cd05cccbfe4a551ad6a56a5801e6a1cf58cc859c46bfb24f773dd47972ff9daa0146db64a79096c7b8950294362", "0499d4b30d87c34226529af124d14c05457c61471b99842d3a4a9bd34e646c372a63bd3ec34ca5d162c630a88de8904d8b14d692549db250728d255396d8eaf024"), + arrayOf("11e0cda377d08b6bcb54ddce09333f54e721b0de226ca6ff38b7fb4239f25037", "04dfc90258647101fa45805b4c5935cf4544b3ed8e722494622195a03895f3c46ce4761bbb9e536ad40c95865d02b98af172b1ecbb9d8c170747dc3e68920df598", "040aea611985a088eb2f679cdfbc7c20163614b6737ab15de92e0d03e5d52137f18c645e1799c66d6d0894116a0ce75c5e37e4d43acb68e6338caa746e1630d49d", "dfc90258647101fa45805b4c5935cf4544b3ed8e722494622195a03895f3c46ce4761bbb9e536ad40c95865d02b98af172b1ecbb9d8c170747dc3e68920df5980aea611985a088eb2f679cdfbc7c20163614b6737ab15de92e0d03e5d52137f18c645e1799c66d6d0894116a0ce75c5e37e4d43acb68e6338caa746e1630d49d11e0cda377d08b6bcb54ddce09333f54e721b0de226ca6ff38b7fb4239f25037", "11e0cda377d08b6bcb54ddce09333f54e721b0de226ca6ff38b7fb4239f25037", "04dfc90258647101fa45805b4c5935cf4544b3ed8e722494622195a03895f3c46ce4761bbb9e536ad40c95865d02b98af172b1ecbb9d8c170747dc3e68920df598", "040aea611985a088eb2f679cdfbc7c20163614b6737ab15de92e0d03e5d52137f18c645e1799c66d6d0894116a0ce75c5e37e4d43acb68e6338caa746e1630d49d"), + arrayOf("73d448106d47cf3e1e1f86af80ab91bee8a28c4abc6a48c853b13bee2c851558", "04255a283703c2fcba9a03139aa432b1970f706a38a5225fda9ac7438fd42cd885996e120b1b6960f8ca554b7ec9de08ad68e0ad670347ac17b9ae8784fb1b1480", "04d6d8604caa77fd2fb2c68b5890c7331e0c69d6530b6ba7b88708cf8ebbbb91c4122909a4574680ebbda7c711da7c6d48c3c2b8e89c373cb72ecda9e846c88fa5", "255a283703c2fcba9a03139aa432b1970f706a38a5225fda9ac7438fd42cd885996e120b1b6960f8ca554b7ec9de08ad68e0ad670347ac17b9ae8784fb1b1480d6d8604caa77fd2fb2c68b5890c7331e0c69d6530b6ba7b88708cf8ebbbb91c4122909a4574680ebbda7c711da7c6d48c3c2b8e89c373cb72ecda9e846c88fa573d448106d47cf3e1e1f86af80ab91bee8a28c4abc6a48c853b13bee2c851558", "73d448106d47cf3e1e1f86af80ab91bee8a28c4abc6a48c853b13bee2c851558", "04255a283703c2fcba9a03139aa432b1970f706a38a5225fda9ac7438fd42cd885996e120b1b6960f8ca554b7ec9de08ad68e0ad670347ac17b9ae8784fb1b1480", "04d6d8604caa77fd2fb2c68b5890c7331e0c69d6530b6ba7b88708cf8ebbbb91c4122909a4574680ebbda7c711da7c6d48c3c2b8e89c373cb72ecda9e846c88fa5"), + arrayOf("e0ae56bbf3ed9032ae8a6c1932ae202e2b7918648bd8438aae18e9c4122016df", "04bcefdf39fbe7e5032be7dbfa284527b61733ae032b4ab98df7c77f511adca04d3dbe5566e5ed37d924c5880c77674a6c0528111cf1fb32e7f740276618ea4587", "048be6d681e5514c07578a54713bd1eae7a2a934838ac7cd0de9f813001365d7cf4f602be4d5bd90cb97d0a4878d1d2ffab275211e33f77736b0c859fbdca823dc", "bcefdf39fbe7e5032be7dbfa284527b61733ae032b4ab98df7c77f511adca04d3dbe5566e5ed37d924c5880c77674a6c0528111cf1fb32e7f740276618ea45878be6d681e5514c07578a54713bd1eae7a2a934838ac7cd0de9f813001365d7cf4f602be4d5bd90cb97d0a4878d1d2ffab275211e33f77736b0c859fbdca823dce0ae56bbf3ed9032ae8a6c1932ae202e2b7918648bd8438aae18e9c4122016df", "e0ae56bbf3ed9032ae8a6c1932ae202e2b7918648bd8438aae18e9c4122016df", "04bcefdf39fbe7e5032be7dbfa284527b61733ae032b4ab98df7c77f511adca04d3dbe5566e5ed37d924c5880c77674a6c0528111cf1fb32e7f740276618ea4587", "048be6d681e5514c07578a54713bd1eae7a2a934838ac7cd0de9f813001365d7cf4f602be4d5bd90cb97d0a4878d1d2ffab275211e33f77736b0c859fbdca823dc"), + arrayOf("9f36f260726adb52e8e5750644748e9a0e5e56ef05e98b26ceefd370414312e", "0416b4486d7a51e6e99041258c6c4fa7a6f6104eb3a905e8be85a80c3867598166dc917fb1a9b3a1af7eb00ab02f60da5d8784fbc5b5002b1cc5c5897796713bec", "0415f5ad6c192883ba691cb1eb8160357eb89e87a8febe18da93a2c2aa4e0e9e0a8bc5c909cfc20540fa03acef5f21e899b9381f43de4167916b7f9449b3be4dc2", "16b4486d7a51e6e99041258c6c4fa7a6f6104eb3a905e8be85a80c3867598166dc917fb1a9b3a1af7eb00ab02f60da5d8784fbc5b5002b1cc5c5897796713bec15f5ad6c192883ba691cb1eb8160357eb89e87a8febe18da93a2c2aa4e0e9e0a8bc5c909cfc20540fa03acef5f21e899b9381f43de4167916b7f9449b3be4dc209f36f260726adb52e8e5750644748e9a0e5e56ef05e98b26ceefd370414312e", "9f36f260726adb52e8e5750644748e9a0e5e56ef05e98b26ceefd370414312e", "0416b4486d7a51e6e99041258c6c4fa7a6f6104eb3a905e8be85a80c3867598166dc917fb1a9b3a1af7eb00ab02f60da5d8784fbc5b5002b1cc5c5897796713bec", "0415f5ad6c192883ba691cb1eb8160357eb89e87a8febe18da93a2c2aa4e0e9e0a8bc5c909cfc20540fa03acef5f21e899b9381f43de4167916b7f9449b3be4dc2"), + arrayOf("34142507a94be01a072cbbccfe3686fe0cfe75ff92bd9cc2a4c6391eff7b5b8f", "040f39b989a6f5f6f084eba80ba743712077e8bcf5578f4e37409cef1e5d0d11c5b79de5a5670c9776b3162bc7a37c9ed56c9ad33700092f889a4fc15db9245639", "04284463ec20befce1477bad4ad1d2e31d59c409e6a5e53b94b3c94d4faf6d307aadcf81e1a186bddd38347ad2ae87ad846d9354e702cc1d6d6ee838a11d6b5f50", "0f39b989a6f5f6f084eba80ba743712077e8bcf5578f4e37409cef1e5d0d11c5b79de5a5670c9776b3162bc7a37c9ed56c9ad33700092f889a4fc15db9245639284463ec20befce1477bad4ad1d2e31d59c409e6a5e53b94b3c94d4faf6d307aadcf81e1a186bddd38347ad2ae87ad846d9354e702cc1d6d6ee838a11d6b5f5034142507a94be01a072cbbccfe3686fe0cfe75ff92bd9cc2a4c6391eff7b5b8faabbccdd", "34142507a94be01a072cbbccfe3686fe0cfe75ff92bd9cc2a4c6391eff7b5b8f", "040f39b989a6f5f6f084eba80ba743712077e8bcf5578f4e37409cef1e5d0d11c5b79de5a5670c9776b3162bc7a37c9ed56c9ad33700092f889a4fc15db9245639", "04284463ec20befce1477bad4ad1d2e31d59c409e6a5e53b94b3c94d4faf6d307aadcf81e1a186bddd38347ad2ae87ad846d9354e702cc1d6d6ee838a11d6b5f50"), + ) + + const val packetShortInputIsNull = true + + val txMessages: List> = listOf( + arrayOf("AuthChallengeTx", "0102030405060708", "040102030405060708"), + arrayOf("SignChallengeTx", "000102030405060708090a0b0c0d0e0f", "0c000102030405060708090a0b0c0d0e0f"), + ) + + val authStatusRx: List> = listOf( + arrayOf("050101", "1", "1", "true", "true", "false"), + arrayOf("050001", "0", "1", "false", "true", "false"), + arrayOf("050103", "1", "3", "true", "false", "true"), + arrayOf("050100", "1", "0", "true", "false", "false"), + arrayOf("0501", "0", "0", "false", "false", "false"), + arrayOf("0401010000", "0", "0", "false", "false", "false"), + arrayOf("05020100", "2", "1", "false", "true", "false"), + ) + + val certInfoRx: List> = listOf( + arrayOf("0b0000ea0100", "0", "-1", "-1", "false"), + arrayOf("0b000000000000", "0", "0", "0", "false"), + arrayOf("0b00010a000000", "0", "1", "10", "true"), + arrayOf("0b01000a000000", "1", "0", "10", "false"), + arrayOf("0b0000ea01", "0", "-1", "-1", "false"), + arrayOf("0c0000ea010000", "0", "-1", "-1", "false"), + ) + + val authRequestTx2: List> = listOf( + arrayOf("false", "", "0011223344556677", "02001122334455667702"), + arrayOf("true", "", "0011223344556677", "02001122334455667701"), + arrayOf("false", "010203", "0011223344556677", "02001122334455667705"), + arrayOf("true", "0102fe", "0011223344556677", "020011223344556677ff"), + arrayOf("false", "0102", "0011223344556677", "02001122334455667702"), + ) + + const val partC = "308187020100301306072a8648ce3d020106082a8648ce3d030107046d306b0201010420007cfbd596f6e74477b8c0e9f6f7a174275e101ef6bf7d18caf01181d127b579a144034200045118c35e9e41e7e0654fee801c52a9c5dfc510ef09597d5cca8461e4af9c666714834f2bc903f16fabfc45755b0183f1a09745cdffcb4e2f799e50bed9a6b58c" + const val partCScalar = "7cfbd596f6e74477b8c0e9f6f7a174275e101ef6bf7d18caf01181d127b579" + const val partCPublic = "045118c35e9e41e7e0654fee801c52a9c5dfc510ef09597d5cca8461e4af9c666714834f2bc903f16fabfc45755b0183f1a09745cdffcb4e2f799e50bed9a6b58c" + + val ecdsaSign: List> = listOf( + arrayOf("67066dbb197a825506655509ff7d2e31", "8e10e0314e2b72aee83b40b4e086c6051c1933400aa92c7002f4f2492e5820874fd0da7fb74b046339b567b552c6412ac0cf1b251a4e5fbdb7984821f3c070cc", "false", "ddac3f4b2c33b6cbce5e00454cce9f1bef24c3c9027426fea1f4b1088f3f512f", "604663dbda1575511f041fc3e7479373797a16b7e27a0f23eb9dcc6b7d06eee3", "true"), + arrayOf("a5a23a39f7be0bdb64e17b61ec39a412", "85c9733836e6eb6ab676eb5358ef3d8797785e6c72c3a49f85b8cc6a8b1c0799c1c0b08cd3445df89bc1dac14b7d7ede4af6ebeb811813d9d97f51617f820097", "false", "89f3c316fc8bda316b29e6c7f1037d131e113c08dd099905e7147db571487748", "5a832524643f3f64b4aed66064aa34174e7b251db60557db7b5d18215f2ed3e1", "true"), + arrayOf("8b1fe9c8b6baadb38d91e5952ecba48d", "edbee6647d363d58c9da24157f5f675eb890a2dd33b40067f3a73b47c0a977dc1cc054e579c42b1367af2dd87e55e86ece03a4a5146bce9b14af8a7bbadf9350", "false", "47ae539b98426c068fd8d2fc807dc5e36538e230efd2a720e117a2b2a6226b82", "330e37e557c2952ac19c06a0460bd74492053af0416b9eba27870765a6186099", "true"), + arrayOf("73f54eddd45c0b826acfcc913cf5788e", "96ec3033e432a90a27b9a673ba2fd8dde75d227533b4bf04e2a07c829752a753a74263a4a04b360ea5e2321006ad4b2d8ca0eff88598d8d89e1965d23a7a7c16", "false", "9f38b57266cd744329d13fc7a3ed03752d2c1552954808cfadb7f9039d96128a", "8070d4f25d4f1a2b9cc0501041a91ac8792d4b1128251550d373fa0ac4b6989", "true"), + arrayOf("78b8b9fe9c05157bace3d3fe3390ac21", "60b3b338fe1c397d8f01b8fa8e71343af9deff5601d44873ce3c777ead5727350953742e75611e3e69202af0420c35f8f515e253cb169f565eaf7d7c79a2d12f", "false", "e78da86f12f9d075b11341b0160fac0ea454d4df16f28fbd8e125d7c101d8dc6", "a8be82b10396af8ac109ee3d563359d1f2c2a9d4838fe18bac59a3c7507da677", "true"), + arrayOf("498ba3af63e2e47fb8666d49b2088b14", "b061301e2b1695fddfe07ffa584b9a858a74203087b999b4a8ac1552240f94024dffa51ff1b3daa0cf57fc01136350ef33b23472b09f68a5862ee64820719adf", "false", "dfaeb590646b3180dba1a46a7ff55cfdeb0f0ba0e71a4277be10bfbf9010b899", "fce9fcad9b81d1e6960cc1867227dfdede7af23baf0bcb903dbbfa117be7f345", "true"), + ) + + val ecdsaVerify: List> = listOf( + arrayOf("406bcc3a0d4a4e13de3cb5bd047a09c8", "45ebaada4d23159a7cf8be3c1f63edf1dfb5f81b8e7f6eefc5b07ec225a7a3674ebc07662f8db133cc763b296c07d9ddd03bd74a2cf5c1a0358ff17eaffb971b", "45ebaada4d22159a7cf8be3c1f63edf1dfb5f81b8e7f6eefc5b07ec225a7a3674ebc07662f8db133cc763b296c07d9ddd03bd74a2cf5c1a0358ff17eaffb971b"), + arrayOf("b2a99325d6dd671ed1a1607c84c6354c", "4e17e0612af12e8ec2b023ecb2c890bf6797f600b2b534c49d36fb4b643c9e54ecab0a9f23e1e2f2ea05da988e1cfb63d32187ca3abae581af7f3d667679fba5", "4e17e0612af02e8ec2b023ecb2c890bf6797f600b2b534c49d36fb4b643c9e54ecab0a9f23e1e2f2ea05da988e1cfb63d32187ca3abae581af7f3d667679fba5"), + arrayOf("88265fe24f7290fd53f7deb63d52d419", "3d0bebdfd5d68d6ee89d1178f65ce49cb652de8009b03e033a1cf237ca66ba390c01cc65620b01b28f259a777715f7c3ea51d54de84c6b2db48dcf560f3e132c", "3d0bebdfd5d78d6ee89d1178f65ce49cb652de8009b03e033a1cf237ca66ba390c01cc65620b01b28f259a777715f7c3ea51d54de84c6b2db48dcf560f3e132c"), + ) + + val challenger: List> = listOf( + arrayOf("0e20a3d5a504eb182f4b2c0dd0434c3e0aac", "7b59b0910e6500b6496fe6230f29f4358a983c5f578c0ee94970c10ef1258da461260cb78b5efbf415294928157e3a5d13dcaf5a8638aeef4ed0d3eaf389fe04"), + arrayOf("29404ec86cc8715a9a6f9c15102ece610b58", "7d1af27d45906a1de049f3e51265e475074013f6114592ea6127aac9c731e6b20ce34cac64422d0b062c04bd19495dc408bb0a3fb6c72161f1a58400ca017ed9"), + arrayOf("bf879f76155111ad155f36c56939a0034173", "507370e4e0b3811bbe75121e799c222efc848261f27a12cbe69ca9577f330529945df081216a4aa7ca29fc702f6b86c6cd0e542337182b4592755b9727fe5bb6"), + arrayOf("7fb6163241ba7f1c8859492e6131f082b802", "73751f5a3153201e1e3a2cba870355b5cf263468e6bacaaa600660cc055877c05032051b6d334934e6d90e3bd3eb90f3cac60c3b93d5eff63120f66dc99da5d7"), + ) + + val bigMod: List> = listOf( + arrayOf("0", "0", "0"), + arrayOf("1", "1", "1"), + arrayOf("2", "2", "2"), + arrayOf("ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "4319055358e8617b0c46353d039cdaad"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550"), + arrayOf("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "0", "4319055358e8617b0c46353d039cdaae"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "0"), + arrayOf("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "fffffffeffffffffffffffffffffffff000000000000000000000000", "ffffffff00000000000000004319055258e8617b0c46353d039cdaae"), + arrayOf("8000000000000000000000000000000000000000000000000000000000000000", "8000000000000000000000000000000000000000000000000000000000000000", "8000000000000000000000000000000000000000000000000000000000000000"), + arrayOf("265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7d", "265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7d", "265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7d"), + arrayOf("775ba67c7e8471fe55848450f5988a8d5df54ea6bb5231f99f3ea91eb430e144", "775ba67c7e8471fe55848450f5988a8d5df54ea6bb5231f99f3ea91eb430e144", "775ba67c7e8471fe55848450f5988a8d5df54ea6bb5231f99f3ea91eb430e144"), + arrayOf("e53d6ac2a9d065ccefa28f414fd1d3ebae185e8f7df8582a9c9187935356ffe", "e53d6ac2a9d065ccefa28f414fd1d3ebae185e8f7df8582a9c9187935356ffe", "e53d6ac2a9d065ccefa28f414fd1d3ebae185e8f7df8582a9c9187935356ffe"), + arrayOf("35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180"), + arrayOf("a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44", "a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44", "a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44"), + arrayOf("17b3c7e07b02fc6678f1828809b5c6742db74af8f604f55d28dbfa5cfde4ba35", "17b3c7e07b02fc6678f1828809b5c6742db74af8f604f55d28dbfa5cfde4ba35", "17b3c7e07b02fc6678f1828809b5c6742db74af8f604f55d28dbfa5cfde4ba35"), + arrayOf("a73988095f96aaef9645f3edfc51e3d29f745fa984ae4bad8371b3f6973c5f1b", "a73988095f96aaef9645f3edfc51e3d29f745fa984ae4bad8371b3f6973c5f1b", "a73988095f96aaef9645f3edfc51e3d29f745fa984ae4bad8371b3f6973c5f1b"), + arrayOf("72fff0cd0c00d9516aaaaeb7c1e5f7ebfa13510b982729a8d2b0d655914c2fae", "72fff0cd0c00d9516aaaaeb7c1e5f7ebfa13510b982729a8d2b0d655914c2fae", "72fff0cd0c00d9516aaaaeb7c1e5f7ebfa13510b982729a8d2b0d655914c2fae"), + arrayOf("273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449", "273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449", "273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449"), + arrayOf("da4b4f5d2b430d5e03724ba8f9a519a57d77e82b7da88ce33dd8dcc8e4848582", "da4b4f5d2b430d5e03724ba8f9a519a57d77e82b7da88ce33dd8dcc8e4848582", "da4b4f5d2b430d5e03724ba8f9a519a57d77e82b7da88ce33dd8dcc8e4848582"), + arrayOf("ed3415970860d9205fcb75c353b4b2922d48d5c73f569d042441d999491f7d6e", "ed3415970860d9205fcb75c353b4b2922d48d5c73f569d042441d999491f7d6e", "ed3415970860d9205fcb75c353b4b2922d48d5c73f569d042441d999491f7d6e"), + arrayOf("2547d817889aa379a04fd2734ba60da5d988dead67f0f6ae9451cecf220f8f3f", "2547d817889aa379a04fd2734ba60da5d988dead67f0f6ae9451cecf220f8f3f", "2547d817889aa379a04fd2734ba60da5d988dead67f0f6ae9451cecf220f8f3f"), + arrayOf("dd53dd21dbcef5e7047c043bdfacdbf6080093b808729c1a07b908be1e040ff2", "dd53dd21dbcef5e7047c043bdfacdbf6080093b808729c1a07b908be1e040ff2", "dd53dd21dbcef5e7047c043bdfacdbf6080093b808729c1a07b908be1e040ff2"), + arrayOf("68ffcec715e32b33dddb30ba8fefd65175027d10571a5fe54682106bb2081430", "68ffcec715e32b33dddb30ba8fefd65175027d10571a5fe54682106bb2081430", "68ffcec715e32b33dddb30ba8fefd65175027d10571a5fe54682106bb2081430"), + arrayOf("88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1ef2a9f13493969739", "88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1ef2a9f13493969739", "88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1ef2a9f13493969739"), + arrayOf("f731da8f03181b5a981010f9de72a0faf401b58e8e032daaff0491543dbbb294", "f731da8f03181b5a981010f9de72a0faf401b58e8e032daaff0491543dbbb294", "f731da8f03181b5a981010f9de72a0faf401b58e8e032daaff0491543dbbb294"), + arrayOf("e26e2123d3a28d3402759554935338a80026b3c316cc837b337747576f4cab85", "e26e2123d3a28d3402759554935338a80026b3c316cc837b337747576f4cab85", "e26e2123d3a28d3402759554935338a80026b3c316cc837b337747576f4cab85"), + arrayOf("689b4e34c2624fb7ef186f82919987ae3c58be508d5bee6bac793d93ad2cc3d2", "689b4e34c2624fb7ef186f82919987ae3c58be508d5bee6bac793d93ad2cc3d2", "689b4e34c2624fb7ef186f82919987ae3c58be508d5bee6bac793d93ad2cc3d2"), + arrayOf("1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23"), + arrayOf("9047ad8b042bb82e3c21928f42d52a9b73d92a8414b46f3e7a550f1c2aaf3e63", "9047ad8b042bb82e3c21928f42d52a9b73d92a8414b46f3e7a550f1c2aaf3e63", "9047ad8b042bb82e3c21928f42d52a9b73d92a8414b46f3e7a550f1c2aaf3e63"), + arrayOf("b698d9359320bf01c5a9e27f2b73b3c906859b95e59909062a264e66c59ea0dd", "b698d9359320bf01c5a9e27f2b73b3c906859b95e59909062a264e66c59ea0dd", "b698d9359320bf01c5a9e27f2b73b3c906859b95e59909062a264e66c59ea0dd"), + arrayOf("83e1554bb92622db1f27452dc92ffc6bfcac6ddf2691392dd6b2ab0d1e71ab8a", "83e1554bb92622db1f27452dc92ffc6bfcac6ddf2691392dd6b2ab0d1e71ab8a", "83e1554bb92622db1f27452dc92ffc6bfcac6ddf2691392dd6b2ab0d1e71ab8a"), + arrayOf("5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca"), + arrayOf("98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23"), + arrayOf("41aa680a327f06d357780366e0ad1404248c7ce7e2b4530540951dc661e9ff5", "41aa680a327f06d357780366e0ad1404248c7ce7e2b4530540951dc661e9ff5", "41aa680a327f06d357780366e0ad1404248c7ce7e2b4530540951dc661e9ff5"), + arrayOf("6187f66c8377439657180f12fec15e26db6801012b041f662c76fdbd4e1ad300", "6187f66c8377439657180f12fec15e26db6801012b041f662c76fdbd4e1ad300", "6187f66c8377439657180f12fec15e26db6801012b041f662c76fdbd4e1ad300"), + arrayOf("e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772"), + arrayOf("b6d523b5ba4f0ba9266556499e1695743b10b98460edd46d409b0ddb9bbbdabb", "b6d523b5ba4f0ba9266556499e1695743b10b98460edd46d409b0ddb9bbbdabb", "b6d523b5ba4f0ba9266556499e1695743b10b98460edd46d409b0ddb9bbbdabb"), + arrayOf("72af80d38cfbd4003bce3b66231c24b4db4eae70e9749eb5183832d19b32d2dd", "72af80d38cfbd4003bce3b66231c24b4db4eae70e9749eb5183832d19b32d2dd", "72af80d38cfbd4003bce3b66231c24b4db4eae70e9749eb5183832d19b32d2dd"), + arrayOf("aa36d620a88189977e12600bf8e3444402284f72a321be0c1660e91e833060e5", "aa36d620a88189977e12600bf8e3444402284f72a321be0c1660e91e833060e5", "aa36d620a88189977e12600bf8e3444402284f72a321be0c1660e91e833060e5"), + arrayOf("63386867c5d43c991677d0f6e02c2d7c5f705c64a8e51e761c21958f4c07a35a", "63386867c5d43c991677d0f6e02c2d7c5f705c64a8e51e761c21958f4c07a35a", "63386867c5d43c991677d0f6e02c2d7c5f705c64a8e51e761c21958f4c07a35a"), + arrayOf("932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4", "932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4", "932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4"), + arrayOf("aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28d", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28d", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28d"), + arrayOf("68d3853af55433e7d4f1ce47fadc1c699ba352c977ad9dbfd60f4260780ca6e", "68d3853af55433e7d4f1ce47fadc1c699ba352c977ad9dbfd60f4260780ca6e", "68d3853af55433e7d4f1ce47fadc1c699ba352c977ad9dbfd60f4260780ca6e"), + arrayOf("7df7219c51c1eab2ef9fa93a39c0428430c42d761cbf883cea28d9b4c68ca22d", "7df7219c51c1eab2ef9fa93a39c0428430c42d761cbf883cea28d9b4c68ca22d", "7df7219c51c1eab2ef9fa93a39c0428430c42d761cbf883cea28d9b4c68ca22d"), + arrayOf("d83e8780ea6c14e39e4a06759d082f2e730e34598a0448282806acc8b4762920", "d83e8780ea6c14e39e4a06759d082f2e730e34598a0448282806acc8b4762920", "d83e8780ea6c14e39e4a06759d082f2e730e34598a0448282806acc8b4762920"), + arrayOf("524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818", "524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818", "524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818"), + arrayOf("1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a", "1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a", "1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a"), + arrayOf("dd1d7d870b39e98121d4ccd07a26c795c33c8d3af51f8ac356d6c7b288926819", "dd1d7d870b39e98121d4ccd07a26c795c33c8d3af51f8ac356d6c7b288926819", "dd1d7d870b39e98121d4ccd07a26c795c33c8d3af51f8ac356d6c7b288926819"), + arrayOf("2b79cd9d840d1eee32b037dccf7655ea3d225bbf66913ff10c009d18f423ed93", "2b79cd9d840d1eee32b037dccf7655ea3d225bbf66913ff10c009d18f423ed93", "2b79cd9d840d1eee32b037dccf7655ea3d225bbf66913ff10c009d18f423ed93"), + arrayOf("1313f664abc386b0dc215391c78737046a3af6db63c4ef5811e0112483ef6bc19669e5e485113742a0dd9832532aab79b69e726a12d70ae9600ddf9018d0daeb", "e1ecc409f4d58ecaf5bb5ce8d09a46da4d60ae7145de20757332d860f4f94fae", "73321f582dd4bc84ffb5c8fa428bab329fa08838f2a8c662b790c4617380fa4b"), + arrayOf("293e13dd799d3e5b94caf18169b0270340eff9e83dfa200ac9665452dbad9102341052c2d426e926e2406afa8189439b5af5299fd2a12c5c71b98289b6629d53", "e12ece68331d820a964c49ef0bc3ea276ae63c519e50294d7c38c29a26e31e0", "be7a5c16639586d3fd322ee8d65c1611938483f7bd3c25d86ae4a43944026712"), + arrayOf("946765c6463eab334798bfbb19ef00560b16b5326445c2b34db783afd9aeda711aef266f638ebd919506a1eb32a1532f8d94ae83a8b047b8ab3d5adb363dcb72", "e0effa3e7f4bec51d5c065a889f23821636b1566f5cdeee9210cd033aac7091d", "4d9c6713457f4ee02f009f1c8ab9e35db112e7a30d126a08d634425051878dbb"), + arrayOf("a5f447224b4a83131cebd31d0b2f178cfa42c8cf9e394c6aaeb24c005b8565b9d37e06163a743ba95bcfabc7d66c1bff34d2a0ad584a005be089d1d42ede986", "f604941467af0749839b48a102500dbfaac763bb3e29b7843141bb55fcb6e138", "ce5de61088fb73be5eda723ceb8d94bf63ee240de8810bf9e7ce7e5103d341c"), + arrayOf("7f4b9f3562b3e6bbcff868f1c61a76f9d11cd3ed5ede19ed2dbb1be22a03a610511aede245ffd45c0122d877bd462e8b73a6a2e1da7112d8948e9f2ac2bc91ca", "32f3a3cee4ec6df8b5cc292dbf869f4e9b034078587411cfa9156f1d5097b929", "e91e8f2edd5879618b1ae293f1541b22a24ba566e9d6189c70ace26e5cd78e94"), + arrayOf("28fb800693a61e59dfbd1de97586244297da01c5341719a0624a8ca250cefe1a0c176e18b9617d7634f76bb88ab7c5a730264c9d78ad68a75b181f82df41952c", "b6a48eb4f2ee6bbe78c848e03282c2164e8eabd3a83fc7c2df94e5391197bd9d", "4526f893e6f8764a3c372fcb3f4a9be9308c022ca7ba1ab3a32549f5b639e899"), + arrayOf("7a3348c387beed5a5dac51519625be32e56566545a5b0c2b16fbd08fc0ebb639e34c27beb1e8060bcccd3d97bdc6cfb691a85197b05f1b308094211604ef2c60", "df3f3640c3502a29d2169133bbd2ff5e94501c699081063ffc26b82e7be04ff7", "42c0cca0472ba30ea7b72985e110df5cb29fb2df6217e5b5044b84442f838d4"), + arrayOf("2b0194f84f025333860ca0152288831dc1c1634af4716ee1573c84b4025251562acaa6fe5d0c2ac6a6d800396faa07e239ac0f54c3b270bdb066694fd7a2268f", "4f59c1decc94185cc5c4a996c428ade603bc113879d4baa8d97b518677d822e8", "316da2e47aa971ee0aff073a70c3fb54598f0164066cbd84a36909e9a959c4ff"), + arrayOf("2f08e43a3c5fd165d8afaada522ecd026fbc67f2602cee85725a9e28e1ab0fd778dc9e222fb3e188debbbe41fa50b61b0ea3c36a32e3017ed9377d5644381937", "ecda8c53c78f1b0967fa4484b9e5ea8be81b45f3beb3f77c1577dc87c1431602", "fc9db8cc657b54d948cfa476007614322f9a8975b1fe31543a1f750757db1a98"), + arrayOf("bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f99f60740bd841e333d35c56a8f6f090da3642af38bd4fa44326c643ee71169cfa", "d133d0d6a39d7af2b66e90cbfd9906d658aa1b7fc9b76de213249829c77b2bce", "4fb9b684cc5ba000c1f3d5ff75b861512d63f1022d6b904eef54d3baef48f72e"), + arrayOf("4326a06b09f900ef", "4326a06b09f900ef", "4326a06b09f900ef"), + arrayOf("2894ad2bc0573646", "2894ad2bc0573646", "2894ad2bc0573646"), + arrayOf("979f1c64776574e0", "979f1c64776574e0", "979f1c64776574e0"), + arrayOf("a890fc4ad7cabd1a", "a890fc4ad7cabd1a", "a890fc4ad7cabd1a"), + arrayOf("b71201ae48ab3a40", "b71201ae48ab3a40", "b71201ae48ab3a40"), + arrayOf("20b24ea73c995bca", "20b24ea73c995bca", "20b24ea73c995bca"), + ) + + val bigArith: List> = listOf( + arrayOf("5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "5ce996c4b321ab4c1e2dfab3010ae970726664d58c0796a75d6d7248f6d068c51019b28b62d7b0edfee518b9f7e1955dac16da952fcb414745cf1d43f0831936", "0", "89624659dffa04b01fe7172145aa254d00f30ce54f69d2eb4d890b856731718b", "15ce996c4100b4211d14fa5fec24f4d5e63660c35d034beb8ba30e2bc0f7ce6c9", "5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "5ce996c5100b4210d14fa5fec24f4d5e204d06e1774c5d3dadeaad7f0be00c1c"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "0", "0", "0", "0", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "0"), + arrayOf("a890fc4ad7cabd1a", "ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "a890fc4a2f39c0cfd0c63f30d7cabd1a00000000a890fc4ad7cabd19fffffffeaede076a506a85cc", "ffffffff00000001000000000000000000000000ffffffff576f03b5283542e5", "2c2e6bb1f0433f13854eac6a7f5ccf9950868b4b02e1ee92", "ffffffff0000000100000000000000000000000100000000a890fc4ad7cabd18", "a890fc4ad7cabd19", "a890fc4ad7cabd1b", "ffffffff00000000ffffffffffffffff79cdf55a4e2f3d0a900491d0d09107be"), + arrayOf("946765c6463eab334798bfbb19ef00560b16b5326445c2b34db783afd9aeda711aef266f638ebd919506a1eb32a1532f8d94ae83a8b047b8ab3d5adb363dcb72", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28d", "62dc6302aa577b6b7986f264c518a1bc815006f7d72f44f1c3a712c7d3a316648ee235205fe9a19fcb1bee5f2299207a04dded1b9bf011a352abaadf607a4fc1823e9e1385d11c58e3f39e15fc2c365288fc3bcfd7c12c926add0188a69891ca", "a05b3f1070831d63a16209978ccd57bc03dcb83e3e6e4548b2cf9921f13feedf", "40600ec0be548308820887764f0433066b022372a83f2d4ecc98a40075da7127", "946765c6463eab334798bfbb19ef00560b16b5326445c2b34db783afd9aeda71c578ad2539d22f98533a96e74750742387bfde41d6bf381889db568de2c49dff", "8b7980f5558f5e5793f45aa49ea159155d96452423dcdf48ffaacbe6574ddbab", "36667388a9087a4b178c70ac7543172d693fe5a8c7befe89426ed480fe403690", "a312e05c6f3bdcda70ccaa20760ac26973ceb292861b182deb501160a163e07f"), + arrayOf("4326a06b09f900ef", "88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1ef2a9f13493969739", "23d992b71b32eb216def61296a137cc9680beb1d31c255a21ce763a556e61fd12de6ddb2e1082e37", "89224c4a2b06fef1680beb1d0de8c2eadddae5cd56e61fd151c0706a2014ac0f", "89224c4a2b06fef171715d814329aaf9ff0b4e2bf51eab8ea9117a35d55c24df", "88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1f35d0919f9d8f9828", "88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1f35d0919f9d8f9828", "77543ebe5160321eeec83ec11ea7eec1727a95fed0b2d2e1507caf36766269b5", "77543ebe5160321eeec83ec11ea7eec12f6190ab77ca7166443679f972c58f07"), + arrayOf("2b0194f84f025333860ca0152288831dc1c1634af4716ee1573c84b4025251562acaa6fe5d0c2ac6a6d800396faa07e239ac0f54c3b270bdb066694fd7a2268f", "7a3348c387beed5a5dac51519625be32e56566545a5b0c2b16fbd08fc0ebb639e34c27beb1e8060bcccd3d97bdc6cfb691a85197b05f1b308094211604ef2c60", "14875e884e0711151e7b3aa2f979d050dfa15d84b694366e606ee034a334d3c5e8a3022e2f06ed3892c3f62aadaaad92bebd7d7dc0690e2a0cf45ee95b19cc82317b25880f8eec86e38580aa89b4a6f052d547fb46a8fcc928d43c90b3d05d918d4d8a24da6f52d0801c36c6bc2bc27a52f4ca6b98078f338afdcf46f6f009a0", "d612652875e4c7b9b29a6a362943bcaa25c1dee52a55c35d724a575e2a8cd9d9", "a2ee88edc0d7c7e69e0f7f22c04064502f25561cfb84e4be8c2decbb7fc0feb1", "a534ddbbd6c1408de3b8f166b8ae4150a726c99f4ecc7b0c6e385543c33e07900e16cebd0ef430d273a53dd12d70d798cb5460ec74118bee30fa8a65dc9152ef", "2e98f8208fe4428597db3aca7ffbad44980c2da10a55c0e8d5a209b4f3b872e0", "701a8b9d0943ee33f3ae18630855ae876f6bf4cfe953b468dd549957fbf7d2f0", "2d41961a7636b7bd208394a212b2ed5e8e650636104b3f29532451a566618c2b"), + arrayOf("35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180", "ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "35c748b3d1b36c023e4e65906fa4668cc7541aff96ef4ab26f6b12ac1968b1f21bb05d0c6261d4e9f876a8466095d5b8e2ddd7d3cf0b69295e2646e97c4d1d00", "ca38b74af8854b4aeffe2e6d87d47c96d082332ae785b494af132374be268e7f", "9eda939f89f5abe53a4985b85705e323eb27278ca28c4d450117b1c04bb268ba", "135c748b3077ab4b71001d192782b83692f7dccd7187a4b6b50ecdc8b41d9717e", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d9717f", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97181", "35c748b4077ab4b61001d192782b8368ec64c782bf91e9f044a6a74e3e3c96d3"), + arrayOf("bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f99f60740bd841e333d35c56a8f6f090da3642af38bd4fa44326c643ee71169cfa", "4326a06b09f900ef", "3101a7671bbaf310ac62477a58c9ad025b1f8fec78ffa34662ef702c285cea7ca95ece43e5391b4bf0b8e547d8d161d2bbe7fbb35218ff96f12acab87b5929b4c9ab129d0d468d66", "9958feaedbfc730613cebafaa1a3c990343897d28a9f0ce4552099e4543f44ca", "82e705823194203f5a8e44310c69b5574edbb879b1f7c60adfe123e634ee166b", "bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f99f60740bd841e333d35c56a8f6f090da3642af38bd4fa44369ece4597b0f9de9", "d133d0d6a39d7af2b66e90cbfd9906d658aa1b7fc9b76de2564b3894d1742cbd", "d133d0d6a39d7af2b66e90cbfd9906d658aa1b7fc9b76de1cffdf7bebd822adf", "4fb9b684cc5ba000c1f3d5ff75b861512d63f1022d6b904eac2e334fe54ff63f"), + arrayOf("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4", "93215556ec196931504a9c1268745e41ebedc7b71967a15a7adb40a9c54eee853f6174d90550acdbf96c093336ab842ada3c9c83ca2ff189a3b6d6d8509bfc0c", "0", "b8974bc6caba17f97e499ad5750f68d108cfa3112e94446a3dbddc710070e5b3", "1932155567f3abe893c640543259da4fcd527677135d00e765c492927af6403f3", "932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4", "6cdeaaa780c54178c39bfabcda625b032ad89890ca2ff189a3b6d6d8509bfc0b", "6cdeaaa780c54178c39bfabcda625b032ad89890ca2ff189a3b6d6d8509bfc0b"), + arrayOf("98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "98036da47c66ba50f862b8addf7c0c5ab28bf1f05cba601afcb024363c2e5934e2ec74ee9b40ba828daffe692d463fefb46f35cdfd868e9892de68accdf2f3dd", "0", "2484520d738b8d049c5054ac812e123378a28e9cecda8e08b9344b68830d285c", "198036da4146a27f674c972fe3fdb57637d9dd656027971676d219753320d0c22", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57633a84d101a9910fec60db62162e703175"), + arrayOf("aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28d", "2", "155130d6bac86e40d7c67e9f8295e41e7f4565f7c5c1de0bfbd3bf765590da51a", "55130d6cac86e40c7c67e9f8295e41e7f4565f7b5c1de0bfbd3bf765590da51b", "55130d6cac86e40c7c67e9f8295e41e8376f64ceb506423ac9822ca25caa7fc9", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28f", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28f", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28b", "aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28b"), + arrayOf("a890fc4ad7cabd1a", "e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "9748e88ff89daf35e3bf67f1e857db15a9ed208be124b8bb2040aa20c3982b31815eba04f09c4b94", "dc5d172658714350a9ed208b49dbd02a905a125bc3982b3218a7a2958082e359", "dc5d172658714350d193fead835bd4b5e63239a80e5ac8a32f44269e7787cd3f", "e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e82ce6be17a97bb48c", "e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e82ce6be17a97bb48c", "1a3ecd02238af1dd50c9e2fd59e018aed71f16e66eba0919243b3a7e0619c5a7", "1a3ecd02238af1dd50c9e2fd59e018ae9406119315d1a79e17f50541027ceaf9"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a", "1d1c09df03cc707d375122dc41855e8d9fe634255daac54392a664de39e251911cf1db87fa0e2455a1d65322e233003115908ac51f57b6fe2ab9092082293b7a", "37c0cfe3aa73f5f8379c8a4be75b4960261412b8c4af132e814b377c3228cbdd", "0", "11d1c09de20e87a5d3b1d93595bba778a850b41f1b6dbd73c3c76f5d51dfc32ab", "1d1c09df20e87a5c3b1d93595bba778a850b41f0b6dbd73c3c76f5d51dfc32ac", "e2e3f61fdf1785a4c4e26ca6a4458874f4c2b369975365cdaafc9fb0daca17f7", "e2e3f61fdf1785a4c4e26ca6a4458874f4c2b369975365cdaafc9fb0daca17f7"), + arrayOf("1", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c24", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c24", "67fc9259eb95d80b8b368d01c024a89c826229abfd868e9892de68accdf2f3dd", "67fc9259eb95d80b8b368d01c024a89c3f492458a49e2d1d8698336fca56192f"), + arrayOf("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "a890fc4ad7cabd1a", "a890fc4a2f39c0cfd0c63f30d7cabd1a00000000a890fc4ad7cabd19ffffffff576f03b5283542e6", "0", "2c2e6bb1f0433f13854eac6a7f5ccf99f9178795daacabac", "ffffffff0000000100000000000000000000000100000000a890fc4ad7cabd19", "a890fc4ad7cabd1a", "ffffffff00000001000000000000000000000000ffffffff576f03b5283542e5", "4319055358e8617a63b538f22bd21d94"), + arrayOf("a890fc4ad7cabd1a", "a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44", "6ee5bc094c01c32d762af62debd1885508cd6e8889e4b597a7c786450f74ddc8ed63f8320209ace8", "c22cb95a30ea091f08cd6e881afef98dece0070f0f74ddc95c49b43bbcf12c1e", "c22cb95a30ea091f25de657c9b889b52b4b380474a7addefd8f1e56f0f859ed2", "a86b3370269a77e2b8adc407ffe2ccdba2363282100d133114b697fa41239a5e", "a86b3370269a77e2b8adc407ffe2ccdba2363282100d133114b697fa41239a5e", "5794cc8ed965881e47523bf8001d33245dc9cd7eeff2ecd03c6b609b6e71dfd5", "5794cc8ed965881e47523bf8001d33241ab0c82b970a8b5530252b5e6ad50527"), + arrayOf("e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23", "1c3e9b3cd4c32b9149b6b2a73dc5f5833890a5031acc6c1a8ada1b99784a6b0b019b82c85c7ec7d6f18049b285f445c85059c0d764beb74e45d9af12079c9a96", "f3c8064159d7ad07f7559042c40a39fa675a86aa7d634ef67301c7cd75f0a87b", "44bda3eaccc9c58b0bf951ca2ee61f1231f089ca01ac9df219b9c3523a9b0dc8", "10539c582b5d3fa0d43fd7acb14984e3f0fea5f5ceef380d6dc4702bd8f50f295", "539c583b5d3fa0c43fd7acb14984e3f0fea5f5beef380d6dc4702bd8f50f296", "c648a0770316223a1a6ebf3a37a7806341d772d833986cf82c6480dc1410fc4f", "c648a0770316223a1a6ebf3a37a7806341d772d833986cf82c6480dc1410fc4f"), + arrayOf("17b3c7e07b02fc6678f1828809b5c6742db74af8f604f55d28dbfa5cfde4ba35", "2b0194f84f025333860ca0152288831dc1c1634af4716ee1573c84b4025251562acaa6fe5d0c2ac6a6d800396faa07e239ac0f54c3b270bdb066694fd7a2268f", "3fb5811699215c6fc458c7267eb30fc5bbc33be607f9a1185d043690edcbdc3a7e98823310c059c9ba60b392e4048585d869ff4d223b42a0dcb996553d65299e4294b03c0647c4bc095590f7d8878a9fa9e9d118bd0f6afcd319e1d1ef1e19b", "f418e6ad6aa3ca960eaeb02d65e1d29baab34bf9ca1dfbd96b8556beb196859d", "6056b5faa52302815d96da543fa555dc62c6395dbc09e3a2814cf3998459b9b7", "2b0194f84f025333860ca0152288831dc1c1634af4716ee1573c84b402525156427e6eded80f272d1fc982c1795fce5667635a4db9b7661ad94263acd586e0c4", "670d89bf479714c33eb62c1ecdde745a31735c316fd9b00602574be375bcdd1d", "c85a0600ae6ee40ab32cd8f1458d188e29fb39c17c303ab44f60a8d6860c974c", "e64624fb00598a796df27b4d98f1cb1f910f444296afd65d792cbb3650ee1a87"), + arrayOf("bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f99f60740bd841e333d35c56a8f6f090da3642af38bd4fa44326c643ee71169cfa", "1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a", "153e782a06bf1c4eaaa5a53b4daf961a33adca5fa73a601dea8709ce396a978fc409cd6ca5951c11f993cdd82350a3e40b84b207e449f2d6a0bdb3f62af46d320a16f44b9e9f8d23527bf6b90854093e1cccc5274a937824fdc385e5f355e1e4", "cc21c9f60ff1eff9479883a19bf513cd209958b8572def041fdc7f3923414d1c", "a80da1d7071b48e870f79221a3b97916b8da783fecfecb75273040e7c9f1a33d", "bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f9bc7c7deaf92a5d900e79ea0252ab0864fe66f67ccd13dcfa6f836f0092afaa54", "ee4fdab5c485f54ef18c242559537e6120ce62c3d97ba6995be1c33be9143928", "b417c6f782b500967b50fd72a1de8f4b9085d43bb9f3352aca676d17a5e21e74", "329daca5ab7325a486d642a619fde9c6653fa9be1da75797a697a8a8cdafe9d4"), + arrayOf("35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180", "d83e8780ea6c14e39e4a06759d082f2e730e34598a0448282806acc8b4762920", "2d6d4812ae237f1171ad2bbdae15003929954811874a38a1e38d670e60bf3a5e185bea1726bdcac6eea999bd4ffb38e868296caa6068937dd28dc8fc5f5bb000", "30c15003b9636271aad8b6bad2cb703717713f7dc40a214f42127591ac2d5e53", "b94467c8bb12f81575438d05941a6894cbd7f776399f005b10110b44a40563f3", "10e05d034f1e6c999ae4bd8081533b297a28c012fa27e939378f38953f64f9aa0", "e05d035f1e6c998ae4bd8081533b297a28c012ea27e939378f38953f64f9aa1", "5d88c1321d0e9fd371b7cb1cdb23543abc6f987d8e76034328e62fc28d63485f", "5d88c1321d0e9fd371b7cb1cdb23543a7956932a358da1c81c9ffa8589c66db1"), + arrayOf("f731da8f03181b5a981010f9de72a0faf401b58e8e032daaff0491543dbbb294", "28fb800693a61e59dfbd1de97586244297da01c5341719a0624a8ca250cefe1a0c176e18b9617d7634f76bb88ab7c5a730264c9d78ad68a75b181f82df41952c", "2792a3a6e9b875f191532c0df427053d8b8f6f77863b72881a0828365ebca0db767d31b38c1f509e577e0c7b1b6a2e7f7df34ec597091a4bc6f2c4e90281cdbf0426f4d419ad96cb37f6bf7474c6b11987ac9de602743b733359cac81ec6d570", "5aef4708a8637eb5a0c49940f57d3f43a1c63889adffd084d12710cf7d3397a4", "f5a3ce6024bbe3cde0454ae8d200dd789c3fe922b39fc4a2815d1f212b0a97a1", "28fb800693a61e59dfbd1de97586244297da01c5341719a0624a8ca250cefe1b034948a7bc7998d0cd077cb2692a66a22428022c06b096525a1cb0d71cfd47c0", "add66944f606871810d859da10f56311429061613642f56dde99768d4f537032", "408d4bda1029af9c1f47c819abefdee4a57309bae5c365e81f6fac1b2c23f4f7", "b20ae1fb1c1fa5105bd8e12e9f280511c375b361e64912f75bdf475e8781c9fb"), + arrayOf("a5f447224b4a83131cebd31d0b2f178cfa42c8cf9e394c6aaeb24c005b8565b9d37e06163a743ba95bcfabc7d66c1bff34d2a0ad584a005be089d1d42ede986", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "a5f44721a5563bf17795972c398dc782e0805d739bd2af1916a1e63241b69fb2949435da813d71e8d4f429fd3e80812788e34ed1aa489b388c8c64b92dfa917018d80f7e83f4f0a815ad679a0cc20ebe416406c2064e4f25606b85bc6d94166", "3d22b0d89f509933b40005714db050e2ee1162a6ef0ce2fbec38d368b20bc35c", "0", "a5f447224b4a83131cebd31d0b2f178cfa42c8cf9e394c6aaeb24c005b8565c9d37e06063a743bb95bcfabc7d66c1bfb03424b87c9c3e8ab1c267e03f510ed7", "f604941467af0749839b48a102500dbf67ae5e67e541560924fb8618f91a068a", "f604941467af0749839b48a102500dbfede0690e971218ff3d87f0930053bbe6", "ce5de61088fb73be5eda723ceb8d94bf63ee240de8810bf9e7ce7e5103d341c"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "17b3c7e07b02fc6678f1828809b5c6742db74af8f604f55d28dbfa5cfde4ba35", "17b3c7e0634f348615a24e020bc7405296bca8b06a2cec87a209eba5be1b7d349170e4f06f6bf1c2af97748a9fe6fc7d43b69bb8455bdc14d63ced0892c793c5", "745496397e3e043db844ac4339d2757f26878b05b5a026e446073a7ad7779114", "0", "117b3c7df7b02fc6778f1828809b5c673ea9e45a69d1c93e21c95c51ffa47df86", "17b3c7e07b02fc6678f1828809b5c673ea9e45a59d1c93e21c95c51ffa47df87", "e84c381e84fd039a870e7d77f64a398b8f2fafb4b112a927caddd065fe7e6b1c", "e84c381e84fd039a870e7d77f64a398b8f2fafb4b112a927caddd065fe7e6b1c"), + arrayOf("932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4", "2f08e43a3c5fd165d8afaada522ecd026fbc67f2602cee85725a9e28e1ab0fd778dc9e222fb3e188debbbe41fa50b61b0ea3c36a32e3017ed9377d5644381937", "1b083ae0e359e7ac08feec93d23e4066ad1ccc0593d278d48a0fb942f6872f8ea47c9794de73d9c9d780799cfaaf06587cb6b3a97783fdd49d9de9c4a64d4862ea244a19bcdd62badacd9b6795ebb159cc6aacd990fcd947f2f51e8d203fad6c", "7a59b5821ee588dab3691d534bcb17d3a88ff8b789a679d16e11e0268c9dfc8f", "e43cdb4ae939455963870a354b0bc5202f8025c5764f767926eb798e3fb9cddd", "2f08e43a3c5fd165d8afaada522ecd026fbc67f2602cee85725a9e28e1ab0fd80bfdf379aeeea0111b1fc3851fee5b17e3cb2ada68b30ff53580a67df39c1d2b", "7ffbe1ac46c9d990a45e49c7df838f88bd42ad62f48405f271c105af70a719f7", "a646c902b7aba37fd469c0be6bb7ba70ed0c217d771c16fa46d14c9fee20edf1", "96839c8a19bf69aff39460cd252790ca6273d8a82ae97ba715e37ee353ec0ead"), + arrayOf("524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818", "aa36d620a88189977e12600bf8e3444402284f72a321be0c1660e91e833060e5", "36b944270e0ea0f159fda6bf3763a00938c5d556c9e698461966e290332ef98c67d1d696e243e3c988e61fb2bb914ce0f3bedb21acfd8a7cdd7a6960981e0d78", "ab1ee833874a198e8d0b859e0915008caac04c5d10e46c41ea9eb8560c7e2c84", "eb526f2fa9f36f5f92a7fbf5de92a9c6dd8980ae8861b484a9a70155e149baad", "fc84983fb08da92b24d2d57501b231f2c94f490af6556715255b41d96539f8fd", "fc84983fb08da92b24d2d57501b231f2c94f490af6556715255b41d96539f8fd", "a816ebfd5f8a95fd28ae155d0feba96ac4feaa26b011eafcf8996f9c5ed93732", "a816ebfd5f8a95fd28ae155d0feba96a81e5a4d357298981ec533a5f5b3c5c84"), + arrayOf("e26e2123d3a28d3402759554935338a80026b3c316cc837b337747576f4cab85", "689b4e34c2624fb7ef186f82919987ae3c58be508d5bee6bac793d93ad2cc3d2", "5c861b50d7113c53a60e2937cf0148352b095c4d4bbad18bd6539abab4d43f80358a0ca6221f377ceaf7dbabab42226fd1bab806cd4068c608303ef60f67021a", "141cfed47b457215caf8943a4a63d556843034b66a5f15c28197e22b2364d248", "31ceb8e00fe433a3eb571a776d0a7a80063c7c750c7c016cb703c0e8838a5618", "14b096f589604dcebf18e04d724ecc0563c7f7213a42871e6dff084eb1c796f57", "4b096f599604dceaf18e04d724ecc0563c7f7212a42871e6dff084eb1c796f58", "79d2d2ef11403d7c135d25d201b9b0f9c3cdf5728970950f86fe09c3c21fe7b3", "79d2d2ef11403d7c135d25d201b9b0f9c3cdf5728970950f86fe09c3c21fe7b3"), + arrayOf("1313f664abc386b0dc215391c78737046a3af6db63c4ef5811e0112483ef6bc19669e5e485113742a0dd9832532aab79b69e726a12d70ae9600ddf9018d0daeb", "2894ad2bc0573646", "30632f1ed3bbdb126f93d04379af8e357f8ac5ac5e67951e51c728f409e6366ddb3384dd4d880f753cd21a463d159b9271ee2bec55dda090e0f964e860c2b62d46a2e467d266e42", "534ab51146b3765447e61572110f9181b74fbb207fe61657f5b073ccbedce35", "8bec814bc8cbdb54ba34b1d8ccec020466ea6372ab9619a346fcea30e91fb975", "1313f664abc386b0dc215391c78737046a3af6db63c4ef5811e0112483ef6bc19669e5e485113742a0dd9832532aab79b69e726a12d70ae988a28cbbd9281131", "e1ecc409f4d58ecaf5bb5ce8d09a46da4d60ae7145de20759bc7858cb55085f4", "e1ecc409f4d58ecaf5bb5ce8d09a46da4d60ae7145de20754a9e2b3534a21968", "73321f582dd4bc84ffb5c8fa428bab329fa08838f2a8c6628efc1735b329c405"), + arrayOf("524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818", "b6d523b5ba4f0ba9266556499e1695743b10b98460edd46d409b0ddb9bbbdabb", "3ac7ce2fa1f4b75cc3bafa8b69824d83a2a0e5f0d6e73243d538c5d19c47131a2eec4c28b41f91f190985f42e0bf527610dffa85b0f3fe5e0943359fea0e8988", "d4c5698e61c876071d37790e310ea1db4099b4de8a04967aab696019e9bb7d17", "fa1eeca6873e932cafa961aa0c1becc8d16e24167ccdf850b2222a14fcbe2f61", "10922e5d4c25b2b3ccd25cbb2a6e583230237b31cb4217d764f9566967dc572d3", "922e5d5c25b2b3bcd25cbb2a6e583230237b31bb4217d764f9566967dc572d4", "9b789e684dbd13eb805b1f1f6ab8583a8c164014f245d49bce5f4adf464dbd5c", "9b789e684dbd13eb805b1f1f6ab8583a48fd3ac1995d7320c21915a242b0e2ae"), + arrayOf("dd1d7d870b39e98121d4ccd07a26c795c33c8d3af51f8ac356d6c7b288926819", "9047ad8b042bb82e3c21928f42d52a9b73d92a8414b46f3e7a550f1c2aaf3e63", "7c9e7faec7365450f46773b984c470f5d8861e575517c6a78be285819a547521a43cd4a49271a5758e371b20a7b03d38a28776d983500af66549b20388eb4fab", "da2ff26af821adb547345e580440ebeaeae8ed978b1a83b8943457d9639f2f8", "d0e1d038ccf8121d5e8957ed8eefbf9c93e1b4bb994502735ecd05834b944c25", "16d652b120f65a1af5df65f5fbcfbf2313715b7bf09d3fa01d12bd6ceb341a67c", "6d652b130f65a1ae5df65f5fbcfbf2313715b7be09d3fa01d12bd6ceb341a67d", "4cd5cffc070e3152e5b33a4137519cfa4f6362b6e06b1b84dc81b8965de329b6", "4cd5cffc070e3152e5b33a4137519cfa4f6362b6e06b1b84dc81b8965de329b6"), + arrayOf("946765c6463eab334798bfbb19ef00560b16b5326445c2b34db783afd9aeda711aef266f638ebd919506a1eb32a1532f8d94ae83a8b047b8ab3d5adb363dcb72", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550", "946765c5b1d7456d95c17a4e1894ebce11dae3c5dcb910d5312de0d528224890556ed2b4e3273f6d4d07d03b2198f94f3ff288908fb25ee17ac1ea378e13ac6cfcab00b9dd98704c72c1bc938b06813bb47a84c16230a918663701e5c6cd0da0", "c83801e8abb78851f17047adfb1f69264d5f9aecc37c0b03fc8402409130058d", "b26398ebba80b120d0ff60e375461ca20bd4130a9a05347c1d858872aadb9796", "946765c6463eab334798bfbb19ef00560b16b5326445c2b34db783afd9aeda721aef266e638ebd929506a1eb32a1532f4a7ba9314fc7e63d9ef7259e32a0f0c2", "e0effa3e7f4bec51d5c065a889f23821205210139ce58d6e14c69af6a72a2e6e", "e0effa3e7f4bec51d5c065a889f23821a6841aba4eb650642d530570ae63e3cc", "4d9c6713457f4ee02f009f1c8ab9e35db112e7a30d126a08d634425051878dbc"), + arrayOf("8000000000000000000000000000000000000000000000000000000000000000", "e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "72e0997e6e3a8711d79b0e81530ff3a89470748d48a2fb73c22ae0e668d87bb90000000000000000000000000000000000000000000000000000000000000000", "b9bbd60add087a14217854a3b8c2af0b08b7e8ce245d40eeff07b99ffdad5ed7", "161de14f42b78677c7e43f9198ed1d2bd0bfed45dbc48268106fee12173e4d94", "165c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "65c132fddc750e22af361d02a61fe75128e0e9199145f6e78455c1ccd1b0f773", "9a3ecd02238af1dd50c9e2fd59e018aed71f16e66eba09187baa3e332e4f088d", "9a3ecd02238af1dd50c9e2fd59e018ae9406119315d1a79d6f6408f62ab22ddf"), + arrayOf("7a3348c387beed5a5dac51519625be32e56566545a5b0c2b16fbd08fc0ebb639e34c27beb1e8060bcccd3d97bdc6cfb691a85197b05f1b308094211604ef2c60", "2", "f46691870f7ddab4bb58a2a32c4b7c65cacacca8b4b618562df7a11f81d76c73c6984f7d63d00c17999a7b2f7b8d9f6d2350a32f60be36610128422c09de58c0", "be7e6c8286a05452a42d226777a5febd28a038d221020c7ff84d705cf7c09fef", "858199408e57461d4f6e530bc221beb9653f65bec42fcb6a089708885f071a8", "7a3348c387beed5a5dac51519625be32e56566545a5b0c2b16fbd08fc0ebb639e34c27beb1e8060bcccd3d97bdc6cfb691a85197b05f1b308094211604ef2c62", "df3f3640c3502a29d2169133bbd2ff5e94501c699081063ffc26b82e7be04ff9", "df3f3640c3502a29d2169133bbd2ff5e94501c699081063ffc26b82e7be04ff5", "42c0cca0472ba30ea7b72985e110df5cb29fb2df6217e5b5044b84442f838d2"), + arrayOf("b6d523b5ba4f0ba9266556499e1695743b10b98460edd46d409b0ddb9bbbdabb", "a73988095f96aaef9645f3edfc51e3d29f745fa984ae4bad8371b3f6973c5f1b", "776e20e86cbb8bca7e5349cdd763c66f0bee495f60ac133ab53fc303d7d3f892c02f7172b39979860a389f4c183a799ea07d479c1212e32760d333b1b3cf76b9", "3bfc5fe9d9e7ececeb2a0ecb1a784fa3e0f2d4861c3049403cde4d0072824cea", "2e9d19a7db148b3a911af45c6399b53e14f45fcdfa9f3c3761aa0aea5f13e6bd", "15e0eabbf19e5b698bcab4a379a687946da85192de59c201ac40cc1d232f839d6", "5e0eabc019e5b697bcab4a379a687946da85192ce59c201ac40cc1d232f839d7", "f9b9bac5ab860b9901f625ba1c4b1a19b9c59dadc3f88bfbd2959e5047f7ba0", "f9b9bac5ab860b9901f625ba1c4b1a19b9c59dadc3f88bfbd2959e5047f7ba0"), + arrayOf("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6c9a316693aeff4bdef2eb05a013db0b2a19c99f3cb2fcb414745cf1d43f0831936", "216560ae18b8e241ab4f5f7ea9439f792bceca425218d5fcfa0f285b320a11a", "dd8f13efbe0d348ccd7dc1e2a4593a28e56d72707dff5a815a75fb639140c595", "15ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6c9", "5ce996c6100b420fd14fa5fec24f4d5e63660c33d034beb8ba30e2bc0f7ce6ca", "a316693aeff4bdef2eb05a013db0b2a19c99f3cb2fcb414745cf1d43f0831935", "a316693aeff4bdef2eb05a013db0b2a19c99f3cb2fcb414745cf1d43f0831935"), + arrayOf("83e1554bb92622db1f27452dc92ffc6bfcac6ddf2691392dd6b2ab0d1e71ab8a", "98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "4e4f8ec4f1e35255181d2307f48816d1f9327ea01218bca7e9f78c3380bb9c29bb5b55418eed29010d4146f788ab6aa0c15255d325f3373cc3e1c33d2796ebde", "f152899aea038346446852e97c8e7cdfbe1ec9bd8ee6e627319f1249a8f096d", "7961dcebee29cb68c0e4c0a6483a236f5e6aa0fb46be2a0c8030038397e37f81", "11be4c2f0cd904ad093f0b82c090b53cf7a4a4434290aaa9543d44260507eb7ad", "1be4c2f1cd904acf93f0b82c090b53cf7a4a4433290aaa9543d44260507eb7ae", "ebdde7a5a4bbfae6aa5dd22f8954a5087f0e978b2417c7c6699113b9ec649f66", "ebdde7a5a4bbfae6aa5dd22f8954a5083bf59237cb2f664b5d4ade7ce8c7c4b8"), + arrayOf("1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23", "20b24ea73c995bca", "404fdd1e7fc7bb895f9c9f51007ef525887f2745cfc46f5b5c4c68142e194f9d2fd22abca6c9a9e", "7df645ad240675c85887f27458f74923c9c34cf742e194f9d702207db66e1428", "7df645ad240675c85995a5747b347a1154399e3507f654b6327ac55a0f0633f4", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef78a38f97fa3956ed", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef78a38f97fa3956ed", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef373ef24981069f59", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef373ef24981069f59"), + arrayOf("e26e2123d3a28d3402759554935338a80026b3c316cc837b337747576f4cab85", "bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f99f60740bd841e333d35c56a8f6f090da3642af38bd4fa44326c643ee71169cfa", "a53f75f3a176e45de972b3b93a70a2c55e7839078afc39387947986e40f5c462197faf313956611c0790f9da9de57d11be0c4a3f29c8c5935bfc43758d0778df7d7781fae31d5c259e32eb3187b55df87a05ba7128d850669ca2a027dbd28be2", "9e8792cae339d03c5f63e8d2fe86f5ecf6a65483d845d186450366028799b3a9", "678606f7797e9c18fe7386989d760a54d169c3f18d73957b01ff1b665f101447", "bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807fa81ce952fabe47067d5d1ebfd8a43c982366962fbd41c27be5a3d8b45e063487f", "b3a1f1fb77400825b8e4262090ec3f7e58d0cf41e083f15d469bdf8136c7d754", "113a504d300512414c07048895ba31d1a77c98434d1515992052af2da7d17fb7", "92b46a9f0746ed334081bf551d9ad756d2c2c2c0e960f32c4422739c8003b457"), + arrayOf("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "28fb800693a61e59dfbd1de97586244297da01c5341719a0624a8ca250cefe1a0c176e18b9617d7634f76bb88ab7c5a730264c9d78ad68a75b181f82df41952c", "28fb80066aaa9e5375127f96296f24b30210fb6c3abebc2459b393210258a9016a1da0dd024cf0e2dc075811fbe63fc4935aef03ab3f362969a7f44ce0ff4beefa76e1e55606645343b5fceed06059dbaf1b488e87529758a4e7e07d20be6ad4", "0", "64bcbd2a86f2dc57d526a8c712ec4de00cf0bd7b8bcc5f2c2af173e169b63291", "28fb800693a61e59dfbd1de97586244297da01c5341719a0624a8ca250cefe1b0c176e17b9617d7734f76bb88ab7c5a730264c9e78ad68a75b181f82df41952b", "b6a48eb4f2ee6bbe78c848e03282c2164e8eabd3a83fc7c2df94e5391197bd9d", "495b714a0d1194428737b71fcd7d3de9b171542d57c0383d206b1ac6ee684262", "bad9076b190789b6c3c8d034c0b56416cf73fdd45845e54c5cdab60a49c61766"), + arrayOf("b698d9359320bf01c5a9e27f2b73b3c906859b95e59909062a264e66c59ea0dd", "293e13dd799d3e5b94caf18169b0270340eff9e83dfa200ac9665452dbad9102341052c2d426e926e2406afa8189439b5af5299fd2a12c5c71b98289b6629d53", "1d6ac1f9805ac492dbff1e193ddc1e55e018851501ddbc604a066c27c2c5164e91cb02cd24dce246362f6cc89f68446e282d4123310ff6b883ea4e1ff7ac3506fbd51acb81a747e85d91f79b5e236ed724a9f247e6eed8aa58a02fe00dafb0a7", "b7ecee787b88c681140be808c0848f2f369554a80ac2ea76772d3a5fb843d887", "6e112cb1c9e178ffff5317ba799e0101d0bb6a68c680c1ff54c2ac48d3a3b3c8", "293e13dd799d3e5b94caf18169b0270340eff9e83dfa200ac9665452dbad9102eaa92bf86747a828a7ea4d79acfcf764617ac535b83a35629bdfd0f07c013e30", "c4abc61c165297226f0ea71e1c2ff26b7d33ff5aff7e0b9b01e9da90680cd2bd", "a885ec4f0feee6e11c451de03ab775268fd737d0cbb406715262c23d23306efd", "f81e7d1e2f8b382ec877b39655179db72fe8124bcf7481b2b2fb74f07dff5f1c"), + arrayOf("ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818", "524dc21eb5be5d74f10217f46a1a97d965188152e7295f3e8af9c8ddcd035dce91242a139918528905b2be36fd5c7d5d53bba4e75998adede20b4e8a3beccfd0", "adb23ddff7f3e06d593f8a96f731125138d90668accc56f6f105a7451df667e7", "47d837633240b9c8c690595a12df186039369a3d0b3a60730ba2bbd3048c11fb", "1524dc21e080c1f94a6c0756908ceedaec726f9995333a9090efa58bae2099816", "524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099817", "adb23ddff7f3e06d593f8a96f731125138d90668accc56f6f105a7451df667e6", "adb23ddff7f3e06d593f8a96f731125138d90668accc56f6f105a7451df667e6"), + arrayOf("689b4e34c2624fb7ef186f82919987ae3c58be508d5bee6bac793d93ad2cc3d2", "a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44", "44d1b94113eaa93c5e3136ab4610abd4feba178ce97d33321bf4eb606d4cb7837364f2803bfddb81c29d854787f88b48d9f6320c672705af98abbdfc17204dc8", "22ada888d650dd80036fb398def4daf2f3a993559870b745a11f9790e97b4d63", "ba34fa48d3c08e59f2386dc27a98b4f0baea7eb14b9bac40776ce474960d7038", "1110681a4e8fcc79aa7c6338a917c5489de8ef0d29d69019c189ed9431685a116", "110681a5e8fcc799a7c6338a917c5489de8ef0d19d69019c189ed9431685a117", "c0301ac39bc7d7d6366aab7a91b6bad29a228bcf7d4edb3b4053a1e443d3e68d", "c0301ac39bc7d7d6366aab7a91b6bad25709867c246679c0340d6ca740370bdf"), + arrayOf("35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180", "2", "6b8e91680ef5696c2003a324f05706d25efb99ac30f496d6a1d9b91683b2e300", "6b8e91680ef5696c2003a324f05706d25efb99ac30f496d6a1d9b91683b2e300", "6b8e91680ef5696c2003a324f05706d25efb99ac30f496d6a1d9b91683b2e300", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97182", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97182", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d9717e", "35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d9717e"), + arrayOf("265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7d", "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7cd9aecd44a791c4f964fda144bc2904cc1c3fcf12e8695cdfd112e1cb8bfd3183", "e67505f6f5914d8e76d933768bc6325c3d2f66a3c9fe646fb9fddb6f13e55851", "70b02ae9605d70937151277a31c8232097e8cb0dc2ec6d6fb84d5cacf0d10d15", "1265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7c", "265132bc586e3b059b025ebb43d6fb33e3c030ec1796a3202eed1e347402ce7d", "265132ba586e3b079b025ebb43d6fb33e3c030ee1796a3202eed1e347402ce7d", "265132ba586e3b079b025ebb43d6fb33a0a72b9abeae41a522a6e8f77065f3cf"), + arrayOf("273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449", "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "273fcd321b5e161c34017b484b83c19960cf46d053c6c1ea3625749e63f769bf5a647445c581865cee9718bf6f83a6a934b51f74c20955dc3836e9a76195bb7", "0", "1ea79b6168faaf17ede2d416e5e12bc13b3de27922be92ed1d0696542e1888", "10273fcd22429de35e4f5f916458456faf69b5252b3df6aa23c7c916589e6a448", "273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449", "273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449", "273fcd32429de34e4f5f916458456fab3824cfe5af7092730365c288649c99b"), + arrayOf("2894ad2bc0573646", "a73988095f96aaef9645f3edfc51e3d29f745fa984ae4bad8371b3f6973c5f1b", "1a821ba291971b04411e167b6bfc475b9318095ae08bc23fbb6374286313fa2b6e4d1eb5a8beb362", "d2b5317ebfe310b59318095ac609a69d0f4a3d826313fa2b88cf3a5854d7ea08", "d2b5317ebfe310b59a0aadd837e4fafc22941db7a6fb67070ba2180605ac6adc", "a73988095f96aaef9645f3edfc51e3d29f745fa984ae4badac06612257939561", "a73988095f96aaef9645f3edfc51e3d29f745fa984ae4badac06612257939561", "58c677f5a069551169ba0c1203ae1c2d608ba0577b51b452a522f935291ad72a", "58c677f5a069551169ba0c1203ae1c2d1d729b04226952d798dcc3f8257dfc7c"), + arrayOf("a890fc4ad7cabd1a", "1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23", "14b8f2fe258ddc51804895c40541cd981afae47d4ced6f0d1098efc0e7b21f2fffce5cb6ed46588e", "a5d67214cafafe491afae47d38347c0ed6522071e7b21f3014874fb5278d27dd", "a5d67214cafafe4920695293d830d7d2ad6577fe5ac7501ea6280e88515b558f", "1f789285d95eebe994c75dc86e7866ede70976425dad89f000823d3b956ab83d", "1f789285d95eebe994c75dc86e7866ede70976425dad89f000823d3b956ab83d", "e0876d7926a114176b38a2379187991218f689bea2527611509fbb5a1a2ac1f6", "e0876d7926a114176b38a23791879911d5dd846b496a14964459861d168de748"), + arrayOf("1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a", "72fff0cd0c00d9516aaaaeb7c1e5f7ebfa13510b982729a8d2b0d655914c2fae", "d1396b4cbfbcdc2bcfbae285353925a057ebec0b2de664ee59f47b2b5fd0c7da1f1e45d0de60ac7600acb8db65bab291e5932f8318638d454bfef5fe032992c", "b67d4f66ad5ffb71c6b035090a784beee449987153d84b4403def8679a052056", "bcc0fd4eac0dc1d3c986d9e10e4c8dc158200fbd350da1051892c45fdf306459", "901bfaac2ce953ada5c842111da06f76c237984fa7eb62601b6e0167b2e53d08", "901bfaac2ce953ada5c842111da06f76c237984fa7eb62601b6e0167b2e53d08", "aa1c191114e7a10bd072e4a199d47f9ece10f639779d0f0e760c54bc904cddab", "aa1c191114e7a10bd072e4a199d47f9e8af7f0e61eb4ad9369c61f7f8cb002fd"), + arrayOf("a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44", "dd53dd21dbcef5e7047c043bdfacdbf6080093b808729c1a07b908be1e040ff2", "919bb7a450852d66d48647bd19422bda1382cc8cd05a917fe362c1acba3f6fd0081f8bd11865c04bd41097b6e01fe728a4618f782a79929925c4dac738082648", "a58c50ec6410ce08cbe5db965878a890a333dee057afc3dd0998d55183d9ea3b", "8fb5d06bfcb1cedc8ff2a2b737547ea14fcd8a3bce034ef33e68e1545f842f6b", "185bf109202696dc9bd29c843df8fa8d1aa36c63a187faf4a73dea46d875ced36", "85bf109302696dc8bd29c843df8fa8d1aa36c639187faf4a73dea46d875ced37", "cb17564d4acb81fcb431bfcc2035f0e59a359ecb079a7716646c92f14b54cd51", "cb17564d4acb81fcb431bfcc2035f0e5571c9977aeb2159b58265db447b7f2a3"), + ) + + val bigInverse: List> = listOf( + arrayOf("0", "", ""), + arrayOf("1", "1", "1"), + arrayOf("2", "7fffffff80000000800000000000000000000000800000000000000000000000", "7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a9"), + arrayOf("ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "ffffffff00000001000000000000000000000000fffffffffffffffffffffffe", "18243f8b709e93ebad604247a57e628bebe577fcb3ae1ef188cd3279d1f0d3dd"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550", "5d989b974f49761eb1011435874aa99aa2bbfe0bb8eba30f4d6d50a67498f72c", "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550"), + arrayOf("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", "", "bec9c048fbdbb9bf7baa1c31aa158998bc1b03f7860a98044d74d1aa66910bf7"), + arrayOf("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", "41363fb6042446418455e3ce55ea766711e3890a587b8cc0107b9d4744732e77", ""), + arrayOf("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "e1e1e1e10f0f0f0f69696969b4b4b4b45a5a5a5b0f0f0f0e87878787c3c3c3c2", "646b78f8384d6e771ef9319a025559fc5af4a6580d5e25e84c7cbf12b54961cc"), + arrayOf("8000000000000000000000000000000000000000000000000000000000000000", "fffffffd00000006fffffffa0000000400000002fffffffc0000000600000001", "c1a0cc66920b83d20ff16c083cc0ee4b75bde7c486acdf5f9c3791ef3832f8f2"), + arrayOf("265132bb586e3b069b025ebb43d6fb33e3c030ed1796a3202eed1e347402ce7d", "6c1a26b6e054f75101f5716c3d54decc80457d99b4f6a38494ef2ee1035ad2df", "c464b3b1b9c835b1606c37476f143b810409686570162f48d4009f61f5089ff0"), + arrayOf("775ba67c7e8471fe55848450f5988a8d5df54ea6bb5231f99f3ea91eb430e144", "4f37072cdf26edb8e15ecf9692d6eba6c73711a43aba90e48587a050f52f7ea", "9d4cdfca37a2e64f16ee3b2fab74d822fc5805654f636da476b9766236e4734e"), + arrayOf("e53d6ac2a9d065ccefa28f414fd1d3ebae185e8f7df8582a9c9187935356ffe", "39eabbe3277ff16e626e74d047383ebaa73d3fb318797eea883f050937f5a799", "cb00f9265ecf865b04159d6227a9dabf7b83a8b21398808f17ed76b750943bac"), + arrayOf("35c748b4077ab4b61001d192782b83692f7dccd6187a4b6b50ecdc8b41d97180", "c164f9673b818f807f3f7bde7de8cc1fbdc43746a864939961d7257c77e8a3a6", "e702005fa1b7c90f50358d58d7df62b066ec7971e11ec67504478f76aead4dc"), + arrayOf("a86b3370269a77e2b8adc407ffe2ccdba2363282100d13306c259baf6958dd44", "b2f43fb5f19d723d7f2e634d8af21834d05a109393f49760ba2f4344681943ec", "60cf4bd29ae1cca19db8932a8a670fcb97dfeebafc63564317661709f46d7382"), + arrayOf("17b3c7e07b02fc6678f1828809b5c6742db74af8f604f55d28dbfa5cfde4ba35", "cd41f75cad64e3fc8672deafb413db324349d771aeb6ba33e07fcc14a994715", "cd185c98545c27a9071e7ff3bb75f4e1ca1e0d53e711b4245fef96bf726c3e53"), + arrayOf("a73988095f96aaef9645f3edfc51e3d29f745fa984ae4bad8371b3f6973c5f1b", "c1297a7bec0964df72fd0c2728cb567b8347e1d53d1bf91378c0e03d08856cfe", "4fc9380e0e5b22d4378ee06156c883f5974ea0c57f3a75e0dc414cf53c206ffc"), + arrayOf("72fff0cd0c00d9516aaaaeb7c1e5f7ebfa13510b982729a8d2b0d655914c2fae", "307ade96944ffc15afa773431f9503fd96481d76303814689838a955352de308", "bc073762de45eea99b5fe13924626d39986ce563de19e40549fb5e517afa9122"), + arrayOf("273fcd32429de34e4f5f916458456faf69b5251b3df6aa23c7c916589e6a449", "89231de68bfc16f8164f040df0ee491f39cbb764e9141ccc1894bf4fde1ae6da", "12325d5756ecf00f287336ba31e475a6c5c98d225b03ddd722ccdfaad29c4a3"), + arrayOf("da4b4f5d2b430d5e03724ba8f9a519a57d77e82b7da88ce33dd8dcc8e4848582", "4f9f6c5c41d7d2346424035a223bb776d93790c95f6744d8878fd52289f44128", "598e3e4e1c9182f65017b8484b2b9e41739221a75a4ef8ec2feb3aba03d1878d"), + arrayOf("ed3415970860d9205fcb75c353b4b2922d48d5c73f569d042441d999491f7d6e", "2583ef278b1e666523cb4da040ae0bfe11a21ab3bff793965753aae0d35a7c96", "97767e37856aa8d0a035ad3362741c4fe62ea8f17c85444086e8ba66a3f45abf"), + arrayOf("2547d817889aa379a04fd2734ba60da5d988dead67f0f6ae9451cecf220f8f3f", "9cb8e425f5620cc5d9c72e8b896b91e3ad8f54deda6bfe9a471ae4bb228ea8cb", "606dd8a4df147f4094fd16d09263b0fd34db69d4f3da9e21a0adebd0e27df7d7"), + arrayOf("dd53dd21dbcef5e7047c043bdfacdbf6080093b808729c1a07b908be1e040ff2", "5b0f34c5cf2521b38982c7a5d454c80926b57f0464c8b3ff5dd95df6728a2741", "e4f03bfd38875954a296e3b06f887d01bfc64bd09914c7338ebe217e4647915c"), + arrayOf("68ffcec715e32b33dddb30ba8fefd65175027d10571a5fe54682106bb2081430", "dac02534e220bf883721307bf0eb962d18d1ec3bff42e1b59d9bdbd4f2d9ce84", "9ba2782a86d1ebfb85d506dacf1c1d350cfab1bedb0740ec937391cd3738c1ea"), + arrayOf("88abc140ae9fcde21137c13ee158113e8d856a022f4d2d1ef2a9f13493969739", "cc5cec01ec994d1935da1ad7ff66abfabbdf9a84a85a55c1e5e9a1c7d2919979", "88d775260e03d230906f9a9b97b442af6a8ab7404c4ca8cd61784c569bc7d4a5"), + arrayOf("f731da8f03181b5a981010f9de72a0faf401b58e8e032daaff0491543dbbb294", "7af442c22fd355e8050a7f497473d5005d1c31c01de2ae4aa58298015a2ca422", "2a92b334d0745569e5b332f7b1a80d093181401d310aba5bc70e4e978811c233"), + arrayOf("e26e2123d3a28d3402759554935338a80026b3c316cc837b337747576f4cab85", "4a762da2125ca1f86cf44a5690315dac5eb1674af84a0b1d6750356f855876d4", "6ff134ae7843ea68a7dfd001811374689b60a34aa1e6d7b104d74922a962040b"), + arrayOf("689b4e34c2624fb7ef186f82919987ae3c58be508d5bee6bac793d93ad2cc3d2", "c29a6f685db06204f836f8653e06dbe05f035041c6faa83f1b34870de5b702bf", "3003057e59573e65662b310effe8417b65e36daf38c0fd990d9f89f43355614b"), + arrayOf("1f789285d95eebe994c75dc86e7866ede70976425dad89ef57f140f0bd9ffb23", "391e4616efc1d2b2c790b1ab89377051933416d150e462c49765b2fe46034da5", "9a5e7c7303c41d4cfe81a9aee42670c51d2198305df75c4e124500e6b64c594a"), + arrayOf("9047ad8b042bb82e3c21928f42d52a9b73d92a8414b46f3e7a550f1c2aaf3e63", "4deb1a19730785a78fb385be75855adab5abd5a955e2ba862618ae2378c9cc91", "69bb9c6a16ac415c74db66926caa40602e6380d07a35cda10678e6d70aeb93b1"), + arrayOf("b698d9359320bf01c5a9e27f2b73b3c906859b95e59909062a264e66c59ea0dd", "bb926fc6df151b5d34ab5cd539ccf7e844c90e8d48c29b1b3e3619bbae1c4ac2", "74ab5d4b4661f20d672591d6afa95d7cf1b2cdd1c462c66836faebcc5ba18d0c"), + arrayOf("83e1554bb92622db1f27452dc92ffc6bfcac6ddf2691392dd6b2ab0d1e71ab8a", "936f53b4c52ee1ed7441e4ee3570b6f9426a84a9e273861275e4ddadf8a0e837", "32cdcf6e603e799ba6799241c967384f758de51e1017500bb59c0c0eb3d57b11"), + arrayOf("5ce996c5100b4210d14fa5fec24f4d5e63660c34d034beb8ba30e2bc0f7ce6ca", "fe23f2e01746c1a836f7ee683276ea3907bef496dd186d7eefb13d059c37f7d", "26ad218fbba95adcea7b200168bfbd54058f9982669dd97139d0a8f4e2510117"), + arrayOf("98036da5146a27f574c972fe3fdb57637d9dd655027971676d219753320d0c23", "c73e09e804fbf8b3a823f34797a10d3b7440bfbd37cffd72afa3434499bb0c49", "e50df3937901db3b43be2577f87d73009c67eb87ae3f93100696bfb923c02bda"), + arrayOf("41aa680a327f06d357780366e0ad1404248c7ce7e2b4530540951dc661e9ff5", "3624aec866b2e9760e808642c1d5cba5d70d14b7a7607af7a8441f80ee259bfc", "f4400fadc846963ac05ae5b6691f995ace3b49c3286a2821e23e726f024e1a0b"), + arrayOf("6187f66c8377439657180f12fec15e26db6801012b041f662c76fdbd4e1ad300", "afe13735f0cd8cb1d6dff3f0bf3c07fb5fa2560c9e7d23ac7bddf1fbc3f1d1ff", "3ddafdf0586ce1b838e2964c857b85c3dd9dff2a49aa2c20c9a86151d525fd7a"), + arrayOf("e5c132fcdc750e23af361d02a61fe75128e0e91a9145f6e78455c1ccd1b0f772", "13474caa6fcbac1174292766895ac45ee32c7695bd7411cab0f002380402ddfa", "4728bb0e9d59c27f49d2315d2fea69f3db01f4122dadcf074ab6610df07b5a42"), + arrayOf("b6d523b5ba4f0ba9266556499e1695743b10b98460edd46d409b0ddb9bbbdabb", "338b632b43681e063d275debc92891de763377425619862ef11ae2d659c6d3c4", "6a90793db1cda836b6e0fd3bfaaf23cadd877797ceefdfead5a21477a5918b63"), + arrayOf("72af80d38cfbd4003bce3b66231c24b4db4eae70e9749eb5183832d19b32d2dd", "d029195b66f8623d4ea5fd6d44298fd957f7459202c131bf9a8eae2b47a405f5", "1952d92faf07813ddb38eb52533fffeaffbd6b512fca9c48f9b023362006187d"), + arrayOf("aa36d620a88189977e12600bf8e3444402284f72a321be0c1660e91e833060e5", "b1acd07623659e5efb8bfa88815693e9379a51da6267bb6044fbabe21971919a", "6ddeac55fa26ff586d78043aeb3f60616efb49550606afa42bc45a00f5d740c5"), + arrayOf("63386867c5d43c991677d0f6e02c2d7c5f705c64a8e51e761c21958f4c07a35a", "828bcd2f8a735a3267310091ca6f79502d2230d6b20b81b27f6ffba83ddcaf2f", "240b3bd0d59ad69e59a66cf56e2e38a16bee9a38bd4c3dde798432e5096eca67"), + arrayOf("932155577f3abe883c640543259da4fcd527677035d00e765c492927af6403f4", "dc94ceffae085ca216db283566e89d988ee0ee538573480d33925bb0b75ebe8b", "e4376b7bf8d179264da50d5978fb37b04b7144008e1a60a337f1ce54ef593ced"), + arrayOf("aa8986b5d6437206be33f4fc14af20f3fa2b2fbe2e0ef05fde9dfbb2ac86d28d", "fddbe2180a089f6866a340cb7b70137b933452588c36246d164614a4c810d8cb", "99274baa32c77c15f34575d2c8327bf3c1414e0e0b8dd5280a15e0654a90290c"), + arrayOf("68d3853af55433e7d4f1ce47fadc1c699ba352c977ad9dbfd60f4260780ca6e", "21ad721bedda56ddcbf4e2eff01cfef882afda9856f5fe14e993af43e0cada69", "2f2c9a9ee24c7ff827d3cff22f01245a06bce8c3c3ecf07c1990dff2373337ba"), + arrayOf("7df7219c51c1eab2ef9fa93a39c0428430c42d761cbf883cea28d9b4c68ca22d", "e38498899934a1ad96f0666bc61aa25208342128f0d78169820bc0844139bb81", "c7ca91c09f4b972d21b45b42659710c8bb46723cfa66cdb29962757b8e32ff33"), + arrayOf("d83e8780ea6c14e39e4a06759d082f2e730e34598a0448282806acc8b4762920", "6f033e931dabb497ab1bbe4c29ee85db09e29408cdcebd726cfdfd671e1f63b2", "3f6af4b3cfdc6d32f6a08aa66c16b2f833a9bbb319f4c3c67cc69bd5eccd7e32"), + arrayOf("524dc21f080c1f93a6c0756908ceedaec726f9985333a9090efa58bae2099818", "8a4bda16f696dfa6b3e0948a06079912c54c3af99176d3d3031ef8c2fb9ea9e0", "33ad72e09f325951439c02a553c586f38d7e9487973e1e2e4906f4789ffd9064"), + arrayOf("1d1c09df20e87a5c3b1d93595bba778ac82447440fc438b748bd2b1221990d5a", "6c588a78112b5344a7c0cd8470a366c194efdd686617ff45a866a0bd0be6f4c4", "60b70d7558dc6d075e6c104d145f281a5663b4447171f5bee4f691ba4bf08bac"), + arrayOf("dd1d7d870b39e98121d4ccd07a26c795c33c8d3af51f8ac356d6c7b288926819", "fee0fc0079ef2073da6be99f0b4a2fd7ec6169da8129fa855bc8d480a82eb8ea", "8dc3c76dbb1b9b925744a0c6cbf69731c1cc0959f02a81906b4a8071d61e90c1"), + arrayOf("2b79cd9d840d1eee32b037dccf7655ea3d225bbf66913ff10c009d18f423ed93", "dbd5226891d11f7a0317b613b82962cb0d82afc39a987ee3034fc84a45b19973", "393cec560430a9351da46d40f990be1a6cc28a3d5fb7ec5afba76cfdbbb42b6f"), + arrayOf("1313f664abc386b0dc215391c78737046a3af6db63c4ef5811e0112483ef6bc19669e5e485113742a0dd9832532aab79b69e726a12d70ae9600ddf9018d0daeb", "33306615e81be135db00ed7d2c4e41d8c047ae6a5ad4827a58258572696e9fa6", "589a4344864ec3568c836c1c44a66c3a597bb83ed19219e4b001db6ebb992ee1"), + arrayOf("293e13dd799d3e5b94caf18169b0270340eff9e83dfa200ac9665452dbad9102341052c2d426e926e2406afa8189439b5af5299fd2a12c5c71b98289b6629d53", "d573a354dc16edd317f6bced860d22d6cdaddca73044b01c38a97f224ae599da", "993e8af94ca638ba74721369eb0d68c3ec09e47a56bfb9e26c10e9d720124d0f"), + arrayOf("946765c6463eab334798bfbb19ef00560b16b5326445c2b34db783afd9aeda711aef266f638ebd919506a1eb32a1532f8d94ae83a8b047b8ab3d5adb363dcb72", "89cf187e4fe77ec49cd65cd0c282c110decb6a768f8f281392cf0bc01a9e2825", "9a00a21a9e60619d8f7279984aaad0666014e866f5e32e8b744396402f02da7f"), + arrayOf("a5f447224b4a83131cebd31d0b2f178cfa42c8cf9e394c6aaeb24c005b8565b9d37e06163a743ba95bcfabc7d66c1bff34d2a0ad584a005be089d1d42ede986", "257d640a9643e72701334cea97a13ecccf96443b8b3a40ad52e62b50f894ae03", "27fd857c801f1a2ba72289a8b19a70582a4f1fe17bcb8d8fdad7aa8af3dd710b"), + arrayOf("7f4b9f3562b3e6bbcff868f1c61a76f9d11cd3ed5ede19ed2dbb1be22a03a610511aede245ffd45c0122d877bd462e8b73a6a2e1da7112d8948e9f2ac2bc91ca", "408e5c1932202eb3b007412e5ab05bc667966da87229d31386ad48077a64ec01", "1585838a619b70d17b460b1a0253f0c7ce2e04078b73b62f64718bf4bfe2adee"), + arrayOf("28fb800693a61e59dfbd1de97586244297da01c5341719a0624a8ca250cefe1a0c176e18b9617d7634f76bb88ab7c5a730264c9d78ad68a75b181f82df41952c", "4e7d57af7ca6740f795217adacb04e7bb37ff07b3757df364c835e406a654cb0", "57bd1fea26d15309cf8ce2364b53d6b6d7c8420551e287a7007047cddf007fa2"), + arrayOf("7a3348c387beed5a5dac51519625be32e56566545a5b0c2b16fbd08fc0ebb639e34c27beb1e8060bcccd3d97bdc6cfb691a85197b05f1b308094211604ef2c60", "de9082dc439b5388da120574e658b4dab879546f391dcf45fd3d99b7bfcf50a4", "7892c5dd0a3af04570d9708e9e939257db83448ff753c5466da04ed03be0719f"), + arrayOf("2b0194f84f025333860ca0152288831dc1c1634af4716ee1573c84b4025251562acaa6fe5d0c2ac6a6d800396faa07e239ac0f54c3b270bdb066694fd7a2268f", "25c2496f91e7af77e793b952e7fb4e7806898889695cba3f3667b3604a99d217", "d3020369adf6acc57c2e373ff2220f64641acb1a73c42281590b33974e43ba5b"), + arrayOf("2f08e43a3c5fd165d8afaada522ecd026fbc67f2602cee85725a9e28e1ab0fd778dc9e222fb3e188debbbe41fa50b61b0ea3c36a32e3017ed9377d5644381937", "90726a1cec2f79102123abee60d47876133511096fd00d7f835e60c597b6e8c0", "e944abe8ecd0ff91680238725cfb34730e8371fc945a358d92b4d72cccfe11ff"), + arrayOf("bad3ec68dfb835450fc1ce7d9e18e823753f34a641768524f34ea76565e807f99f60740bd841e333d35c56a8f6f090da3642af38bd4fa44326c643ee71169cfa", "8c63f5f5053cef241aaaf6eb8b0bd3c2ce6ea063d85c2270f9fb77e8f61fac40", "283e300fd69cc9bb05281a376a1ed4a6a3c3d53e283f7202843c754b01a188e6"), + arrayOf("4326a06b09f900ef", "45746bec16f5e09f2ea7b8bcd7c99f41fe44c7c0dc389c24c611f18b01390555", "4ea148d3a8a79a08df45a684fd50a942c64a781bf8b65a0844f487c92fe762e"), + arrayOf("2894ad2bc0573646", "eb36d312877161e24dab766cbb15b6422539816c51af9ba2a5f16521c01ee81d", "e6249add0599b6247dafa210618e4caebe62f0fe2ad02489a992f8b99adfc0a4"), + arrayOf("979f1c64776574e0", "33d943061278c0cc2cce3400658161f5da38b041d48a9a124c8f1170d0ef7f47", "d91fd9e236b77ebf5321dac99e5e5934d3d5d4fb20a295eba7418ce956b0ec1f"), + arrayOf("a890fc4ad7cabd1a", "36df61a1864eb77a9673af9d7de563a4e9ce1648f8b9fac1d63501a5b8563b92", "6f1e5083230d2ad50b2430bf87a37066c22ade92cec7dc4fbba7bce9fc078f65"), + arrayOf("b71201ae48ab3a40", "505f595e9ab4b23d01abd2ed79270c738babd10c8d37ba16477c494d538b81f7", "d0b2374e8e3b86b09071698b752db080d16cee030e9482fa6902e7d79c6698e"), + arrayOf("20b24ea73c995bca", "9d452483c705e9a6d84eba6158ab2abb5da9104eee2005363d6a8d780027c469", "4c070c6f24300f56107e08925cfa02816ebb87c0951ae00b68dc4ec472ee13d"), + ) + + val bigModPow: List> = listOf( + arrayOf("e4ffaf358aead9e1978f275ad0e4ce6f99ac695f0eaa23161e5423f8440aa023", "c79a7b6a9fbb2f5c03e8a26e71325bc0f8309007c4c28312f932771afc3e79a2", "d33f76125848bdf56e5585252ee0a1c158886a9dfdb2617f3b2cf2f33f24f7b3", "68dd82daf7c7f6e0af5562021adb4115549f96da5a9be1af036dd28fbcdcfe3"), + arrayOf("cf00fb72213906aa61dbba8fcee85f378095b9c9d58dc27bde7bb77a18888c69", "81350e632457c5a3281e709f97d854ec818b9828567a5704210fd8dd183e3924", "35d7958166bce45771f415704ed5a9051aad90abb5e002d1d28798e55705eec9", "fd25be58dc2fb87babcbf540232bc84a445fc768aee865af3b72393cf6c6d8ee"), + arrayOf("996a9b0cde6de94725609a913e4d783ec0215eadbdf96d69a5a9c73d839c4b1f", "84128b90281af6fcf6e204ac7c21328ef77e54c168e8550b66632f05609e2c63", "325a3876a7be10d7935e2cc1d1bb053093b6827ab4c570ed996b09bb9e1c8fb7", "c4b7ad58e58853575cb9332dccb805d520f8f17d8451bdad4548cadc78dbf255"), + arrayOf("e6c243cb01aeb4dd906017cccae31423516c2649168668fff17d337bbdea802c", "16e7cf7e0b31a017ba414519e90a2f4eeeaf9d9c6bfe63ffe7820fc02cd108dc", "3e24f1fda2a0644668ae6a5557f9cf1dcf6779b0f16e1a01822fd786880574cf", "8c1269f949dc016dae2921b0652f43d13142658ae502d1ac51ef2760cb2b395f"), + arrayOf("9d4217780cf1a0bd9024bd785a3a9e5c6537e24471817f587eb2a73c4156d3fe", "bb43d66f6fa279d300b3126ce79696ba3d12846212ecb942ffc169d015501660", "2630c2d184db172a4801236ed0da266772ae267aa8d02328fc9cbc1eef6c4524", "2cb1a36c1f2dff670036f4c62bbabb9d91d6f1b23b499b56dd8ab5b581119471"), + arrayOf("e2253d13c01088c050c9dcc1182b50bb723cdabb9f0025d749ea165ac6923d2e", "39e46073345fbbca96ec81a4bf5b8cd6f738803b4c2f2f324d465171f42c031d", "241d70c26ba058494fe6cd0019edc813eb4c8022f48600bfd33e6548cbe4f983", "7eb89b29f87c7ab40c7738357e067789cc505f3a9a6938c9ed6acc1fe0ab29d0"), + arrayOf("1afce7151fd9e1b43e11ad206d6ca5d02e7cfc15b1ee2d2d9081064846b4a216", "94ff9c047b52b01d89b12432fa135a2e71a6d9e44ba4aa80acd611b4e3a1797e", "f6b246aff822bd4db9972a2f4e20a243a61fe7394ca2876c73929cc219e43d7e", "43a77e78c432cde6d68d910f94b36542ce95b53369c87554741e4b477d63cb66"), + arrayOf("e9f7d084671825c70834fec20121c7898d8ebcc4f81c340fce5daf52fabea63f", "1198b792a671288025a267ce612e41da421c41eb7f95b68e3aab9a903aa17ae2", "3586b0d161866a45e200bc4c04c3e00e8b25869c6589f0f0543a1027b0ed50d7", "e394eec111017a1353e9f239f7ee4f98963d6361c16c059889d87031129de4e"), + arrayOf("363f27d81caf8c049aae8105bd670085c4f2a73806539cc4c3bdf2225a37cbab", "36cb669955cccfc9f70b04eafd5dd0183deb9e009acb380f533d3d2693657c59", "341b09a53893709bfeffd4c4ff6a538c60e93090a9a8d816635dbdd0613b3ce5", "26900e98b6e8990f7312ee7c57e95a30e99f2ae2ee53961ec20d868d6211de0c"), + arrayOf("253bf3fdfe9f40592013a64fcbeb35eb495faea4ab5e4005690923aa20b2cf67", "c821672e6a9c698acdb9859a172abd69784315a28c9d4e8a9617c0e9c5014deb", "339f15c87f96fd9b11a727480bf4bc58587bb222dc84a7e84e38100bb1145e7c", "f311cd816b0804d9e8494162133e1a9c52519820ef39ea587d40692127aa90af"), + arrayOf("1ae8edfb0e20e3aa09d906de947461d6cf111e64f723bdd5ffa1a0d1456456f3", "cadfec280556ef62b4c3e434387e41524784368388004d8fdea5c5bdebf0b819", "95f935dbbadf69e0affdb5d73f3b85b5162e012b2e8231346ea980ddc7970cd3", "f99e9c9d8c2702af974f24178d666c830fbc9ce857460c3609c625a47fec2c6a"), + arrayOf("bc25ccf58ca681f0012d7048c075118e4d1f54183dad645301b24a8b02b3cc5b", "8454094887b79324f85e3302293afd33408c6f73fc97e4a6490587325da6f599", "4936fc5d8bece7c663c81b3119e18cf14c16272b875adb66b378ca8c15cb464d", "2f4e631434c501f8c6990d958b850e3b8b6335972ea990147025fb87f4c37ecf"), + ) + + val transcript: Map = mapOf( + "password" to "1234", + "scalarA" to "f3ebb18d77c7cb07c8f649cc4d299d7ba32c9aa0452acd3ea97a3bf405f69", + "scalarB" to "481c1abf89c2b022c653fef76709c3c02ec21b7e5aee5ce1955bb0359cf16521", + "exponent1" to "bdcd038a41e56f9561294bf6811ad49ed736f2a9a613cc4edfb52909b492416a", + "exponent2" to "9e81c9683b3dd362060d659bfa079eaf49b95ab33ec1ea5b04772aef1c6fff76", + "exponent3" to "3bc4d553fb5e494e71bc96f70bc634e85165e292943e3ef8c6f984f54a54c077", + "tokenKey" to "7b7e37780442d9e010b6b2e58c0d8b2e", + "a0_cmd" to "0a00", + "a0_data" to "null", + "bobRound1" to "fdabda15ac3e71004cd575c762a678a63789a080421054427a44a9ff947fa623b34cc4a52e96a5fa132ff90ca9704c9044a7bf7dc969fa7222c622938dc3a6ebe3e3cd9f76ae805ae634c115aaa188ebc1548e82d0ff9258bb01730eca41f295be4d47eaf17f4ffbeb3d5d87c093fa1ca5d9dfbea5f20e0abedcbc77ac8d9794709f6742a8d9e4974b3e8a3786645bfbe7508b92da34127ecf2ed7a06a4d52f1", + "receivedData1" to "true", + "a1_cmd" to "0a01", + "a1_data" to "2e347f312394d10e19a1065bfb353b6a49711f11f5a4c787c63983950b9750ce93d05b9c7b39eeeb079d5430bfa3c39205cb3cda9a3f4edc40cd199b202a67b797f06c2eb20c3b7b9bacb3fa17ce72ff14dcef76785394925f13690c31774acba2493cc59f0c5d3663012515dba5cc0a6c7579a584ef2f515be94dbf8bf550e11385ee586f4b7b55b5a814dde53676314a2613f1e8842da27520c5be748b3211", + "bobValidatesAliceRound1" to "true", + "bobRound2" to "a0fb4e02c21f5a8ffe5fe1547aeccd1a0e9eab19dc87fc8da0963c00f382232f432701ce8660dc81c3f02ec6dbde2c549a5dcfdb861a062d133f627782514200eae0ece6798f539ed98a892b618fe0257fe215d4ecf04995c888d7315af58847c4db3fccc4a15db30430822a1ef4c0afaa1758954be7fd8d94baf246484fbeb01108b243cb334f43cdc45a4d403a8e45f8fd06be3f3ef45dd3dcb60d022be5d8", + "receivedData2" to "true", + "a2_cmd" to "0a02", + "a2_data" to "dd8d8898b8f21cb7fb2119ee2b2f96d3010bbbf41bae8e8e4e78ab6cd306bb30b1f4d109d28d6da5cb2e55bb865d56de2db6f42a08c77c837e57babe2025260cb8837b838426640286fb439bbf8899a16895c1c070ff85fda5e4d455761cf1f184297e5d81da4c801a881ca174c27dc73773b339f442eda743e515b671e5b3a06e9d62962869b4d219b7351d86e7019081aaaa7e88eafd4fe147d1925e432738", + "bobValidatesAliceRound2" to "true", + "bobRound3" to "dc8f1b94ec4bb727f062f7c76c1905a6d4aba8178e9898faeb910e6778c09838e76a926adde87644280c2cba4a6f6aa16f3bf6442013f012ee6eaa1329b1ad1ce21886b0b063242ca515d7572789fd42d406b2ebde995f8f96dbd3066f659a9be3bfea0559a07194506b5986669804945e499707e49516b5a372410f78146c45a859ad6e4c248091fb3756931c1208ad83c458071232daeb8324a5c221374f6c", + "receivedData3" to "true", + "a3_auth" to "027b7e37780442d9e002", + "a3_data" to "dd5c400deb31f39cdc215a675281feb805d3cb1331eba66c5dad506698ea0386c2538c46a88616641cac8d07ec4bdd2791ec873964f3ae258c5c690e550fe50b8f7abbf75bc10848362aecf89d33a07b34a47807bf1ea1abf63416f83ca1804273db1234ed353216a2541c4d2dec416c8acca8a4205f54b03bd846d7cfa4ae7bb5a8d9b61707774d6acce1b8c2e45ce0f032a079e6da8784812a3bb992a3c68b", + "bobValidatesAliceRound3" to "true", + "sharedKeyFull" to "7de3c335b714e03767b927f32f12d038e64656ba73eadf693c30285466b1309e", + "sharedKeyShort" to "7de3c335b714e03767b927f32f12d038", + "aliceToken" to "7b7e37780442d9e0", + "bobChallenge" to "8e68cb7361e2d89f", + "bobAuthResponse" to "031cef6bbe1ba82f2f8e68cb7361e2d89f", + "receivedResponseAuth" to "true", + "a4_authChallenge" to "04c0972d22b78e77e5", + "expectedChallengeHash" to "c0972d22b78e77e5", + "authStatus" to "050101", + "receivedResponseStatus" to "true", + "a5_len" to "1", + "a5_cmd" to "4e", + "persistence1" to "7de3c335b714e03767b927f32f12d038", + "drawOrder" to "scalar f3ebb18d77c7cb07c8f649cc4d299d7ba32c9aa0452acd3ea97a3bf405f69;scalar 481c1abf89c2b022c653fef76709c3c02ec21b7e5aee5ce1955bb0359cf16521;exponent bdcd038a41e56f9561294bf6811ad49ed736f2a9a613cc4edfb52909b492416a;exponent 9e81c9683b3dd362060d659bfa079eaf49b95ab33ec1ea5b04772aef1c6fff76;key 7b7e37780442d9e010b6b2e58c0d8b2e;exponent 3bc4d553fb5e494e71bc96f70bc634e85165e292943e3ef8c6f984f54a54c077", + ) + +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksHandshakeTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksHandshakeTest.kt new file mode 100644 index 000000000000..bea4a507e9c6 --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksHandshakeTest.kt @@ -0,0 +1,117 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksReplay +import jamorham.keks.crypto.KeksUInt +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * A whole four digit pairing, replayed against the one the Java and BouncyCastle code ran. + * + * The other side of the recorded handshake was a second KEKS context driven by the same Java + * classes, so these bytes are a real J-PAKE exchange and not something made up for a test. The six + * random numbers the Java drew were recorded with it, which is what makes the replay exact: every + * message this port writes has to be the same bytes, and the key it ends up with has to be the key + * the other side worked out. + */ +class KeksHandshakeTest { + + private val t = KeksGolden.transcript + + @AfterTest + fun tidy() = KeksReplay.clear() + + @Test + fun theWholeHandshakeIsReproducedByteForByte() { + val plugin = Plugin(t.getValue("password")) + // The two key pairs are normally drawn at random inside the constructor. They are replaced + // here with the ones the Java drew, which the context holds openly. + plugin.context.keyA = KeyPair(KeksUInt.fromHex(t.getValue("scalarA"))) + plugin.context.KeyB = KeyPair(KeksUInt.fromHex(t.getValue("scalarB"))) + KeksReplay.clear() + KeksReplay.exponents.addLast(KeksUInt.fromHex(t.getValue("exponent1"))) + KeksReplay.exponents.addLast(KeksUInt.fromHex(t.getValue("exponent2"))) + KeksReplay.exponents.addLast(KeksUInt.fromHex(t.getValue("exponent3"))) + KeksReplay.randomKeys.addLast(hexBytes(t.getValue("tokenKey"))) + + plugin.amConnected() + + val start = assertNotNull(plugin.aNext()) + assertEquals(t.getValue("a0_cmd"), start[0]!!.hex(), "the round start command") + assertEquals(null, start[1]) + + assertTrue(plugin.receivedData(hexBytes(t.getValue("bobRound1"))), "round 1 from the sensor") + val round1 = assertNotNull(plugin.aNext()) + assertEquals(t.getValue("a1_cmd"), round1[0]!!.hex()) + assertEquals(t.getValue("a1_data"), round1[1]!!.hex(), "our round 1 packet") + + assertTrue(plugin.receivedData(hexBytes(t.getValue("bobRound2"))), "round 2 from the sensor") + val round2 = assertNotNull(plugin.aNext()) + assertEquals(t.getValue("a2_cmd"), round2[0]!!.hex()) + assertEquals(t.getValue("a2_data"), round2[1]!!.hex(), "our round 2 packet") + + assertTrue(plugin.receivedData(hexBytes(t.getValue("bobRound3"))), "round 3 from the sensor") + val round3 = assertNotNull(plugin.aNext()) + assertEquals(t.getValue("a3_auth"), round3[0]!!.hex(), "the authentication request") + assertEquals(t.getValue("a3_data"), round3[1]!!.hex(), "our round 3 packet") + + assertTrue(plugin.receivedResponse(hexBytes(t.getValue("bobAuthResponse"))), "the sensor's challenge") + val challenge = assertNotNull(plugin.aNext()) + assertEquals(t.getValue("a4_authChallenge"), challenge[0]!!.hex(), "our answer to the challenge") + + assertTrue(plugin.receivedResponse(hexBytes(t.getValue("authStatus"))), "authentication status") + val done = assertNotNull(plugin.aNext()) + assertEquals(t.getValue("a5_len").toInt(), done.size, "a single entry means authenticated") + assertEquals(t.getValue("a5_cmd"), done[0]!!.hex()) + + assertEquals(t.getValue("persistence1"), plugin.getPersistence(1)!!.hex(), "the shared key") + assertEquals(t.getValue("sharedKeyShort"), Calc.getShortSharedKey(plugin.context)!!.hex()) + assertEquals(t.getValue("sharedKeyFull"), Calc.getSharedKey(plugin.context)!!.hex()) + assertTrue(KeksReplay.exponents.isEmpty(), "every recorded random number was used") + assertTrue(KeksReplay.randomKeys.isEmpty(), "every recorded random number was used") + } + + @Test + fun ourPacketsAreAcceptedByTheSameCheckThatAcceptsTheSensorsOnes() { + // The sensor side of the recording checked each of our packets with the Java code and said + // yes. The same check here has to say yes as well, in both directions. + assertEquals("true", t.getValue("bobValidatesAliceRound1")) + assertEquals("true", t.getValue("bobValidatesAliceRound2")) + assertEquals("true", t.getValue("bobValidatesAliceRound3")) + val ours = Packet.parse(hexBytes(t.getValue("a1_data")))!! + assertTrue(Calc.validateRound1Packet(ours, Config.Get.ALICE.bytes), "our own round 1 proof") + val theirs = Packet.parse(hexBytes(t.getValue("bobRound1")))!! + assertTrue(Calc.validateRound1Packet(theirs, Config.Get.BOB.bytes), "the sensor's round 1 proof") + assertTrue(!Calc.validateRound1Packet(theirs, Config.Get.ALICE.bytes), "under the wrong party") + } + + @Test + fun aFreshHandshakeAlsoWorksWithRealRandomNumbers() { + // Nothing is pinned here. It only proves the drawing paths are wired up and that a packet + // this port builds passes this port's own check - which the replay above ties to Java. + val plugin = Plugin("1234") + plugin.amConnected() + assertNotNull(plugin.aNext()) + val first = Calc.getRound1Packet(plugin.context) + assertTrue(Calc.validateRound1Packet(first, Config.Get.ALICE.bytes)) + assertEquals(KeksGolden.packetSize, first.output().size) + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksMessageTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksMessageTest.kt new file mode 100644 index 000000000000..85a2395b0cae --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksMessageTest.kt @@ -0,0 +1,78 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksReplay +import jamorham.keks.message.AuthChallengeTxMessage +import jamorham.keks.message.AuthRequestTxMessage2 +import jamorham.keks.message.AuthStatusRxMessage +import jamorham.keks.message.CertInfoRxMessage +import jamorham.keks.message.SignChallengeTxMessage +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The bytes of each message, which is the part of a port that breaks quietly. + */ +class KeksMessageTest { + + @AfterTest + fun tidy() = KeksReplay.clear() + + @Test + fun transmittedMessagesMatchJava() { + val byName = KeksGolden.txMessages.associate { it[0] to Pair(it[1], it[2]) } + val authChallenge = byName.getValue("AuthChallengeTx") + assertEquals(authChallenge.second, AuthChallengeTxMessage(hexBytes(authChallenge.first)).byteSequence!!.hex()) + val signChallenge = byName.getValue("SignChallengeTx") + assertEquals(signChallenge.second, SignChallengeTxMessage(hexBytes(signChallenge.first)).byteSequence!!.hex()) + } + + @Test + fun authRequestMatchesJava() { + for (row in KeksGolden.authRequestTx2) { + KeksReplay.clear() + KeksReplay.randomKeys.addLast(hexBytes("00112233445566778899aabbccddeeff")) + val message = AuthRequestTxMessage2(8, row[0].toBoolean(), hexBytes(row[1])) + assertEquals(row[2], message.singleUseToken.hex(), "token for alt=${row[0]} chal=${row[1]}") + assertEquals(row[3], message.byteSequence!!.hex(), "message for alt=${row[0]} chal=${row[1]}") + } + } + + @Test + fun authStatusIsReadTheSameWay() { + for (row in KeksGolden.authStatusRx) { + val message = AuthStatusRxMessage(hexBytes(row[0])) + assertEquals(row[1].toInt(), message.authenticated, "authenticated of ${row[0]}") + assertEquals(row[2].toInt(), message.bonded, "bonded of ${row[0]}") + assertEquals(row[3].toBoolean(), message.isAuthenticated()) + assertEquals(row[4].toBoolean(), message.isBonded()) + assertEquals(row[5].toBoolean(), message.needsRefresh()) + } + } + + @Test + fun certificateInfoIsReadTheSameWay() { + for (row in KeksGolden.certInfoRx) { + val message = CertInfoRxMessage(hexBytes(row[0])) + assertEquals(row[1].toInt(), message.state, "state of ${row[0]}") + assertEquals(row[2].toInt(), message.which, "which of ${row[0]}") + assertEquals(row[3].toInt(), message.size, "size of ${row[0]}") + assertEquals(row[4].toBoolean(), message.valid(), "valid of ${row[0]}") + } + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksPrimitivesTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksPrimitivesTest.kt new file mode 100644 index 000000000000..72e3a93a256c --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksPrimitivesTest.kt @@ -0,0 +1,120 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.util.AESwrapper +import jamorham.keks.util.Util +import jamorham.libkeks.Digest +import jamorham.libkeks.SHA256 +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The parts of the handshake that have one right answer: the digest, the block cipher and the + * small helpers. Every value came from the Java that ships on Android today. + */ +class KeksPrimitivesTest { + + @Test + fun digestMatchesJava() { + for (row in KeksGolden.sha256) { + assertEquals(row[1], SHA256.hash(hexBytes(row[0])).hex(), "input of ${row[0].length / 2} bytes") + } + assertTrue(KeksGolden.sha256.size >= 18) + } + + @Test + fun runningDigestMatchesJava() { + for (row in KeksGolden.digest) { + val destination = ByteArray(32) + val digest = Digest(destination) + for (chunk in row[0].split('|')) { + if (chunk.isNotEmpty()) digest.update(hexBytes(chunk)) + } + if (row[0].isEmpty()) digest.update(ByteArray(0)) + digest.doFinal() + assertEquals(row[1], destination.hex(), "chunks ${row[0]}") + } + } + + @Test + fun blockCipherMatchesJava() { + for (row in KeksGolden.aesEcb) { + assertEquals(row[2], AESwrapper(hexBytes(row[0])).aes(hexBytes(row[1]))!!.hex()) + } + } + + @Test + fun challengeHashMatchesJava() { + for (row in KeksGolden.calculateHash) { + val context = Context() + context.savedKey = hexBytes(row[0]) + context.challenge = hexBytes(row[1]) + assertEquals(row[2], Calc.calculateHash(context)!!.hex()) + } + } + + @Test + fun passwordHandlingMatchesJava() { + for (row in KeksGolden.passwordBytes) { + val context = Context() + context.password = row[0] + assertEquals(row[1], context.ensurePasswordBytes().hex(), "password of ${row[0].length} digits") + assertEquals(row[2], context.getPasswordBigInteger().toHex()) + } + } + + @Test + fun configurationBytesMatchJava() { + val byName = KeksGolden.config.associate { it[0] to it[1] } + assertEquals(Config.Get.entries.size, byName.size) + for (entry in Config.Get.entries) { + assertEquals(byName[entry.name], entry.bytes.hex(), "config ${entry.name}") + } + // The nibble swap in hexStringToByteArray is what makes these read as words. + assertEquals("client", Config.Get.ALICE.bytes.decodeToString()) + assertEquals("server", Config.Get.BOB.bytes.decodeToString()) + } + + @Test + fun hexHelpersMatchJava() { + for (row in KeksGolden.hexStringToByteArray) { + val result = Util.hexStringToByteArray(row[0]) + if (row[1] == "null") assertNull(result, "input ${row[0]}") else assertEquals(row[1], result!!.hex()) + } + for (row in KeksGolden.tolerantHexStringToByteArray) { + val result = Util.tolerantHexStringToByteArray(row[0]) + if (row[1] == "null") assertNull(result, "input ${row[0]}") else assertEquals(row[1], result!!.hex()) + } + for (row in KeksGolden.bytesToHex) { + assertEquals(row[1], Util.bytesToHex(hexBytes(row[0]))) + } + assertEquals("", Util.bytesToHex(null)) + for (row in KeksGolden.intToByteArray) { + assertEquals(row[1], Util.intToByteArray(row[0].toInt()).hex()) + } + } + + @Test + fun arrayHelpersMatchJava() { + assertEquals("0102030405", Util.arrayAppend(hexBytes("0102"), hexBytes("030405")).hex()) + assertEquals("0102", Util.arrayAppend(hexBytes("0102"), ByteArray(0)).hex()) + assertEquals("0102", Util.arrayReduce(hexBytes("01020304"), 2)!!.hex()) + assertNull(Util.arrayReduce(null, 2)) + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksProofTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksProofTest.kt new file mode 100644 index 000000000000..c6beaa94542b --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksProofTest.kt @@ -0,0 +1,70 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The zero knowledge proof, which is what makes each round of the handshake believable. + */ +class KeksProofTest { + + @Test + fun proofHashMatchesJava() { + for (row in KeksGolden.zeroKnowledgeHash) { + val hash = Calc.getZeroKnowledgeHash(pointOf(row[0]), pointOf(row[1]), pointOf(row[2]), hexBytes(row[3])) + assertEquals(row[4], hash.toHex(), "party ${row[3]}") + } + } + + @Test + fun aJavaProofIsAcceptedAndADifferentPartyIsNot() { + for (row in KeksGolden.zeroKnowledgeProof) { + val ok = Calc.validateZeroKnowledgeProof( + pointOf(row[0]), pointOf(row[1]), pointOf(row[2]), bigOf(row[3]), hexBytes(row[4]), + ) + assertEquals(row[5].toBoolean(), ok, "proof should verify") + assertTrue(ok) + val bad = Calc.validateZeroKnowledgeProof( + pointOf(row[0]), pointOf(row[1]), pointOf(row[2]), bigOf(row[3]), + Config.Get.BOB.bytes, + ) + assertEquals(row[6].toBoolean(), bad, "the same proof under another party") + assertFalse(bad) + } + } + + @Test + fun packetSerialisationMatchesJava() { + for (row in KeksGolden.packet) { + val packet = Packet(bigOf(row[0]), pointOf(row[1]), pointOf(row[2])) + assertEquals(row[3].take(KeksGolden.packetSize * 2), packet.output().hex()) + val parsed = Packet.parse(hexBytes(row[3]))!! + assertEquals(row[4], parsed.hash.toHex()) + assertEquals(row[5], parsed.publicKeyPoint1.getEncoded().hex()) + assertEquals(row[6], parsed.publicKeyPoint2.getEncoded().hex()) + } + } + + @Test + fun aShortPacketIsNotParsed() { + assertTrue(KeksGolden.packetShortInputIsNull) + assertEquals(null, Packet.parse(ByteArray(KeksGolden.packetSize - 1))) + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksSignatureTest.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksSignatureTest.kt new file mode 100644 index 000000000000..9715da5d7fe9 --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksSignatureTest.kt @@ -0,0 +1,110 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksDer +import jamorham.keks.crypto.KeksEcdsa +import jamorham.keks.crypto.KeksP256 +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The signature the sensor asks for during four digit pairing. + * + * BouncyCastle drew a fresh random number for every signature, so two signatures over the same + * challenge were already different bytes on Android and no signature can be pinned as it stands. + * What is pinned instead is the random number itself, worked back out of a real Java signature + * with k = (e + r * d) / s, and checked at the time it was recorded. Given that one number the + * whole signing path is fixed, so the bytes below really are Java's. + */ +class KeksSignatureTest { + + private val privateKey = KeksDer.readPrivateKeyScalar(hexBytes(KeksGolden.partC)) + + @Test + fun theKeyIsReadOutOfThePkcs8TheSameWay() { + assertEquals(KeksGolden.partCScalar, privateKey.toHex()) + assertEquals(KeksGolden.partCPublic, KeksP256.G.multiply(privateKey).getEncoded().hex()) + assertEquals(KeksGolden.partCScalar, KeyPair.fromBytes(hexBytes(KeksGolden.partC))!!.toHex()) + } + + @Test + fun badKeyMaterialAnswersNullRatherThanThrowing() { + assertEquals(null, KeyPair.fromBytes(hexBytes("30030201ff"))) + assertEquals(null, KeyPair.fromBytes(ByteArray(0))) + } + + @Test + fun signingWithTheRecordedRandomNumberGivesJavaBytes() { + for (row in KeksGolden.ecdsaSign) { + assertEquals("true", row[5], "the recorded k was checked when it was written down") + assertEquals("false", row[2], "BouncyCastle signatures were never repeatable") + val signature = KeksEcdsa.signWith(privateKey, hexBytes(row[0]), bigOf(row[4])) + assertNotNull(signature) + assertEquals(row[1], signature.hex(), "signature over ${row[0]}") + } + } + + @Test + fun javaSignaturesVerifyAndTamperedOnesDoNot() { + val publicKey = KeksP256.G.multiply(privateKey) + for (row in KeksGolden.ecdsaVerify) { + assertTrue(KeksEcdsa.verify(publicKey, hexBytes(row[0]), hexBytes(row[1])), "java signature") + assertFalse(KeksEcdsa.verify(publicKey, hexBytes(row[2]), hexBytes(row[1])), "wrong message") + assertFalse(KeksEcdsa.verify(publicKey, hexBytes(row[0]), hexBytes(row[2])), "bent signature") + } + } + + @Test + fun ourOwnSignaturesVerify() { + val publicKey = KeksP256.G.multiply(privateKey) + for (row in KeksGolden.ecdsaSign) { + val challenge = hexBytes(row[0]) + val signature = DSAChallenger(privateKey).response(challenge) + assertNotNull(signature) + assertEquals(64, signature.size) + assertTrue(KeksEcdsa.verify(publicKey, challenge, signature)) + } + } + + @Test + fun challengerTakesSixteenBytesFromOffsetTwo() { + for (row in KeksGolden.challenger) { + val incoming = hexBytes(row[0]) + val signature = Calc.challenger(hexBytes(KeksGolden.partC), incoming) + assertNotNull(signature) + // The Java bytes cannot be compared because of the random number, but the message that + // was signed can: it is exactly bytes 2 through 17 of what arrived. + val publicKey = KeksP256.G.multiply(privateKey) + assertTrue(KeksEcdsa.verify(publicKey, incoming.copyOfRange(2, 18), signature)) + assertFalse(KeksEcdsa.verify(publicKey, incoming.copyOfRange(1, 17), signature)) + } + } + + @Test + fun aShortChallengeFailsTheWayTheJavaDid() { + var raised = false + try { + Calc.challenger(hexBytes(KeksGolden.partC), hexBytes("050101")) + } catch (e: IndexOutOfBoundsException) { + raised = true + } + assertTrue(raised, "a three byte packet where a challenge was expected has to raise") + } +} diff --git a/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksTestSupport.kt b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksTestSupport.kt new file mode 100644 index 000000000000..a85cd90662e3 --- /dev/null +++ b/plugins/libkeks/src/commonTest/kotlin/jamorham/keks/KeksTestSupport.kt @@ -0,0 +1,50 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Tests for the Kotlin translation. They check it against the behaviour of the original Java code in + * NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks + +import jamorham.keks.crypto.KeksEcPoint +import jamorham.keks.crypto.KeksUInt + +/** Lower case hex, which is how every value in `KeksGolden` is written. */ +internal fun ByteArray.hex(): String { + val digits = "0123456789abcdef" + val out = StringBuilder(size * 2) + for (b in this) { + val v = b.toInt() and 0xFF + out.append(digits[v ushr 4]).append(digits[v and 0x0F]) + } + return out.toString() +} + +internal fun hexBytes(text: String): ByteArray { + require(text.length % 2 == 0) { "odd hex: $text" } + val out = ByteArray(text.length / 2) + for (i in out.indices) { + out[i] = ((hexDigit(text[i * 2]) shl 4) or hexDigit(text[i * 2 + 1])).toByte() + } + return out +} + +private fun hexDigit(c: Char): Int = when (c) { + in '0'..'9' -> c - '0' + in 'a'..'f' -> c - 'a' + 10 + in 'A'..'F' -> c - 'A' + 10 + else -> throw IllegalArgumentException("not hex: $c") +} + +internal fun bigOf(text: String): KeksUInt = KeksUInt.fromHex(text) + +internal fun pointOf(encoded: String): KeksEcPoint = KeksEcPoint.decodePoint(hexBytes(encoded)) diff --git a/plugins/libkeks/src/jvmMain/kotlin/jamorham/keks/crypto/KeksPlatformJvm.kt b/plugins/libkeks/src/jvmMain/kotlin/jamorham/keks/crypto/KeksPlatformJvm.kt new file mode 100644 index 000000000000..d2cc8945a0a7 --- /dev/null +++ b/plugins/libkeks/src/jvmMain/kotlin/jamorham/keks/crypto/KeksPlatformJvm.kt @@ -0,0 +1,57 @@ +/* + * KEKS J-PAKE / ExtraData authentication for Dexcom G7 / ONE+. + * + * Translated to Kotlin from NightscoutFoundation/xDrip + * https://github.com/NightscoutFoundation/xDrip + * pin commit 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f (tag 2026.07.15) + * See plugins/libkeks/NOTICE. + * + * SPDX-License-Identifier: GPL-3.0-only + * + * Part of AndroidAPS (AGPL-3.0-or-later); these KEKS sources retain their + * upstream GPL-3.0 terms. Free software, distributed WITHOUT ANY WARRANTY. + * See https://www.gnu.org/licenses/gpl-3.0.html + */ +package jamorham.keks.crypto + +import java.security.InvalidParameterException +import java.security.SecureRandom +import java.util.concurrent.locks.ReentrantLock +import javax.crypto.Cipher +import javax.crypto.spec.SecretKeySpec + +private val secureRandom = SecureRandom() + +internal actual fun keksRandomBytes(out: ByteArray) { + secureRandom.nextBytes(out) +} + +internal actual fun keksAesEcbEncrypt(key: ByteArray, plaintext: ByteArray): ByteArray? = + try { + val aesCipher = Cipher.getInstance("AES/ECB/NoPadding") + val secretKeySpec = SecretKeySpec(key, "AES") + aesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec) + aesCipher.doFinal(plaintext, 0, plaintext.size) + } catch (e: Exception) { + null + } + +/** + * The desktop shell has no Android log, so the line goes to standard output. Printing is a + * deliberate choice over dropping it: a line that is written is a line that can be read. + */ +internal actual fun keksLogWrite(tag: String, message: String) { + println("$tag: $message") +} + +internal actual class KeksLock actual constructor() { + private val delegate = ReentrantLock() + actual fun lock() = delegate.lock() + actual fun unlock() = delegate.unlock() +} + +actual typealias KeksSecurityException = SecurityException + +actual typealias KeksInvalidParameterException = InvalidParameterException + +actual typealias KeksArrayIndexOutOfBoundsException = ArrayIndexOutOfBoundsException diff --git a/settings.gradle b/settings.gradle index ac3ed7318ee9..cdaa8f50ed06 100644 --- a/settings.gradle +++ b/settings.gradle @@ -29,6 +29,7 @@ include ':plugins:automation' include ':plugins:calibration' include ':plugins:configuration' include ':plugins:constraints' +include ':plugins:libkeks' include ':plugins:main' include ':plugins:sensitivity' include ':plugins:smoothing' From c7a33c3b6782a2c4ff409610ccb670300b8d9b79 Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Wed, 28 Oct 2026 14:37:04 +0100 Subject: [PATCH 02/27] Add the Dexcom ONE+ source to the core enums, database and calibration Groundwork for the Dexcom ONE+ / G7 source plugin, which comes in a later commit. Nothing here changes behaviour for existing users. core/data - SourceSensor.DEXCOM_ONEPLUS_NATIVE("AAPS-DexcomOnePlus"), an own entry for readings from the native ONE+ / G7 plugin. - It is in ADVANCED_FILTERING_SENSORS, like DEXCOM_G6 / DEXCOM_G7: the sensor filters internally, so SMB-always is allowed for it as for G7 read through BYODA. - Sources.DexcomOnePlus for user entries. database - GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE and UserEntry.Sources.DexcomOnePlus, with both converter directions. - Both columns store the enum NAME (Converters.fromSourceSensor / fromSource), so a new entry needs no Room migration and no DATABASE_VERSION change. A test checks the stored name. implementation - UserEntryPresentationHelperImpl: icon and colour for DexcomOnePlus, the same as Dexcom. core/interfaces - NotificationId.CGM_STAGING_AUTO_PROMOTED, appended at the end (the system notification id is the ordinal). - source/CgmWarmupStatus.kt and source/CgmSensorLifecycle.kt: warm-up and second-sensor (pre-soak) status that a BG source can publish without naming a vendor. CgmSensorStatusProvider also exposes stagingSettleRemainingMs, so the overview can show the countdown without its own copy of the settle rule. Only members that the plugin screens or the overview read are there. Calibration cut-off - Calibration.ignoreEntriesBefore(timestamp), default does nothing. A promoted pre-soak sensor gets a session that starts hours before the swap; without the cut, fingersticks paired with the retired sensor would be fitted onto the new one. - LinearCalibrationPlugin stores the cut in a new non-exportable key calibration_entries_valid_from (CalibrationLongKey, 0 = no cut) and fits only entries from max(session start, cut), so a later SENSOR_CHANGE wins over an older cut. The cut only moves forward. A cut more than 5 minutes in the future is logged and ignored, and the cut is removed when the database is cleared. The plugin now extends PluginBaseWithPreferences to own the key. The calibration screen uses the same entries, so it shows the fit that is applied. When nothing calls it, the fit is unchanged. - prefs-schema.txt gets the new key. Tests: new cases in SourceSensorExtensionsTest, SourceSensorExtension- Test, SourcesExtensionTest, ConvertersSourceSensorTest and LinearCalibrationPluginTest (entries before the cut are left out, only newer entries are fitted, no call = same query as before, the cut never moves back, a later session start wins, a cut in the future is ignored, a database reset removes the cut). The full unit-tests CI command passes, and every touched module compiles for iosArm64, including :ios:shell. No test on a real sensor is claimed for this branch. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/src/testFull/resources/prefs-schema.txt | 1 + .../app/aaps/core/data/model/SourceSensor.kt | 3 + .../core/data/model/SourceSensorExtensions.kt | 2 + .../kotlin/app/aaps/core/data/ue/Sources.kt | 1 + .../data/model/SourceSensorExtensionsTest.kt | 8 + .../interfaces/calibration/Calibration.kt | 22 +++ .../notifications/NotificationId.kt | 6 +- .../interfaces/source/CgmSensorLifecycle.kt | 124 +++++++++++++++ .../core/interfaces/source/CgmWarmupStatus.kt | 37 +++++ .../aaps/database/entities/GlucoseValue.kt | 1 + .../app/aaps/database/entities/UserEntry.kt | 1 + .../database/ConvertersSourceSensorTest.kt | 7 + .../converters/SourceSensorExtension.kt | 2 + .../converters/SourcesExtension.kt | 2 + .../converters/SourceSensorExtensionTest.kt | 6 + .../converters/SourcesExtensionTest.kt | 3 + .../UserEntryPresentationHelperImpl.kt | 2 + .../LinearCalibrationPluginTest.kt | 144 +++++++++++++++++- .../compose/CalibrationViewModelTest.kt | 4 +- .../plugins/calibration/CalibrationMath.kt | 6 + .../calibration/LinearCalibrationPlugin.kt | 45 +++++- .../compose/CalibrationViewModel.kt | 11 +- .../calibration/keys/CalibrationLongKey.kt | 19 +++ 23 files changed, 446 insertions(+), 11 deletions(-) create mode 100644 core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt create mode 100644 core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt create mode 100644 plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/keys/CalibrationLongKey.kt diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index b62d8f38f60b..08e6927563ab 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -108,6 +108,7 @@ bolussnooze_dia_divisor|DoubleKey|true boluswizard_percentage|IntKey|true bt_watchdog_last|LongNonKey|true bt_watchdog|BooleanKey|true +calibration_entries_valid_from|CalibrationLongKey|false carbsReqThreshold|IntKey|true carbs_button_increment_1|IntKey|true carbs_button_increment_2|IntKey|true diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt index e7e3f98ddbde..1435bbdaa34b 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensor.kt @@ -16,6 +16,9 @@ enum class SourceSensor(val text: String, val aliases: Set = emptySet()) DEXCOM_UNKNOWN("Dexcom", setOf("AAPS-Dexcom", "Share Follow")), DEXCOM_G6("Dexcom G6", setOf("AAPS-DexcomG6", "G6 Native")), DEXCOM_G7("Dexcom G7", setOf("AAPS-DexcomG7", "G7 Native", "G7")), + + /** Dexcom ONE+ and G7, read directly over Bluetooth by the AAPS Dexcom ONE+ / G7 source plugin. */ + DEXCOM_ONEPLUS_NATIVE("AAPS-DexcomOnePlus"), LIBRE_1( "Libre1", setOf("Other App", "Network libre", "BlueReader", "Transmiter PL", "Blucon", "Tomato", "Rfduino", "LimiTTer", "Bubble", "Atom", "Glimp") diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt index 6eedcffb8d25..8cf2844edf71 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/model/SourceSensorExtensions.kt @@ -20,6 +20,8 @@ private val ADVANCED_FILTERING_SENSORS = setOf( SourceSensor.DEXCOM_UNKNOWN, SourceSensor.DEXCOM_G6, SourceSensor.DEXCOM_G7, + // Dexcom ONE+ / G7 read by the AAPS native plugin. The sensor filters internally, as above. + SourceSensor.DEXCOM_ONEPLUS_NATIVE, SourceSensor.LIBRE_2, SourceSensor.LIBRE_3, SourceSensor.SYAI_TAG, diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt index c161476c2a5a..f3efd93f1979 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/ue/Sources.kt @@ -29,6 +29,7 @@ enum class Sources { BG, //From BG plugin => Add One Source per BG Source for Calibration or Sensor Change Aidex, Dexcom, + DexcomOnePlus, Eversense, Glimp, MM640g, diff --git a/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt b/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt index 3757d506c281..3363929f9d65 100644 --- a/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt +++ b/core/data/src/commonTest/kotlin/app/aaps/core/data/model/SourceSensorExtensionsTest.kt @@ -1,6 +1,7 @@ package app.aaps.core.data.model import kotlin.test.Test +import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -18,6 +19,13 @@ class SourceSensorExtensionsTest { assertTrue(SourceSensor.DEXCOM_G6.advancedFilteringSupported()) assertTrue(SourceSensor.DEXCOM_G7.advancedFilteringSupported()) assertTrue(SourceSensor.DEXCOM_G7.advancedFilteringSupported()) + assertTrue(SourceSensor.DEXCOM_ONEPLUS_NATIVE.advancedFilteringSupported()) + } + + @Test + fun `dexcom one plus native is found by its text`() { + assertEquals(SourceSensor.DEXCOM_ONEPLUS_NATIVE, SourceSensor.fromString("AAPS-DexcomOnePlus")) + assertEquals("AAPS-DexcomOnePlus", SourceSensor.DEXCOM_ONEPLUS_NATIVE.text) } @Test diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt index 41b56e40e7ab..ae1e26b3c96c 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/calibration/Calibration.kt @@ -47,4 +47,26 @@ interface Calibration { * re-evaluates everything. This is a UX hint, not a contract. */ suspend fun checkPreconditions(): AddEntryResult + + /** + * Leave every calibration entry older than [timestamp] (epoch ms) out of the fit from now on. + * + * For a BG source that swaps sensors inside one recorded sensor session: a pre-soaked sensor + * that is made the production sensor gets a session that starts at its own start, hours before + * the swap. Without this cut, fingersticks paired with the retired sensor would be fitted onto + * the new one. + * + * Rules: + * - The cut only moves forward. A [timestamp] that is not later than the current cut is ignored. + * - A [timestamp] in the future (more than a few minutes after now) is ignored and logged, so a + * wrong clock cannot hide every new fingerstick. + * - The fit uses entries from max(session start, cut). So a later SENSOR_CHANGE wins over an + * older cut, and the cut needs no reset at the next sensor. + * - A SENSOR_CHANGE that is entered with a time older than the cut is still clipped by the cut: + * entries between that SENSOR_CHANGE and the cut stay out of the fit. + * - The cut is cleared when the database is cleared. + * + * A plugin that fits nothing has nothing to cut, so the default does nothing. + */ + suspend fun ignoreEntriesBefore(timestamp: Long) {} } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt index 1b3d3b078e6c..0279cb28354c 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 @@ -256,7 +256,11 @@ enum class NotificationId( // and the pairing secrets are plain files next to the data. IMPORTANT, not URGENT: nothing is wrong with // therapy, but a copy of the folder gives everything away, and the user can fix it. Appended at the END for // the same reason as above. - SECRETS_NOT_PROTECTED(IMPORTANT, SYSTEM); + SECRETS_NOT_PROTECTED(IMPORTANT, SYSTEM), + + // A pre-soak sensor (Dexcom ONE+ / G7) was made the production sensor by the app itself, without the + // user pressing the promote button. Appended at the END for the same reason as above. + CGM_STAGING_AUTO_PROMOTED(NORMAL, CGM); companion object { diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt new file mode 100644 index 000000000000..e204d870afec --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorLifecycle.kt @@ -0,0 +1,124 @@ +package app.aaps.core.interfaces.source + +import kotlinx.coroutines.flow.StateFlow + +/** + * Which logical sensor a reading belongs to when a CGM source can overlap a new sensor + * over the outgoing one (pre-soak / staging). + * + * [PRODUCTION] feeds the loop. [STAGING] is warmed in parallel and is never published + * until the user promotes it. + */ +enum class SensorSlot { PRODUCTION, STAGING } + +/** + * State of the optional STAGING slot, for a "new sensor" card. + * + * - [ABSENT] no staging sensor started. + * - [WARMUP] staging sensor warming up / reconnecting (no glucose yet). + * - [SETTLING] warmed up, collecting glucose, not settled long enough to promote. + * - [READY] settled and producing valid glucose → promotion allowed. + */ +enum class StagingState { ABSENT, WARMUP, SETTLING, READY } + +/** + * Generic sensor life info so the UI can show the sensor age and the end of life (time to start a + * new sensor) without naming a vendor. + * + * Times are in ms. Fields are null when the source cannot know them. + */ +data class CgmSensorLifecycle( + val startedAtEpochMs: Long?, + val ageMs: Long?, + val endOfLife: Boolean, +) + +/** + * Proof that the collect-only staging sensor is really producing data. + * + * A pre-soak asks the user to wait many hours on a sensor whose readings are never + * published. Without this, a working sensor and a dead one look the same. + */ +data class CgmStagingEvidence( + val validCount: Int, + val lastValueMgdl: Double?, + val lastValueAtEpochMs: Long?, +) + +/** Why a promote-staging-to-production request was refused. */ +enum class PromotionRejectReason { + STAGING_ABSENT, + STAGING_NOT_SETTLED, + STAGING_NO_VALID_GLUCOSE, + + /** Early promotion asked, but the staging sensor has not sent a recent reading. */ + STAGING_NO_RECENT_GLUCOSE, +} + +/** + * Result of a promote-staging-to-production request. + * + * [OkBoundFailed] and [OkFollowUpFailed] say that the sensors were swapped but a later step + * failed. They are not a silent [Ok], so the user can be told. + */ +sealed interface PromotionResult { + /** Promotion succeeded: the staging sensor now feeds the loop, and older calibration entries are ignored. */ + data object Ok : PromotionResult + + /** + * The exchange already happened and is kept. + * [app.aaps.core.interfaces.calibration.Calibration.ignoreEntriesBefore] threw, so older + * calibration entries were not ignored. Not a rollback, and not a full success. + */ + data object OkBoundFailed : PromotionResult + + /** + * The exchange already happened, older calibration entries are ignored, and a later step + * (loading or resuming the session) threw. + * [productionIdentityPresent] is read from the production store after that throw. + */ + data class OkFollowUpFailed(val productionIdentityPresent: Boolean) : PromotionResult + + /** Promotion refused; [reason] says why (no state changed). */ + data class Rejected(val reason: PromotionRejectReason) : PromotionResult +} + +/** + * Implemented by a [BgSource] that can overlap a second (staging) sensor over production. + * Extends [CgmWarmupProvider]: production warm-up stays the source of truth for the warm-up display. + * + * The STAGING slot is collect-only until [promoteStagingToProduction]. + */ +interface CgmSensorStatusProvider : CgmWarmupProvider { + + /** Production sensor lifecycle, or null when unknown / no sensor. */ + val lifecycle: StateFlow + + /** Staging sensor lifecycle, or null when there is no staging sensor. */ + val stagingLifecycle: StateFlow + + /** Coarse staging slot state for the "new sensor" card. */ + val stagingState: StateFlow + + /** Evidence that staging is collecting, or null when there is no staging sensor. */ + val stagingEvidence: StateFlow + + /** + * Milliseconds left before the staging sensor has settled long enough to be promoted, or null + * when there is no staging sensor or the wait is already over. + * + * The source owns the settle rule, so the UI can show a countdown without knowing it. A UI that + * kept its own copy of the threshold would drift from the rule that really gates promotion. + */ + val stagingSettleRemainingMs: StateFlow + + /** + * Promote the staging sensor to production. This is the only action that changes + * the loop glucose source. + * + * @param allowEarly the user promotes a sensor that has not finished its soak, + * because production stopped early. Soak is skipped, but evidence gates are not: + * staging must have enough valid readings and one recent reading. + */ + suspend fun promoteStagingToProduction(allowEarly: Boolean = false): PromotionResult +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt new file mode 100644 index 000000000000..8adcd1bc5c50 --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmWarmupStatus.kt @@ -0,0 +1,37 @@ +package app.aaps.core.interfaces.source + +import kotlinx.coroutines.flow.StateFlow + +/** + * Generic warm-up / reconnect status of an active CGM source. + * + * A [BgSource] that can report this implements [CgmWarmupProvider]. UI and safety can then + * react to a sensor that is warming up or reconnecting (no glucose yet) without naming a vendor. + * + * @param active true while warm-up or reconnect is in progress. + * @param phase honest phase of the current wait. + * @param remainingMs countdown in ms if the protocol knows it, else null. + * @param endsAtEpochMs wall-clock end in epoch ms if known, else null. + * @param totalMs full warm-up length in ms if known; lets UI draw a determinate ring. + */ +data class CgmWarmupStatus( + val active: Boolean, + val phase: Phase, + val remainingMs: Long?, + val endsAtEpochMs: Long?, + val totalMs: Long? = null, +) { + + enum class Phase { CONNECTING, RECONNECTING, WARMING, PAIRING } +} + +/** + * Implemented by a [BgSource] plugin that can report a generic [CgmWarmupStatus]. + * + * Consumers cast the active BG source: `(activeBgSource as? CgmWarmupProvider)?.warmupStatus`. + */ +interface CgmWarmupProvider { + + /** Current warm-up status, or null when there is nothing to show (READY / IDLE / FAILED). */ + val warmupStatus: StateFlow +} diff --git a/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..244c8f3d1fd7 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 @@ -72,6 +72,7 @@ data class GlucoseValue( DEXCOM_UNKNOWN, DEXCOM_G6, DEXCOM_G7, + DEXCOM_ONEPLUS_NATIVE, LIBRE_1, LIBRE_2, LIBRE_3, diff --git a/database/impl/src/commonMain/kotlin/app/aaps/database/entities/UserEntry.kt b/database/impl/src/commonMain/kotlin/app/aaps/database/entities/UserEntry.kt index efde6692a0d8..1dbd57037ba3 100644 --- a/database/impl/src/commonMain/kotlin/app/aaps/database/entities/UserEntry.kt +++ b/database/impl/src/commonMain/kotlin/app/aaps/database/entities/UserEntry.kt @@ -161,6 +161,7 @@ data class UserEntry( BG, //From BG plugin => Add One Source per BG Source for Calibration or Sensor Change Aidex, Dexcom, + DexcomOnePlus, Eversense, Glimp, MM640g, diff --git a/database/impl/src/commonTest/kotlin/app/aaps/database/ConvertersSourceSensorTest.kt b/database/impl/src/commonTest/kotlin/app/aaps/database/ConvertersSourceSensorTest.kt index 3325889f72ad..7f8cb2a1b6e6 100644 --- a/database/impl/src/commonTest/kotlin/app/aaps/database/ConvertersSourceSensorTest.kt +++ b/database/impl/src/commonTest/kotlin/app/aaps/database/ConvertersSourceSensorTest.kt @@ -26,6 +26,13 @@ class ConvertersSourceSensorTest { } } + @Test + fun `dexcom one plus native is stored by its name`() { + // The column holds the entry name, so a new entry needs no database migration. + assertEquals("DEXCOM_ONEPLUS_NATIVE", converters.fromSourceSensor(GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE)) + assertEquals(GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE, converters.toSourceSensor("DEXCOM_ONEPLUS_NATIVE")) + } + @Test fun `names written before the dexcom entries were merged keep their sensor`() { assertEquals(GlucoseValue.SourceSensor.DEXCOM_UNKNOWN, converters.toSourceSensor("DEXCOM_NATIVE_UNKNOWN")) 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..f05c3524f083 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 @@ -8,6 +8,7 @@ fun GlucoseValue.SourceSensor.fromDb(): SourceSensor = GlucoseValue.SourceSensor.DEXCOM_UNKNOWN -> SourceSensor.DEXCOM_UNKNOWN GlucoseValue.SourceSensor.DEXCOM_G6 -> SourceSensor.DEXCOM_G6 GlucoseValue.SourceSensor.DEXCOM_G7 -> SourceSensor.DEXCOM_G7 + GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE -> SourceSensor.DEXCOM_ONEPLUS_NATIVE GlucoseValue.SourceSensor.LIBRE_1 -> SourceSensor.LIBRE_1 GlucoseValue.SourceSensor.LIBRE_2 -> SourceSensor.LIBRE_2 GlucoseValue.SourceSensor.LIBRE_3 -> SourceSensor.LIBRE_3 @@ -48,6 +49,7 @@ fun SourceSensor.toDb(): GlucoseValue.SourceSensor = SourceSensor.DEXCOM_UNKNOWN -> GlucoseValue.SourceSensor.DEXCOM_UNKNOWN SourceSensor.DEXCOM_G6 -> GlucoseValue.SourceSensor.DEXCOM_G6 SourceSensor.DEXCOM_G7 -> GlucoseValue.SourceSensor.DEXCOM_G7 + SourceSensor.DEXCOM_ONEPLUS_NATIVE -> GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE SourceSensor.LIBRE_1 -> GlucoseValue.SourceSensor.LIBRE_1 SourceSensor.LIBRE_2 -> GlucoseValue.SourceSensor.LIBRE_2 SourceSensor.LIBRE_3 -> GlucoseValue.SourceSensor.LIBRE_3 diff --git a/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourcesExtension.kt b/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourcesExtension.kt index c136667c899c..e8fdb7369fb4 100644 --- a/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourcesExtension.kt +++ b/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/SourcesExtension.kt @@ -33,6 +33,7 @@ fun UserEntry.Sources.fromDb(): Sources = UserEntry.Sources.BG -> Sources.BG UserEntry.Sources.Aidex -> Sources.Aidex UserEntry.Sources.Dexcom -> Sources.Dexcom + UserEntry.Sources.DexcomOnePlus -> Sources.DexcomOnePlus UserEntry.Sources.Eversense -> Sources.Eversense UserEntry.Sources.Glimp -> Sources.Glimp UserEntry.Sources.MM640g -> Sources.MM640g @@ -122,6 +123,7 @@ fun Sources.toDb(): UserEntry.Sources = Sources.BG -> UserEntry.Sources.BG Sources.Aidex -> UserEntry.Sources.Aidex Sources.Dexcom -> UserEntry.Sources.Dexcom + Sources.DexcomOnePlus -> UserEntry.Sources.DexcomOnePlus Sources.Eversense -> UserEntry.Sources.Eversense Sources.Glimp -> UserEntry.Sources.Glimp Sources.MM640g -> UserEntry.Sources.MM640g diff --git a/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourceSensorExtensionTest.kt b/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourceSensorExtensionTest.kt index 7cb11809aa11..cfdbca82dc38 100644 --- a/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourceSensorExtensionTest.kt +++ b/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourceSensorExtensionTest.kt @@ -28,4 +28,10 @@ internal class SourceSensorExtensionTest { assertEquals(GlucoseValue.SourceSensor.UNKNOWN, SourceSensor.UNKNOWN.toDb()) assertEquals(SourceSensor.ZT_PREDICTION, GlucoseValue.SourceSensor.ZT_PREDICTION.fromDb()) } + + @Test + fun `dexcom one plus native maps both ways`() { + assertEquals(GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE, SourceSensor.DEXCOM_ONEPLUS_NATIVE.toDb()) + assertEquals(SourceSensor.DEXCOM_ONEPLUS_NATIVE, GlucoseValue.SourceSensor.DEXCOM_ONEPLUS_NATIVE.fromDb()) + } } diff --git a/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourcesExtensionTest.kt b/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourcesExtensionTest.kt index 02f8f07fd9d8..f8515d2ab13d 100644 --- a/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourcesExtensionTest.kt +++ b/database/persistence/src/commonTest/kotlin/app/aaps/database/persistence/converters/SourcesExtensionTest.kt @@ -33,6 +33,9 @@ internal class SourcesExtensionTest { assertEquals(UserEntry.Sources.Garmin, Sources.Garmin.toDb()) assertEquals(Sources.Garmin, UserEntry.Sources.Garmin.fromDb()) + + assertEquals(UserEntry.Sources.DexcomOnePlus, Sources.DexcomOnePlus.toDb()) + assertEquals(Sources.DexcomOnePlus, UserEntry.Sources.DexcomOnePlus.fromDb()) } @Test diff --git a/implementation/src/commonMain/kotlin/app/aaps/implementation/userEntry/UserEntryPresentationHelperImpl.kt b/implementation/src/commonMain/kotlin/app/aaps/implementation/userEntry/UserEntryPresentationHelperImpl.kt index 28401616e0aa..a586adee80a7 100644 --- a/implementation/src/commonMain/kotlin/app/aaps/implementation/userEntry/UserEntryPresentationHelperImpl.kt +++ b/implementation/src/commonMain/kotlin/app/aaps/implementation/userEntry/UserEntryPresentationHelperImpl.kt @@ -129,6 +129,7 @@ class UserEntryPresentationHelperImpl( Sources.DanaRv2 -> IcPluginDanaI Sources.Database -> Icons.Default.Storage Sources.Dexcom -> IcByoda + Sources.DexcomOnePlus -> IcByoda Sources.DiaconnG8 -> IcPluginDiaconn Sources.EOPatch2 -> IcPluginEopatch Sources.Equil -> IcPluginEquil @@ -217,6 +218,7 @@ class UserEntryPresentationHelperImpl( Sources.DanaRv2 -> ElementType.PUMP.color() Sources.Database -> ElementType.AAPS.color() Sources.Dexcom -> ElementType.CGM_DEX.color() + Sources.DexcomOnePlus -> ElementType.CGM_DEX.color() Sources.DiaconnG8 -> ElementType.PUMP.color() Sources.EOPatch2 -> ElementType.PUMP.color() Sources.Equil -> ElementType.PUMP.color() diff --git a/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/LinearCalibrationPluginTest.kt b/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/LinearCalibrationPluginTest.kt index d02725aec027..43b6593eaf9e 100644 --- a/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/LinearCalibrationPluginTest.kt +++ b/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/LinearCalibrationPluginTest.kt @@ -19,9 +19,13 @@ import app.aaps.core.interfaces.notifications.NotificationId import app.aaps.core.interfaces.notifications.NotificationLevel import app.aaps.core.interfaces.notifications.NotificationManager import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.calibration.keys.CalibrationLongKey import app.aaps.shared.tests.TestBase import app.aaps.shared.tests.generatedTextResolver import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test @@ -29,8 +33,10 @@ import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doAnswer import org.mockito.kotlin.eq import org.mockito.kotlin.never +import org.mockito.kotlin.timeout import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -42,6 +48,10 @@ class LinearCalibrationPluginTest : TestBase() { @Mock lateinit var notificationManager: NotificationManager @Mock lateinit var glucoseStatusProvider: GlucoseStatusProvider @Mock lateinit var config: Config + @Mock lateinit var preferences: Preferences + + /** What the [preferences] mock holds for [CalibrationLongKey.EntriesValidFrom]. */ + private var storedCut = 0L private lateinit var plugin: LinearCalibrationPlugin @@ -57,8 +67,11 @@ class LinearCalibrationPluginTest : TestBase() { whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(defaultSessionStart)) whenever(persistenceLayer.getTherapyEventDataFromToTime(any(), any())).thenReturn(emptyList()) whenever(persistenceLayer.getValidCalibrationEntriesSince(any())).thenReturn(emptyList()) + storedCut = 0L + whenever(preferences.get(CalibrationLongKey.EntriesValidFrom)).thenAnswer { storedCut } + doAnswer { storedCut = it.getArgument(1); null }.whenever(preferences).put(eq(CalibrationLongKey.EntriesValidFrom), any()) plugin = LinearCalibrationPlugin( - aapsLogger, rh, dateUtil, persistenceLayer, notificationManager, glucoseStatusProvider, rxBus, config + aapsLogger, rh, dateUtil, persistenceLayer, notificationManager, glucoseStatusProvider, rxBus, config, preferences ) } @@ -417,6 +430,135 @@ class LinearCalibrationPluginTest : TestBase() { // ------------ helpers ------------ + // ------------ ignoreEntriesBefore() ------------ + + /** Makes the database answer like the real query: valid entries at or after `from`. */ + private suspend fun storeEntries(entries: List) { + whenever(persistenceLayer.getValidCalibrationEntriesSince(any())).thenAnswer { call -> + val from = call.getArgument(0) + entries.filter { it.timestamp >= from } + } + } + + @Test + fun calibrate_neverCut_fitsEveryEntryOfTheSession() = runTest { + // Without a call to ignoreEntriesBefore the plugin works as before: it reads from the session start. + storeEntries( + listOf( + calEntry(sensor = 100.0, fs = 110.0, timestamp = now - T.hours(6).msecs()), + calEntry(sensor = 200.0, fs = 220.0, timestamp = now - T.hours(5).msecs()) + ) + ) + val data = bucketed(listOf(now to 150.0)) + plugin.calibrate(data, CalibrationContext.NONE) + verify(persistenceLayer).getValidCalibrationEntriesSince(defaultSessionStart) + assertThat(data[0].calibrated!!).isWithin(0.01).of(165.0) + } + + @Test + fun calibrate_afterCut_leavesOlderEntriesOutOfTheFit() = runTest { + // Two fingersticks paired with the retired sensor, inside the same recorded session. + storeEntries( + listOf( + calEntry(sensor = 100.0, fs = 110.0, timestamp = now - T.hours(6).msecs()), + calEntry(sensor = 200.0, fs = 220.0, timestamp = now - T.hours(5).msecs()) + ) + ) + plugin.ignoreEntriesBefore(now - T.hours(1).msecs()) + val data = bucketed(listOf(now to 150.0)) + plugin.calibrate(data, CalibrationContext.NONE) + verify(persistenceLayer).getValidCalibrationEntriesSince(now - T.hours(1).msecs()) + // Nothing is left to fit, so the reading is not changed. + assertThat(data[0].calibrated).isNull() + } + + @Test + fun calibrate_afterCut_fitsOnlyTheNewerEntries() = runTest { + val cut = now - T.hours(1).msecs() + storeEntries( + listOf( + // Retired sensor: would give slope 1.1. + calEntry(sensor = 100.0, fs = 110.0, timestamp = cut - T.hours(3).msecs()), + calEntry(sensor = 200.0, fs = 220.0, timestamp = cut - T.hours(2).msecs()), + // New sensor: reads 10 mg/dL low, slope 1. + calEntry(sensor = 100.0, fs = 110.0, timestamp = cut + T.mins(10).msecs()), + calEntry(sensor = 200.0, fs = 210.0, timestamp = cut + T.mins(20).msecs()) + ) + ) + plugin.ignoreEntriesBefore(cut) + val data = bucketed(listOf(now to 150.0)) + plugin.calibrate(data, CalibrationContext.NONE) + assertThat(data[0].calibrated!!).isWithin(0.01).of(160.0) + } + + @Test + fun ignoreEntriesBefore_storesTheCut() = runTest { + plugin.ignoreEntriesBefore(now) + verify(preferences).put(CalibrationLongKey.EntriesValidFrom, now) + } + + @Test + fun ignoreEntriesBefore_neverMovesTheCutBack() = runTest { + plugin.ignoreEntriesBefore(now) + plugin.ignoreEntriesBefore(now) + plugin.ignoreEntriesBefore(now - 1L) + verify(preferences).put(eq(CalibrationLongKey.EntriesValidFrom), any()) + assertThat(storedCut).isEqualTo(now) + } + + @Test + fun ignoreEntriesBefore_cutBeforeSessionStart_changesNothing() = runTest { + // A cut older than the session start does not widen the window: the session start still wins. + plugin.ignoreEntriesBefore(defaultSessionStart - T.hours(1).msecs()) + plugin.calibrate(bucketed(listOf(now to 150.0)), CalibrationContext.NONE) + verify(persistenceLayer).getValidCalibrationEntriesSince(defaultSessionStart) + } + + @Test + fun ignoreEntriesBefore_laterSessionStart_winsOverOlderCut() = runTest { + // The cut was set for the last sensor. A new SENSOR_CHANGE after it starts the window again. + val cut = now - T.hours(6).msecs() + val newSessionStart = now - T.hours(3).msecs() + plugin.ignoreEntriesBefore(cut) + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(newSessionStart)) + plugin.calibrate(bucketed(listOf(now to 150.0)), CalibrationContext.NONE) + verify(persistenceLayer).getValidCalibrationEntriesSince(newSessionStart) + } + + @Test + fun ignoreEntriesBefore_cutInTheFuture_isIgnored() = runTest { + plugin.ignoreEntriesBefore(now + T.hours(1).msecs()) + verify(preferences, never()).put(eq(CalibrationLongKey.EntriesValidFrom), any()) + assertThat(storedCut).isEqualTo(0L) + plugin.calibrate(bucketed(listOf(now to 150.0)), CalibrationContext.NONE) + verify(persistenceLayer).getValidCalibrationEntriesSince(defaultSessionStart) + } + + @Test + fun ignoreEntriesBefore_cutSlightlyAhead_isAccepted() = runTest { + // A small clock step between the caller and dateUtil is not a bad value. + plugin.ignoreEntriesBefore(now + T.mins(1).msecs()) + assertThat(storedCut).isEqualTo(now + T.mins(1).msecs()) + } + + @Test + fun databaseCleared_removesTheCut() = runTest { + plugin.ignoreEntriesBefore(now) + whenever(persistenceLayer.observeChanges(CAL::class)).thenReturn(emptyFlow()) + // Emits once when collected, like a "Reset databases" right after start. + whenever(persistenceLayer.databaseClearedFlow).thenReturn(flowOf(Unit)) + plugin.onStart() + try { + // The plugin collects on its own dispatcher, so wait for it with a real-time timeout. + verify(preferences, timeout(5_000)).remove(CalibrationLongKey.EntriesValidFrom) + } finally { + plugin.onStop() + } + } + + private fun calEntry(sensor: Double, fs: Double, timestamp: Long): CAL = + CAL(id = 0L, timestamp = timestamp, fingerstickMgdl = fs, sensorMgdlAtPairing = sensor) + private fun value(ts: Long, v: Double) = InMemoryGlucoseValue( timestamp = ts, value = v, diff --git a/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModelTest.kt b/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModelTest.kt index ab83bbea24b6..3add5db94dc8 100644 --- a/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModelTest.kt +++ b/plugins/calibration/src/androidHostTest/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModelTest.kt @@ -10,6 +10,7 @@ import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.resources.TextResolver import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -50,6 +51,7 @@ internal class CalibrationViewModelTest { @Mock private lateinit var rxBus: RxBus @Mock private lateinit var config: Config @Mock private lateinit var batchExecutor: BatchExecutor + @Mock private lateinit var preferences: Preferences @BeforeEach fun setUp() { @@ -68,7 +70,7 @@ internal class CalibrationViewModelTest { } private fun viewModel() = - CalibrationViewModel(persistenceLayer, profileUtil, dateUtil, rh, rxBus, config, batchExecutor) + CalibrationViewModel(persistenceLayer, profileUtil, dateUtil, rh, rxBus, config, batchExecutor, preferences) @Test fun uiState_hasEmptySessionDefaults() { diff --git a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/CalibrationMath.kt b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/CalibrationMath.kt index 009f82a922af..afc0c0c6786a 100644 --- a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/CalibrationMath.kt +++ b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/CalibrationMath.kt @@ -63,6 +63,12 @@ data class CalibrationFit( val isApplicable: Boolean get() = slopeInRange && correctionInRange } +/** + * First timestamp of the entries the fit may use: the session start, or the later cut set by + * [app.aaps.core.interfaces.calibration.Calibration.ignoreEntriesBefore] (0 when it was never set). + */ +internal fun fitStart(sessionStart: Long, entriesValidFrom: Long): Long = maxOf(sessionStart, entriesValidFrom) + /** * Time-decay weight (0..1] for an entry of age `now - timestamp`, matching the fit's τ. * diff --git a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/LinearCalibrationPlugin.kt b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/LinearCalibrationPlugin.kt index 1a147c412c92..9f92affc65af 100644 --- a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/LinearCalibrationPlugin.kt +++ b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/LinearCalibrationPlugin.kt @@ -22,13 +22,16 @@ import app.aaps.core.interfaces.notifications.NotificationAction import app.aaps.core.interfaces.notifications.NotificationId import app.aaps.core.interfaces.notifications.NotificationManager import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginBaseWithPreferences import app.aaps.core.interfaces.plugin.PluginDescription import app.aaps.core.interfaces.resources.TextResolver import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventCalibrationChanged import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.compose.icons.IcCalibration import app.aaps.plugins.calibration.compose.CalibrationComposeContent +import app.aaps.plugins.calibration.keys.CalibrationLongKey import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesIntoMap import dev.zacsweers.metro.Inject @@ -57,15 +60,20 @@ class LinearCalibrationPlugin( notificationManager: NotificationManager, private val glucoseStatusProvider: GlucoseStatusProvider, private val rxBus: RxBus, - private val config: Config -) : PluginBase( - PluginDescription() + private val config: Config, + preferences: Preferences +) : PluginBaseWithPreferences( + pluginDescription = PluginDescription() .mainType(PluginType.CALIBRATION) .icon(IcCalibration) .pluginName(CalibrationStrings.linear_calibration_name) .description(CalibrationStrings.description_linear_calibration) .composeContent { CalibrationComposeContent() }, - aapsLogger, rh, notificationManager + ownPreferences = CalibrationLongKey.entries, + aapsLogger = aapsLogger, + rh = rh, + preferences = preferences, + notificationManager = notificationManager ), Calibration { private var scope: CoroutineScope? = null @@ -85,6 +93,8 @@ class LinearCalibrationPlugin( // change-tracking flow above — observe the dedicated cleared signal so the graph recomputes. scope?.launch { persistenceLayer.databaseClearedFlow.collect { + // The cut belongs to the data that was just wiped. Kept, it would hide new entries. + preferences.remove(CalibrationLongKey.EntriesValidFrom) rxBus.send(EventCalibrationChanged()) } } @@ -121,7 +131,7 @@ class LinearCalibrationPlugin( return data } - val entries = persistenceLayer.getValidCalibrationEntriesSince(sessionStart) + val entries = entriesForFit(sessionStart) val fit = fitLinearCalibration(entries, now) if (fit == null) { aapsLogger.debug(LTag.GLUCOSE) { "LinearCalibration: ${entries.size} entries (<$MIN_ENTRIES_FOR_FIT), identity" } @@ -163,7 +173,7 @@ class LinearCalibrationPlugin( // fit is in place, so its magnitude scales with slope. Scale the raw-units threshold // by the active slope so a sensor rate of e.g. 5 mg/dL/5min (the "stable enough" // bar) is treated identically whether or not calibration is multiplying the signal. - val activeFit = fitLinearCalibration(persistenceLayer.getValidCalibrationEntriesSince(sessionStart), timestamp) + val activeFit = fitLinearCalibration(entriesForFit(sessionStart), timestamp) val effectiveThreshold = if (activeFit != null && activeFit.isApplicable) { DELTA_GATE_MGDL_PER_5MIN * activeFit.slope } else { @@ -198,6 +208,25 @@ class LinearCalibrationPlugin( return AddEntryResult.Accepted } + override suspend fun ignoreEntriesBefore(timestamp: Long) { + val now = dateUtil.now() + if (timestamp > now + MAX_CUT_AHEAD_MS) { + // A cut in the future would leave every new fingerstick out of the fit until that time. + aapsLogger.warn(LTag.GLUCOSE, "LinearCalibration: cut $timestamp is in the future (now $now), ignored") + return + } + val current = preferences.get(CalibrationLongKey.EntriesValidFrom) + if (timestamp <= current) return + preferences.put(CalibrationLongKey.EntriesValidFrom, timestamp) + aapsLogger.info(LTag.GLUCOSE, "LinearCalibration: entries before $timestamp are no longer fitted") + // The fit changed, so the BG graph must be computed again. + rxBus.send(EventCalibrationChanged()) + } + + /** The entries of the session that the fit may use. See [ignoreEntriesBefore]. */ + private suspend fun entriesForFit(sessionStart: Long): List = + persistenceLayer.getValidCalibrationEntriesSince(fitStart(sessionStart, preferences.get(CalibrationLongKey.EntriesValidFrom))) + private suspend fun detectAndNotifyGap(data: List, sessionStart: Long?) { // Only the master asks. Its button writes a sensor change, and on a client that would stay on the client. // The master sees the same gap and posts the same notice. A client also sees gaps when its sync is late. @@ -259,5 +288,9 @@ class LinearCalibrationPlugin( const val DELTA_GATE_MGDL_PER_5MIN = 5.0 const val SENSOR_CHANGE_PROXIMITY_MS = 60L * 60L * 1000L const val PAIR_LOOKBACK_MS = 10L * 60L * 1000L + + // How far after now a cut from ignoreEntriesBefore may be. Allows small clock steps between + // the caller and dateUtil; anything later is treated as a bad value. + const val MAX_CUT_AHEAD_MS = 5L * 60L * 1000L } } diff --git a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModel.kt b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModel.kt index 5cb1acea1ef9..b8cf42c3972b 100644 --- a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModel.kt +++ b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/compose/CalibrationViewModel.kt @@ -16,8 +16,11 @@ import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.resources.TextResolver import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.ui.clientcontrol.RecordRemoval import app.aaps.plugins.calibration.fitLinearCalibration +import app.aaps.plugins.calibration.fitStart +import app.aaps.plugins.calibration.keys.CalibrationLongKey import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesIntoMap import dev.zacsweers.metro.Inject @@ -52,7 +55,8 @@ class CalibrationViewModel( rh: TextResolver, rxBus: RxBus, config: Config, - batchExecutor: BatchExecutor + batchExecutor: BatchExecutor, + private val preferences: Preferences ) : ViewModel() { private val _uiState = MutableStateFlow(CalibrationUiState()) @@ -80,7 +84,10 @@ class CalibrationViewModel( private suspend fun recomputeSuspend() { val now = dateUtil.now() val sessionStart = persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)?.timestamp - val entries = if (sessionStart != null) persistenceLayer.getValidCalibrationEntriesSince(sessionStart) else emptyList() + // Same entries as the fit in LinearCalibrationPlugin, so the screen shows the fit that is applied. + val entries = if (sessionStart != null) { + persistenceLayer.getValidCalibrationEntriesSince(fitStart(sessionStart, preferences.get(CalibrationLongKey.EntriesValidFrom))) + } else emptyList() val warmUpEndsAt = sessionStart?.plus(WARM_UP_DURATION_MS) val isInWarmUp = warmUpEndsAt != null && now < warmUpEndsAt _uiState.update { previous -> diff --git a/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/keys/CalibrationLongKey.kt b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/keys/CalibrationLongKey.kt new file mode 100644 index 000000000000..5c1ebcb9eb3b --- /dev/null +++ b/plugins/calibration/src/commonMain/kotlin/app/aaps/plugins/calibration/keys/CalibrationLongKey.kt @@ -0,0 +1,19 @@ +package app.aaps.plugins.calibration.keys + +import app.aaps.core.keys.interfaces.LongNonPreferenceKey + +enum class CalibrationLongKey( + override val key: String, + override val defaultValue: Long, + override val exportable: Boolean = true +) : LongNonPreferenceKey { + + /** + * Calibration entries older than this (epoch ms) are left out of the fit. Set by + * [app.aaps.core.interfaces.calibration.Calibration.ignoreEntriesBefore]; 0 means no cut. + * + * Not exportable: it belongs to the sensor running on this phone. An imported value from + * another phone, or from an older backup, would hide or bring back the wrong entries. + */ + EntriesValidFrom("calibration_entries_valid_from", 0L, exportable = false) +} From 8ac6e785063ea99601014c2285ae66f00d788ad0 Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Wed, 28 Oct 2026 14:53:32 +0100 Subject: [PATCH 03/27] dexcom_oneplus: add the native Dexcom ONE+ / G7 BLE driver New module :plugins:dexcom_oneplus. It talks to a Dexcom ONE+ / G7 sensor over Bluetooth LE without the Dexcom app: scan, connect, KEKS (J-PAKE) authentication through :plugins:libkeks, then the Control loop that asks for glucose (EGV) and pulls missed readings (backfill). Nothing uses it yet; the source plugin that feeds the loop comes in a later commit. Packages (app.aaps.plugins.dexcomoneplus) - root: the driver facade OnePlusCgmDriver, the real driver, the two driver slots (production and pre-soak sensor), logging, platform port. - gatt, scan: GATT client and LE scanner. The Android scanner keeps a scan start budget (the OS silently drops scans above 5 starts in 30 s). - session: KEKS auth, EGV and backfill sessions, reconnect cycle policy, MAC arbiter (one sensor, one owner), CPU lease (wake lock). - parse: message encoders and decoders, including the display-only flag check that keeps a value echoed after a calibration away from the loop. - identity, oem, reconnect, warmup: sensor identity and store, per-phone BLE defaults, retry policy, warm-up clock. The reconnect and radio hardening is kept as it is: wake lock through the pre-connect settle, scan quota, warm-up retry budget, INDICATE before NOTIFY on Control, no HIGH connection priority (peer status 19), blind connect and stale MAC rules, audio link logging, OEM profiles. Provenance: parts are derived from xDrip (pin 1e86d9a2a5, tag 2026.07.15) and Juggluco (pin 5297da7c23, version 10.9.6, GPL-3.0-or-later). NOTICE lists every derived file. Left out on purpose - iOS: Android is the only target. The protocol code stays in commonMain without Android imports, so iOS targets can be added later with an iosMain only. The module is in the PLUGIN_LIBRARIES list of :appshell because it has no Apple variant. - Radio lease (back off while a pump is set up): nothing ever asked for it, so setRadioBackOff, setLowPower and the scan budget hold are gone. - Sending a fingerstick calibration to the sensor (opcode 0x34): it writes something permanent into the sensor, so it has its own commit later in this series ("send fingerstick calibrations to the sensor"). Reading the calibration state from glucose packets is here. Notes - AapsLock.withLock has no callsInPlace contract, so three places in OnePlusCgmDriverReal return their values from the lock block instead of assigning vals inside it. - The wake lock tag is AndroidAPS::DexcomOnePlusAuth. - There is no placeholder GATT client or auth that only throws: the driver always gets the real ones. - Manifest: BLUETOOTH_CONNECT, and BLUETOOTH_SCAN with neverForLocation, the same as the app and the pump drivers. The old BLUETOOTH and BLUETOOTH_ADMIN are not declared: the app needs Android 12 or newer. - Logs: a MAC shows only its last 5 characters and a sensor serial only its last 3. Key bytes are never logged, only their length. Lines written for every glucose packet (EGV, backfill sample, Control timeout, transmitter time, EGV request) are debug, not info. Tests: 175 JUnit tests in testAndroidHostTest, including the commonTest classes, which run there with Android as the only target. They are unit tests only; no test on a real sensor is claimed for this branch. RawPreferenceStoreScanTest gets a toDo entry for the small Android adapter that opens the sensor store file. The file holds the sensor identity and pairing key, one plain SharedPreferences file per sensor slot. Moving it to the encrypted settings store is a follow-up, with a migration from the old file. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../aaps/keys/RawPreferenceStoreScanTest.kt | 9 + appshell/build.gradle.kts | 2 + plugins/dexcom_oneplus/NOTICE | 153 +++ plugins/dexcom_oneplus/build.gradle.kts | 76 ++ .../OnePlusCgmDriverResumePolicyTest.kt | 48 + .../OnePlusCgmDriverSessionReleaseTest.kt | 81 ++ .../dexcomoneplus/OnePlusCgmDriversTest.kt | 108 ++ .../gatt/OnePlusAudioLinkStateTest.kt | 27 + .../identity/OnePlusAdvCandidateTest.kt | 137 +++ .../OnePlusGs1ApplicatorParserTest.kt | 41 + .../identity/OnePlusSensorStoreTest.kt | 101 ++ .../oem/DeviceProfileRegistryTest.kt | 86 ++ .../parse/OnePlusBackFillMessageTest.kt | 71 ++ .../parse/OnePlusCalibrationMapperTest.kt | 26 + .../parse/OnePlusGlucoseParserEgvTest.kt | 64 + .../parse/OnePlusGlucoseParserTest.kt | 198 +++ .../parse/OnePlusSessionStartMessageTest.kt | 65 + .../parse/OnePlusSessionStopMessageTest.kt | 41 + .../OnePlusTransmitterTimeMessageTest.kt | 55 + .../reconnect/OemAwareReconnectPolicyTest.kt | 39 + .../scan/OnePlusBleScannerAndroidTest.kt | 207 ++++ .../scan/OnePlusScanBudgetTest.kt | 120 ++ .../session/OnePlusAuthStatusRxTest.kt | 45 + .../OnePlusBleSessionCyclePolicyTest.kt | 403 +++++++ .../session/OnePlusMacArbiterTest.kt | 86 ++ .../session/OnePlusSessionStartPolicyTest.kt | 66 + .../session/OnePlusSessionStartTest.kt | 30 + .../warmup/OnePlusWarmupClockTest.kt | 53 + .../src/androidMain/AndroidManifest.xml | 11 + .../dexcomoneplus/OnePlusAndroidPlatform.kt | 44 + .../OnePlusBleExecutorAndroid.kt | 29 + .../dexcomoneplus/OnePlusElapsedAndroid.kt | 5 + .../dexcomoneplus/OnePlusLogAndroid.kt | 19 + .../dexcomoneplus/OnePlusSleepAndroid.kt | 10 + .../gatt/OnePlusAudioLinkState.kt | 55 + .../gatt/OnePlusGattClientAndroid.kt | 1062 +++++++++++++++++ .../dexcomoneplus/gatt/OnePlusGattUuids.kt | 28 + .../identity/OnePlusSensorPrefsAndroid.kt | 66 + .../oem/OnePlusDeviceInfoAndroid.kt | 13 + .../scan/OnePlusBleScannerAndroid.kt | 478 ++++++++ .../session/OnePlusAndroidCpuLease.kt | 39 + .../dexcomoneplus/OnePlusBleExecutor.kt | 36 + .../plugins/dexcomoneplus/OnePlusCgmDriver.kt | 50 + .../dexcomoneplus/OnePlusCgmDriverReal.kt | 637 ++++++++++ .../dexcomoneplus/OnePlusCgmDriverStub.kt | 96 ++ .../dexcomoneplus/OnePlusCgmDrivers.kt | 110 ++ .../plugins/dexcomoneplus/OnePlusElapsed.kt | 15 + .../dexcomoneplus/OnePlusGlucoseSample.kt | 20 + .../dexcomoneplus/OnePlusGlucoseWatcher.kt | 11 + .../aaps/plugins/dexcomoneplus/OnePlusLog.kt | 43 + .../dexcomoneplus/OnePlusLogMarkers.kt | 28 + .../plugins/dexcomoneplus/OnePlusPlatform.kt | 44 + .../plugins/dexcomoneplus/OnePlusSleep.kt | 14 + .../dexcomoneplus/OnePlusWarmupState.kt | 39 + .../gatt/OnePlusBluetoothUuids.kt | 34 + .../dexcomoneplus/gatt/OnePlusGattClient.kt | 96 ++ .../dexcomoneplus/gatt/OnePlusKeksNotify.kt | 25 + .../identity/OnePlusAdvCandidate.kt | 137 +++ .../identity/OnePlusGs1ApplicatorParser.kt | 104 ++ .../identity/OnePlusSensorIdentity.kt | 41 + .../identity/OnePlusSensorPrefs.kt | 50 + .../identity/OnePlusSensorStore.kt | 300 +++++ .../oem/DeviceProfileRegistry.kt | 162 +++ .../dexcomoneplus/oem/OemDeviceProfile.kt | 73 ++ .../dexcomoneplus/oem/OnePlusDeviceInfo.kt | 15 + .../parse/OnePlusBackFillControlRx.kt | 15 + .../parse/OnePlusBackFillStream.kt | 95 ++ .../dexcomoneplus/parse/OnePlusBackFillTx.kt | 23 + .../dexcomoneplus/parse/OnePlusBytes.kt | 114 ++ .../parse/OnePlusCalibrationState.kt | 77 ++ .../dexcomoneplus/parse/OnePlusEGlucoseTx.kt | 24 + .../dexcomoneplus/parse/OnePlusFastCrc16.kt | 43 + .../parse/OnePlusGlucoseParser.kt | 218 ++++ .../parse/OnePlusSessionStartRx.kt | 65 + .../parse/OnePlusSessionStartTx.kt | 31 + .../parse/OnePlusSessionStopRx.kt | 45 + .../parse/OnePlusSessionStopTx.kt | 27 + .../parse/OnePlusTransmitterTimeRx.kt | 57 + .../parse/OnePlusTransmitterTimeTx.kt | 23 + .../reconnect/OnePlusReconnectPolicy.kt | 38 + .../dexcomoneplus/scan/OnePlusBleScanner.kt | 75 ++ .../dexcomoneplus/scan/OnePlusScanBudget.kt | 120 ++ .../dexcomoneplus/scan/OnePlusScanResult.kt | 21 + .../scan/OnePlusScanSelection.kt | 45 + .../session/OnePlusAuthStatusRx.kt | 34 + .../dexcomoneplus/session/OnePlusBackfill.kt | 17 + .../session/OnePlusBackfillSession.kt | 137 +++ .../session/OnePlusBleSession.kt | 1035 ++++++++++++++++ .../dexcomoneplus/session/OnePlusCpuLease.kt | 30 + .../session/OnePlusEgvSession.kt | 409 +++++++ .../OnePlusInvalidShortPairingCodes.kt | 44 + .../session/OnePlusKeksGuideCerts.kt | 82 ++ .../session/OnePlusMacArbiter.kt | 88 ++ .../session/OnePlusSessionAuth.kt | 47 + .../session/OnePlusSessionAuthKeks.kt | 381 ++++++ .../session/OnePlusSessionStart.kt | 32 + .../session/OnePlusSessionStartPolicy.kt | 32 + .../warmup/OnePlusWarmupClock.kt | 43 + .../dexcomoneplus/OnePlusBleExecutorTest.kt | 115 ++ .../OnePlusCgmDriverRealSharedTest.kt | 181 +++ .../dexcomoneplus/parse/OnePlusBytesTest.kt | 130 ++ .../session/OnePlusKeksGuideCertsTest.kt | 84 ++ settings.gradle | 1 + 103 files changed, 10555 insertions(+) create mode 100644 plugins/dexcom_oneplus/NOTICE create mode 100644 plugins/dexcom_oneplus/build.gradle.kts create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverResumePolicyTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverSessionReleaseTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriversTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkStateTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParserTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistryTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillMessageTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationMapperTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserEgvTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartMessageTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopMessageTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeMessageTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OemAwareReconnectPolicyTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudgetTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRxTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionCyclePolicyTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiterTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicyTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClockTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusAndroidPlatform.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsedAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleepAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkState.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClientAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattUuids.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefsAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfoAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAndroidCpuLease.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutor.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverStub.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsed.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseSample.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseWatcher.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLog.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogMarkers.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusPlatform.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleep.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusWarmupState.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusBluetoothUuids.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClient.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusKeksNotify.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParser.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorIdentity.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefs.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistry.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OemDeviceProfile.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfo.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillControlRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillStream.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillTx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytes.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationState.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusEGlucoseTx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusFastCrc16.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParser.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartTx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopTx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeTx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OnePlusReconnectPolicy.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScanner.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudget.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanSelection.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfill.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCpuLease.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusInvalidShortPairingCodes.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCerts.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiter.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStart.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicy.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClock.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCertsTest.kt diff --git a/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt b/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt index 7cccc8c7b676..9895d16da618 100644 --- a/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt +++ b/app/src/testFull/kotlin/app/aaps/keys/RawPreferenceStoreScanTest.kt @@ -114,6 +114,15 @@ class RawPreferenceStoreScanTest { "pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/Delegates.kt" to "ComboV2, same migration", "pump/insight/src/main/kotlin/app/aaps/pump/insight/utils/PairingDataStorage.kt" to "Insight pump pairing. Open question 6.2: moving it into registered keys would make 'restore pump configuration' work after a reinstall, but it would also put a pump secret in the export file. Needs an answer before it moves.", + // Added with the Dexcom ONE+ / G7 driver. This file stores the driver's own sensor state: the + // sensor identity and the pairing key, in one preference file per sensor slot. It is in this + // list and not in `allowed` because it fits none of the reasons there: registered composed + // keys (one argument per sensor slot) could hold it. It can move to registered keys later, + // with a migration that copies the values from the old file. + // The store itself is shared code and never touches the file. This small Android adapter is the + // only place that opens it. + "plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefsAndroid.kt" to + "Dexcom ONE+ / G7 sensor identity, including the pairing key. Live device state like the Insight pairing above, so it needs a migration, not a removal. 14 keys, in one file per sensor slot (production or pre-soak sensor), so the move needs registered per-slot keys plus a migration that copies from the old file and keeps it until the move is confirmed on a real sensor. Whether the keys are exportable (a sensor would then survive a change of phone, but the pairing key would be in the export file) needs an answer before it moves.", ) @Test diff --git a/appshell/build.gradle.kts b/appshell/build.gradle.kts index 7e67007082ab..e5a24aafd71a 100644 --- a/appshell/build.gradle.kts +++ b/appshell/build.gradle.kts @@ -16,6 +16,8 @@ plugins { val PLUGIN_LIBRARIES = setOf( // KEKS authentication for Dexcom ONE+ / G7 (Android and JVM only). ":plugins:libkeks", + // The Dexcom ONE+ / G7 BLE driver (Android only). The plugin itself is in :plugins:source. + ":plugins:dexcom_oneplus", ) /** diff --git a/plugins/dexcom_oneplus/NOTICE b/plugins/dexcom_oneplus/NOTICE new file mode 100644 index 000000000000..5f88a217babb --- /dev/null +++ b/plugins/dexcom_oneplus/NOTICE @@ -0,0 +1,153 @@ +THIRD-PARTY / UPSTREAM NOTICE +============================= +Module: :plugins:dexcom_oneplus (Dexcom ONE+ / G7 native CGM driver) + +Status: Current NOTICE for ported / derived sources (update when new files land). + Do not invent copyright holders; unknowns are marked explicitly. + +This AndroidAPS tree is licensed under the GNU Affero General +Public License v3 (see repository root LICENSE.txt). Portions of this module are +derived from xDrip+ (GNU GPL v3) AND from Juggluco (GNU GPL v3). Combined +distribution of this app remains under AGPL-3 with GPL-3 obligations respected +for the derived parts (GPLv3 §13 AGPL compatibility). + +Note: several files are co-derived from BOTH xDrip and Juggluco and are listed +in both sections 1 and 2 below. + + +------------------------------------------------------------------------------- +1. xDrip+ (NightscoutFoundation) — messages / auth / Ob1 control flow +------------------------------------------------------------------------------- + +Project: xDrip+ / Nightscout xDrip +Repository: https://github.com/NightscoutFoundation/xDrip +License: GNU General Public License v3.0 (file LICENSE in that repository) +Homepage: https://jamorham.github.io/#xdrip-plus +Pin: + Tag: 2026.07.15 + Commit: 1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f + URL: https://github.com/NightscoutFoundation/xDrip/commit/1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f +Related historical repo (same lineage; prefer NightscoutFoundation for pins): + https://github.com/jamorham/xDrip-plus + +Copyright holders: + UNKNOWN as complete legal © lines — many upstream .java files carry no formal + "Copyright (C) YEAR NAME" header. Author / credit markers observed upstream: + - "JamOrHam" / "jamorham" (widespread on Ob1, g5model, libkeks, plugin) + - "joeginley" (comment on BluetoothServices UUID definitions) + README publisher mention: "Published by the Nightscout Foundation" + (community / publishing umbrella — not treated here as a verified sole © owner). + +Translated to Kotlin, not a verbatim copy (separate module, own NOTICE + +per-file SPDX headers that keep the pin): + - :plugins:libkeks (jamorham.keks + IPluginDA). The Java sources at the pin + were translated to Kotlin Multiplatform; plugins/libkeks/NOTICE lists every + change and the golden tests that check the translation. + +Ported into original Kotlin (wire format / algorithm identical, text rewritten): + gatt/OnePlusBluetoothUuids.kt ← BluetoothServices.java UUIDs + gatt/OnePlusKeksNotify.kt ← Ob1 Auth/ExtraData notify routing + parse/OnePlusFastCrc16.kt ← FastCRC16.java + parse/OnePlusGlucoseParser.kt ← EGlucoseRxMessage / EGlucoseRxMessage2 + parse/OnePlusCalibrationState.kt ← CalibrationState + parse/OnePlusEGlucoseTx.kt ← EGlucoseTxMessage / BaseMessage.init + parse/OnePlusTransmitterTimeTx.kt, Rx.kt ← TransmitterTimeTx/RxMessage + parse/OnePlusSessionStartTx.kt, Rx.kt ← SessionStartTx/RxMessage + parse/OnePlusSessionStopTx.kt, Rx.kt ← SessionStopTx/RxMessage + parse/OnePlusBackFillTx.kt, ControlRx.kt, Stream.kt + ← BackFillTxMessage2 / BackFillControlRx / BackFillStream + session/OnePlusBackfillSession.kt ← Ob1G5StateMachine.backFillIfNeeded / monitorBackFill + session/OnePlusInvalidShortPairingCodes.kt ← TxIdHelper.INVALID_SHORT_PAIRING_CODES + session/OnePlusSessionStart.kt ← TxIdHelper.isValidShortPairingCode + session/OnePlusKeksGuideCerts.kt ← xDrip G7 keks Auto-Configure QR / Ob1 setPersistence + +Co-derived with Juggluco (also listed in section 2): + gatt/OnePlusGattClient.kt, gatt/OnePlusGattClientAndroid.kt, + oem/OemDeviceProfile.kt, session/OnePlusAuthStatusRx.kt, + session/OnePlusSessionAuth.kt, session/OnePlusSessionAuthKeks.kt, + session/OnePlusEgvSession.kt + (companion :plugins:source module: DexcomOnePlusIngest.kt ← Ob1 getForPreciseTimestamp dedup) + +Still incomplete vs full Ob1: full bond-state-machine UX, 24h backfill option, +robust DexTimeKeeper persistence across process death. + + +------------------------------------------------------------------------------- +2. Juggluco — device identity / BLE + bond choreography / EGV request +------------------------------------------------------------------------------- + +Project: Juggluco +Repository: https://github.com/j-kaltes/Juggluco +License: GNU General Public License v3.0 or later (root LICENSE.txt is the + GPL v3 text; DexGattCallback.java header says "version 3 of the + License, or (at your option) any later version") +Author: j-kaltes (per repo). No formal per-file © lines assumed; do not invent. +Pin: + Version: 10.9.6 + Commit: 5297da7c23a312d1065c5e828a7b61a161cc1200 + URL: https://github.com/j-kaltes/Juggluco/commit/5297da7c23a312d1065c5e828a7b61a161cc1200 + The files this module derives from (Common/src/dex/java/tk/glucodata/ + DexGattCallback.java, SuperGattCallback.java, SensorBluetooth.java, BarCode.hpp) + are unchanged upstream from commit 63197a8f (10.9.3) up to the last commit + before 43fdbe1e (11.0.1), so any commit in that range gives the same code. + +Material derived from Juggluco (behaviour / approach ported into original Kotlin, +not a verbatim copy): + identity/OnePlusAdvCandidate.kt ← isG7 ADV name detection (DX + CM/02/01) + identity/OnePlusGs1ApplicatorParser.kt ← BarCode GS1 AIs / dexcomEnd PIN + identity/OnePlusSensorIdentity.kt ← GS1 Data Matrix fields / DexDeviceName + identity/OnePlusSensorStore.kt ← short-auth reconnect persistence pattern + scan/OnePlusBleScannerAndroid.kt ← isG7 scan soft-filter / sticky match + +Co-derived with xDrip (also listed in section 1): + gatt/OnePlusGattClient.kt, gatt/OnePlusGattClientAndroid.kt + ← bond wait, createBond(TRANSPORT_LE) via + reflection, removeBond, CCCD teardown/restore, + MTU "never request" on Dex path + oem/OemDeviceProfile.kt, oem/DeviceProfileRegistry.kt ← Dex-path MTU / interval defaults + session/OnePlusAuthStatusRx.kt ← DexGattCallback.authenticate ChallengeReply semantics + session/OnePlusSessionAuthKeks.kt ← auth!=1 recovery, removeBond, CCCD teardown + session/OnePlusSessionAuth.kt ← short-auth reconnect path + session/OnePlusEgvSession.kt ← DexGattCallback.getdatacmd EGV/backfill approach + +Note: Juggluco is named in some user-facing strings (source module) only as a +compatible app to close before connecting — that is not code derivation. + + +------------------------------------------------------------------------------- +3. Other third-party libraries +------------------------------------------------------------------------------- + +None. Bouncy Castle (bcpkix / bcprov) used to arrive here through :plugins:libkeks. +That module was translated to Kotlin Multiplatform in October 2026 and carries +its own secp256r1 and ECDSA code now, so nothing third-party reaches this module +through it any more. See plugins/libkeks/NOTICE. +Add SPDX name / version / licence URL here if new direct dependencies land. + + +------------------------------------------------------------------------------- +4. Original AndroidAPS code (not from xDrip or Juggluco) +------------------------------------------------------------------------------- + +Original to AndroidAPS (no upstream provenance marker): + OnePlusCgmDriver.kt, OnePlusCgmDriverReal.kt, OnePlusCgmDriverStub.kt, + OnePlusCgmDrivers.kt, OnePlusGlucoseSample.kt, OnePlusGlucoseWatcher.kt, + OnePlusLogMarkers.kt, OnePlusWarmupState.kt, + reconnect/OnePlusReconnectPolicy.kt, scan/OnePlusBleScanner.kt, + scan/OnePlusScanResult.kt, session/OnePlusBackfill.kt, + session/OnePlusBleSession.kt (reconnect/OEM orchestration; carries + Juggluco-informed wake-lock / short-auth patterns but is original code), + session/OnePlusSessionStartPolicy.kt, warmup/OnePlusWarmupClock.kt. +The OEM device-profile abstraction (oem/) and the Android GATT plumbing bulk of +gatt/OnePlusGattClientAndroid.kt are original AAPS implementation; only the +protocol choreography within them is derived (see sections 1 and 2). + + +------------------------------------------------------------------------------- +Reviewer verification points (not legal advice — maintainer/counsel to confirm) +------------------------------------------------------------------------------- + a. SPDX GPL-3.0-only vs GPL-3.0-or-later — Juggluco is GPL-3.0-or-later (section 2); + confirm the xDrip side against its LICENSE and file headers. + b. Repository root LICENSE.txt is AGPL-3.0(-or-later). + +End of NOTICE diff --git a/plugins/dexcom_oneplus/build.gradle.kts b/plugins/dexcom_oneplus/build.gradle.kts new file mode 100644 index 000000000000..3fb7020e30a2 --- /dev/null +++ b/plugins/dexcom_oneplus/build.gradle.kts @@ -0,0 +1,76 @@ +plugins { + id("kmp-test-defaults") + kotlin("multiplatform") + // NOT com.android.library. AGP 9 refuses that plugin together with the multiplatform plugin. + // Same reason as :plugins:source and the :core modules. + alias(libs.plugins.android.kmp.library) + // No KSP and no Metro: this driver has no dependency injection at all. It is reached through + // the OnePlusCgmDrivers object from :plugins:source, not from the application graph. +} + +kotlin { + android { + namespace = "app.aaps.plugins.dexcomoneplus" + compileSdk = Versions.compileSdk + minSdk = Versions.minSdk + // Creates the androidHostTest compilation. isReturnDefaultValues and + // isIncludeAndroidResources are restated from test-module-dependencies, which a + // multiplatform module cannot apply: the scanner test touches android.bluetooth classes + // that are stubs on the unit-test classpath. + withHostTest { + isReturnDefaultValues = true + isIncludeAndroidResources = true + } + compilerOptions { jvmTarget.set(Versions.jvmTarget) } + // Restated from android-module-dependencies, which a multiplatform module cannot apply. + lint { + checkReleaseBuilds = false + disable += "MissingTranslation" + disable += "ExtraTranslation" + } + } + + // Android is the only target. The protocol code is shared (commonMain, no Android imports) so + // another platform can be added later; nothing checks that yet, so keep Android types out by hand. + + sourceSets { + commonMain { + dependencies { + implementation(project(":core:interfaces")) + // The xDrip KEKS authentication library, translated to Kotlin Multiplatform, so + // OnePlusSessionAuthKeks and OnePlusKeksGuideCerts can live in commonMain. + implementation(project(":plugins:libkeks")) + } + } + + androidMain { + dependencies { + // AAPS writes everything that comes through slf4j to AndroidAPS.log. JVM only, + // which is why OnePlusLog keeps its sink behind an expect/actual. + implementation(libs.org.slf4j.api) + } + } + + // Shared tests (kotlin.test only) run in testAndroidHostTest. Everything else stays in + // androidHostTest, written against JUnit 5 and Truth. + getByName("commonTest") { + dependencies { + implementation(kotlin("test")) + } + } + + // Hand written rather than taken from test-module-dependencies, which applies + // com.android.library and so cannot be used by a multiplatform module. + getByName("androidHostTest") { + dependencies { + // Only what the test classes actually import: JUnit 5 and Truth. Mockito, + // joda-time, jsonassert and coroutines-test came from the convention plugin and + // are not used here. + implementation(libs.org.junit.jupiter) + implementation(libs.org.junit.jupiter.api) + implementation(libs.com.google.truth) + runtimeOnly(libs.org.junit.platform.launcher) + } + } + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverResumePolicyTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverResumePolicyTest.kt new file mode 100644 index 000000000000..276e22c0f6bd --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverResumePolicyTest.kt @@ -0,0 +1,48 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusCgmDriverResumePolicyTest { + + @Test + fun `complete stored session can resume`() { + val stored = storedSession() + + assertThat(OnePlusCgmDriverResumePolicy.canResume(stored)).isTrue() + } + + @Test + fun `resume requires valid pin MAC and shared key`() { + assertThat(OnePlusCgmDriverResumePolicy.canResume(null)).isFalse() + assertThat( + OnePlusCgmDriverResumePolicy.canResume( + storedSession().copy(lastMac = null), + ), + ).isFalse() + assertThat( + OnePlusCgmDriverResumePolicy.canResume( + storedSession().copy(identity = OnePlusSensorIdentity(pin = "12")), + ), + ).isFalse() + assertThat( + OnePlusCgmDriverResumePolicy.canResume( + storedSession().copy(sharedKey = null), + ), + ).isFalse() + assertThat( + OnePlusCgmDriverResumePolicy.canResume( + storedSession().copy(sharedKey = ByteArray(15)), + ), + ).isFalse() + } + + private fun storedSession() = OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = "1234"), + lastMac = "DA:3B:12:0D:5B:B7", + lastDeviceName = "DX02aS", + sharedKey = ByteArray(16), + ) +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverSessionReleaseTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverSessionReleaseTest.kt new file mode 100644 index 000000000000..83979905244e --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverSessionReleaseTest.kt @@ -0,0 +1,81 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * What happens to the driver's "a session is running" state when a link ends by itself. + * + * `OnePlusBleSession.fail` - the terminal end of the retry ladder - returns normally instead of + * throwing, so the driver used to keep `session` and `resumeQueued` set for ever. `resumeStoredSession` + * refuses to start anything while either is set, so the plugin's reconnect watchdog answered "already + * active" at every wake-up and no glucose ever came back without an app restart. + * + * This is an `androidHostTest` and not a `commonTest` because it reaches the private state of the + * driver through JVM reflection. The code under test itself is in commonMain. + */ +class OnePlusCgmDriverSessionReleaseTest { + + private class FakeSession : OnePlusBleSession { + + override fun startWithPairingCode(deviceAddress: String, pairingCode: String) = Unit + override fun stop(reason: String?) = Unit + override fun isUp(): Boolean = false + override fun warmupState(): OnePlusWarmupState = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.FAILED) + } + + private fun field(name: String) = OnePlusCgmDriverReal::class.java.getDeclaredField(name).apply { isAccessible = true } + + private fun release(driver: OnePlusCgmDriverReal, generation: Long, ended: OnePlusBleSession) { + OnePlusCgmDriverReal::class.java + .getDeclaredMethod("releaseSessionIfCurrent", Long::class.java, OnePlusBleSession::class.java) + .apply { isAccessible = true } + .invoke(driver, generation, ended) + } + + @Test + fun `a session that ended frees the driver for the next attempt`() { + val driver = OnePlusCgmDriverReal() + val ended = FakeSession() + field("session").set(driver, ended) + field("resumeQueued").set(driver, true) + val generation = field("operationGeneration").getLong(driver) + + release(driver, generation, ended) + + assertThat(field("session").get(driver)).isNull() + assertThat(field("resumeQueued").getBoolean(driver)).isFalse() + } + + @Test + fun `a newer session is not released by the old one unwinding`() { + // A connect started while the old link was still ending: the old thread must not clear the + // state of the session that has just replaced it. + val driver = OnePlusCgmDriverReal() + val old = FakeSession() + val current = FakeSession() + field("session").set(driver, current) + field("resumeQueued").set(driver, true) + val generation = field("operationGeneration").getLong(driver) + + release(driver, generation, old) + + assertThat(field("session").get(driver)).isSameInstanceAs(current) + assertThat(field("resumeQueued").getBoolean(driver)).isTrue() + } + + @Test + fun `a session from an older operation generation releases nothing`() { + val driver = OnePlusCgmDriverReal() + val ended = FakeSession() + field("session").set(driver, ended) + field("resumeQueued").set(driver, true) + val generation = field("operationGeneration").getLong(driver) + + release(driver, generation - 1, ended) + + assertThat(field("session").get(driver)).isSameInstanceAs(ended) + assertThat(field("resumeQueued").getBoolean(driver)).isTrue() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriversTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriversTest.kt new file mode 100644 index 000000000000..76175952db27 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriversTest.kt @@ -0,0 +1,108 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.core.interfaces.source.SensorSlot +import app.aaps.plugins.dexcomoneplus.session.OnePlusMacArbiter +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test + +class OnePlusCgmDriversTest { + + @AfterEach + fun reset() { + // A leftover staging instance must be dropped too: `by lazy` used to keep a shut-down + // driver for the next test, which is the bug this registry exists to avoid. + OnePlusCgmDrivers.shutdownAll() + OnePlusMacArbiter.reset() + } + + @Test + fun `production is always the real driver`() { + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(OnePlusCgmDrivers.realProduction()) + assertThat(OnePlusCgmDrivers.default()).isNotInstanceOf(OnePlusCgmDriverStub::class.java) + } + + @Test + fun `a shut-down registry builds a new production driver`() { + val first = OnePlusCgmDrivers.default() + + OnePlusCgmDrivers.shutdownAll() + + assertThat(OnePlusCgmDrivers.default()).isNotSameInstanceAs(first) + } + + @Test + fun `production keeps the original store file and staging gets its own`() { + assertThat(OnePlusCgmDrivers.storeNamespace(SensorSlot.PRODUCTION)).isNull() + assertThat(OnePlusCgmDrivers.storeNamespace(SensorSlot.STAGING)) + .isEqualTo(OnePlusCgmDrivers.STAGING_NAMESPACE) + } + + @Test + fun `a promotion makes the pre-soak instance the production default`() { + val soak = OnePlusCgmDrivers.staging() + + val retired = OnePlusCgmDrivers.promoteStagingInstance() + + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(soak) + assertThat(OnePlusCgmDrivers.realProduction()).isSameInstanceAs(soak) + assertThat(retired).isNotSameInstanceAs(soak) + // The next pre-soak is a new instance. The one that now feeds the loop is not reused. + assertThat(OnePlusCgmDrivers.staging()).isNotSameInstanceAs(soak) + } + + @Test + fun `a second promotion does not reuse a shut-down instance`() { + val firstSoak = OnePlusCgmDrivers.staging() + val retiredFirst = OnePlusCgmDrivers.promoteStagingInstance() + retiredFirst?.shutdown() + + val secondSoak = OnePlusCgmDrivers.staging() + assertThat(secondSoak).isNotSameInstanceAs(firstSoak) + assertThat(secondSoak).isNotSameInstanceAs(retiredFirst) + + val retiredSecond = OnePlusCgmDrivers.promoteStagingInstance() + assertThat(retiredSecond).isSameInstanceAs(firstSoak) + retiredSecond?.shutdown() + + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(secondSoak) + assertThat(OnePlusCgmDrivers.default()).isNotSameInstanceAs(retiredFirst) + assertThat(OnePlusCgmDrivers.default()).isNotSameInstanceAs(firstSoak) + } + + @Test + fun `each driver instance has its own arbiter token`() { + val first = OnePlusCgmDriverReal(storeNamespace = OnePlusCgmDrivers.STAGING_NAMESPACE) + val second = OnePlusCgmDriverReal(storeNamespace = OnePlusCgmDrivers.STAGING_NAMESPACE) + try { + val firstToken = arbiterOwner(first) + val secondToken = arbiterOwner(second) + assertThat(firstToken).startsWith("staging#") + assertThat(secondToken).startsWith("staging#") + assertThat(firstToken).isNotEqualTo(secondToken) + // Same slot name, different instance: the second claim must not release the first. + assertThat(OnePlusMacArbiter.claim(MAC, firstToken)).isTrue() + assertThat(OnePlusMacArbiter.claim(MAC, secondToken)).isFalse() + assertThat(OnePlusMacArbiter.ownerOf(MAC)).isEqualTo(firstToken) + } finally { + first.shutdown() + second.shutdown() + } + } + + private fun arbiterOwner(driver: OnePlusCgmDriverReal): String = + OnePlusCgmDriverReal::class.java.getDeclaredField("arbiterOwner") + .apply { isAccessible = true } + .get(driver) as String + + @Test + fun `the two slots never share a store namespace`() { + // Sharing it is what let a pre-soak adopt the sensor already in use (same MAC, PIN and key). + assertThat(OnePlusCgmDrivers.storeNamespace(SensorSlot.STAGING)) + .isNotEqualTo(OnePlusCgmDrivers.storeNamespace(SensorSlot.PRODUCTION)) + } + + companion object { + private const val MAC = "AA:BB:CC:DD:EE:10" + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkStateTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkStateTest.kt new file mode 100644 index 000000000000..4625e3096ca4 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkStateTest.kt @@ -0,0 +1,27 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +import android.bluetooth.BluetoothProfile +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusAudioLinkStateTest { + + @Test + fun `a headset playing music is visible in the log line`() { + val line = OnePlusAudioLinkState.format( + a2dp = BluetoothProfile.STATE_CONNECTED, + headset = BluetoothProfile.STATE_CONNECTED, + leAudio = BluetoothProfile.STATE_DISCONNECTED, + musicActive = true, + ) + + assertThat(line).isEqualTo("audio a2dp=on headset=on leAudio=off music=on") + } + + @Test + fun `an unknown state shows as a question mark instead of failing`() { + val line = OnePlusAudioLinkState.format(a2dp = null, headset = 42, leAudio = null, musicActive = null) + + assertThat(line).isEqualTo("audio a2dp=? headset=? leAudio=? music=?") + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt new file mode 100644 index 000000000000..d0764d63e7ff --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt @@ -0,0 +1,137 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusAdvCandidateTest { + + @Test + fun isG7FamilyName_matchesJugglucoPrefixes() { + assertThat(OnePlusAdvCandidate.isG7FamilyName("DX02aS")).isTrue() + assertThat(OnePlusAdvCandidate.isG7FamilyName("DX01xx")).isTrue() + assertThat(OnePlusAdvCandidate.isG7FamilyName("DXCMab")).isTrue() + assertThat(OnePlusAdvCandidate.isG7FamilyName("DexcomONE")).isFalse() + assertThat(OnePlusAdvCandidate.isG7FamilyName("Dexcom65")).isFalse() + } + + @Test + fun nameMatchesSoft_rejectsG6MarketingNames() { + assertThat(OnePlusAdvCandidate.nameMatchesSoft("DX02aS")).isTrue() + assertThat(OnePlusAdvCandidate.nameMatchesSoft("Dexcom65")).isFalse() + assertThat(OnePlusAdvCandidate.nameMatchesSoft("DexcomONE")).isFalse() + } + + @Test + fun isCandidate_rejectsDexcom65UnlessStickyMac() { + assertThat( + OnePlusAdvCandidate.isCandidate("Dexcom65", "F2:08:F3:22:6B:77", session = null), + ).isFalse() + val sticky = OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = "1234"), + lastMac = "F2:08:F3:22:6B:77", + lastDeviceName = "Dexcom65", + ) + // Sticky MAC still matches (reconnect to stored device) — UI should not offer it for ONE+. + assertThat( + OnePlusAdvCandidate.isCandidate("Dexcom65", "F2:08:F3:22:6B:77", sticky), + ).isTrue() + } + + @Test + fun stickyMacAndNamePreferred() { + val session = OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = "1234", serial = "SER1"), + lastMac = "AA:BB:CC:DD:EE:FF", + lastDeviceName = "DX02aS", + ) + assertThat( + OnePlusAdvCandidate.isCandidate("DX02aS", "11:22:33:44:55:66", session), + ).isTrue() + assertThat( + OnePlusAdvCandidate.isCandidate("Other", "AA:BB:CC:DD:EE:FF", session), + ).isTrue() + assertThat( + OnePlusAdvCandidate.rankScore("DX02aS", "AA:BB:CC:DD:EE:FF", -70, session), + ).isGreaterThan( + OnePlusAdvCandidate.rankScore("DX02zz", "11:22:33:44:55:66", -40, session), + ) + } + + // ------------ scanHintFor(): rank this scan from the code on screen ------------ + + @Test + fun scanHintFor_sameCode_keepsTheStoredSensorSticky() { + val stored = storedSensor(pin = "1234") + assertThat(OnePlusAdvCandidate.scanHintFor(stored, OnePlusSensorIdentity(pin = "1234"))) + .isEqualTo(stored) + } + + @Test + fun scanHintFor_newCode_dropsStoredMacAndName() { + val hint = OnePlusAdvCandidate.scanHintFor(storedSensor(pin = "1234"), OnePlusSensorIdentity(pin = "5678"))!! + + assertThat(hint.identity.pin).isEqualTo("5678") + assertThat(hint.lastMac).isNull() + assertThat(hint.lastDeviceName).isNull() + } + + @Test + fun scanHintFor_serialDecidesWhenBothSidesKnowIt() { + // The code is not unique, so the same four digits on another serial is another sensor… + val stored = storedSensor(pin = "1234", serial = "SER1") + val other = OnePlusAdvCandidate.scanHintFor(stored, OnePlusSensorIdentity(pin = "1234", serial = "SER2"))!! + assertThat(other.lastMac).isNull() + + // …and the same serial is the same sensor, whatever the code says. + assertThat(OnePlusAdvCandidate.scanHintFor(stored, OnePlusSensorIdentity(pin = "9999", serial = "SER1"))) + .isEqualTo(stored) + } + + @Test + fun scanHintFor_firstPairingHasNothingSticky() { + assertThat(OnePlusAdvCandidate.scanHintFor(null, null)).isNull() + + val fresh = OnePlusAdvCandidate.scanHintFor(null, OnePlusSensorIdentity(pin = "1234"))!! + assertThat(fresh.lastMac).isNull() + assertThat(fresh.lastDeviceName).isNull() + } + + @Test + fun scanHintFor_noCodeOnScreen_leavesTheStoreAlone() { + // Nothing on screen contradicts the store, so a plain reconnect still ranks as before. + val stored = storedSensor(pin = "1234") + assertThat(OnePlusAdvCandidate.scanHintFor(stored, onScreen = null)).isEqualTo(stored) + } + + @Test + fun newCode_theOldTransmitterLosesItsBoost() { + val stored = storedSensor(pin = "1234") + val hint = OnePlusAdvCandidate.scanHintFor(stored, OnePlusSensorIdentity(pin = "5678")) + + // The sensor being replaced is far away, the new one is right here. With the code on screen + // the near sensor now ranks first… + assertThat( + OnePlusAdvCandidate.rankScore("DX02aS", STORED_MAC, -90, hint), + ).isLessThan( + OnePlusAdvCandidate.rankScore("DX02zz", OTHER_MAC, -50, hint), + ) + // …while ranking with the store, which is what the screen used to do, put it last. + assertThat( + OnePlusAdvCandidate.rankScore("DX02aS", STORED_MAC, -90, stored), + ).isGreaterThan( + OnePlusAdvCandidate.rankScore("DX02zz", OTHER_MAC, -50, stored), + ) + } + + private fun storedSensor(pin: String, serial: String? = null) = OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = pin, serial = serial), + lastMac = STORED_MAC, + lastDeviceName = "DX02aS", + ) + + private companion object { + + const val STORED_MAC = "AA:BB:CC:DD:EE:FF" + const val OTHER_MAC = "11:22:33:44:55:66" + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParserTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParserTest.kt new file mode 100644 index 000000000000..c3c778a1eaa1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParserTest.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusGs1ApplicatorParserTest { + + @Test + fun bareFourDigitPin() { + val id = OnePlusGs1ApplicatorParser.parse("1234") + assertThat(id).isNotNull() + assertThat(id!!.pin).isEqualTo("1234") + assertThat(id.serial).isNull() + } + + @Test + fun gs1WithPinAndSerial() { + // Synthetic GS1: 01(GTIN14) + 21(serial) + 240(pin) + val raw = "\u001d010123456789012321ABCD12345678\u001d2401234" + val id = OnePlusGs1ApplicatorParser.parse(raw) + assertThat(id).isNotNull() + assertThat(id!!.pin).isEqualTo("1234") + assertThat(id.serial).isEqualTo("ABCD12345678") + assertThat(id.gtin).isEqualTo("01234567890123") + } + + @Test + fun caretBracketGsNormalized() { + val raw = "^]010123456789012321SERIALXYZ001^]2409876" + val id = OnePlusGs1ApplicatorParser.parse(raw) + assertThat(id).isNotNull() + assertThat(id!!.pin).isEqualTo("9876") + assertThat(id.serial).isEqualTo("SERIALXYZ001") + } + + @Test + fun extractPinTakesTrailingFourDigits() { + assertThat(OnePlusGs1ApplicatorParser.extractPin("XX1234")).isEqualTo("1234") + assertThat(OnePlusGs1ApplicatorParser.extractPin("12")).isNull() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreTest.kt new file mode 100644 index 000000000000..ab6a35bae135 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreTest.kt @@ -0,0 +1,101 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * Pure part of the session-start anchoring (the store itself needs a Context). + * Decides whether an explicit sensor start restarts the sensor age. + */ +class OnePlusSensorStoreTest { + + private val sensorA = "AA:BB:CC:DD:EE:01" + private val sensorB = "AA:BB:CC:DD:EE:02" + + @Test + fun `nothing stored yet starts a new session`() { + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 0L, + storedOwnerMac = null, + previousMac = null, + deviceAddress = sensorA, + ), + ).isTrue() + } + + @Test + fun `re-connecting the same sensor keeps its age`() { + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 1_000L, + storedOwnerMac = sensorA, + previousMac = sensorA, + deviceAddress = sensorA, + ), + ).isFalse() + // MAC case must not matter (stored uppercase, scan results may differ). + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 1_000L, + storedOwnerMac = sensorA.lowercase(), + previousMac = null, + deviceAddress = sensorA, + ), + ).isFalse() + } + + @Test + fun `another sensor restarts the age`() { + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 1_000L, + storedOwnerMac = sensorA, + previousMac = sensorA, + deviceAddress = sensorB, + ), + ).isTrue() + } + + @Test + fun `a session anchored before the owner key existed falls back to the last stored MAC`() { + // Sensor started by an older build: session start present, no owner MAC. Without the + // fallback the same sensor would look new — resetting its age and logging a sensor change. + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 1_000L, + storedOwnerMac = null, + previousMac = sensorA, + deviceAddress = sensorA, + ), + ).isFalse() + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 1_000L, + storedOwnerMac = null, + previousMac = sensorA, + deviceAddress = sensorB, + ), + ).isTrue() + } + + @Test + fun `an unknown owner with no previous MAC starts a new session`() { + assertThat( + OnePlusSensorStore.startsNewSession( + storedStartMs = 1_000L, + storedOwnerMac = null, + previousMac = "", + deviceAddress = sensorA, + ), + ).isTrue() + } + + @Test + fun `a serial in a log line shows only its last three characters`() { + assertThat(OnePlusSensorStore.maskSerial("3MH0A1B2C3")).isEqualTo("***2C3") + assertThat(OnePlusSensorStore.maskSerial("AB")).isEqualTo("***") + assertThat(OnePlusSensorStore.maskSerial("")).isEqualTo("-") + assertThat(OnePlusSensorStore.maskSerial(null)).isEqualTo("-") + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistryTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistryTest.kt new file mode 100644 index 000000000000..b92ebd9ba28e --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistryTest.kt @@ -0,0 +1,86 @@ +package app.aaps.plugins.dexcomoneplus.oem + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class DeviceProfileRegistryTest { + + @Test + fun pixel_doesNotRequestMtuBeforeDiscover() { + // Juggluco Dex path never requestMtu before discover; Pixel previously did and + // could race CCCD/auth on fragile stacks. + assertThat(DeviceProfileRegistry.PixelDefault.requestMtuOnConnect).isFalse() + assertThat(DeviceProfileRegistry.SamsungDefault.requestMtuOnConnect).isFalse() + assertThat(DeviceProfileRegistry.GenericFallback.requestMtuOnConnect).isFalse() + } + + @Test + fun samsung_requiresAdvOnFirstAttemptAndAutoConnectFromStart() { + val s = DeviceProfileRegistry.SamsungDefault + assertThat(s.autoConnectFromAttempt).isEqualTo(0) + // Hard ADV gate only on attempt 0 (driver); flag still true for Samsung. + assertThat(s.requireAdvBeforeConnect).isTrue() + assertThat(s.preConnectScanMs).isAtLeast(8_000L) + } + + @Test + fun motorola_getsItsOwnProfileAndNotTheFallback() { + val resolved = DeviceProfileRegistry.resolve(manufacturer = "motorola", model = "moto g84 5G") + assertThat(resolved.id).isEqualTo(OemProfileId.MOTOROLA) + assertThat(resolved).isEqualTo(DeviceProfileRegistry.MotorolaDefault) + } + + @Test + fun motorola_takesTheSamsungLessonOnBlindConnects() { + // A blind hard connect without a fresh ADV is what cost minutes on this stack, exactly as it + // did on Samsung. Wait for the advertisement, and let the platform hold the link from the + // first attempt. + val m = DeviceProfileRegistry.MotorolaDefault + assertThat(m.requireAdvBeforeConnect).isTrue() + assertThat(m.autoConnectFromAttempt).isEqualTo(0) + assertThat(m.preConnectScanMs).isAtLeast(8_000L) + assertThat(m.requestMtuOnConnect).isFalse() + } + + @Test + fun motorola_isNotMistakenForPixelOrSamsung() { + assertThat(DeviceProfileRegistry.resolve(manufacturer = "Google", model = "Pixel 8").id) + .isEqualTo(OemProfileId.PIXEL) + assertThat(DeviceProfileRegistry.resolve(manufacturer = "samsung", model = "SM-S911B").id) + .isEqualTo(OemProfileId.SAMSUNG) + assertThat(DeviceProfileRegistry.resolve(manufacturer = "Xiaomi", model = "whatever").id) + .isEqualTo(OemProfileId.GENERIC_FALLBACK) + } + + @Test + fun everyProfileIsReachableById() { + OemProfileId.entries.forEach { id -> + assertThat(DeviceProfileRegistry.byId(id).id).isEqualTo(id) + } + } + + @Test + fun genericFallback_isTheSafestProfileNotTheBoldest() { + // It is where every phone that is not a Pixel or a Samsung lands, so a blind connect must not + // be its default. Two field logs — a Motorola and a CUBOT KING KONG MINI 3 — reached it. + val g = DeviceProfileRegistry.GenericFallback + assertThat(g.requireAdvBeforeConnect).isTrue() + assertThat(g.autoConnectFromAttempt).isEqualTo(0) + assertThat(g.preConnectScanMs).isAtLeast(8_000L) + } + + @Test + fun everyProfileWaitsForTheAdvertisementExceptPixel() { + // Pixel is the one stack with field evidence that a direct connect works without it. + assertThat(DeviceProfileRegistry.SamsungDefault.requireAdvBeforeConnect).isTrue() + assertThat(DeviceProfileRegistry.MotorolaDefault.requireAdvBeforeConnect).isTrue() + assertThat(DeviceProfileRegistry.GenericFallback.requireAdvBeforeConnect).isTrue() + } + + @Test + fun unknownOemFallsBackAndKeepsTheGuard() { + val resolved = DeviceProfileRegistry.resolve(manufacturer = "CUBOT", model = "KINGKONG MINI 3") + assertThat(resolved.id).isEqualTo(OemProfileId.GENERIC_FALLBACK) + assertThat(resolved.requireAdvBeforeConnect).isTrue() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillMessageTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillMessageTest.kt new file mode 100644 index 000000000000..6ae94abc3bfc --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillMessageTest.kt @@ -0,0 +1,71 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class OnePlusBackFillMessageTest { + + @Test + fun backFillTx_layout() { + val packet = OnePlusBackFillTx.build(100, 400) + assertThat(packet).hasLength(9) + assertThat(packet[0]).isEqualTo(OnePlusBackFillTx.OPCODE) + val buf = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN) + buf.get() + assertThat(buf.int).isEqualTo(100) + assertThat(buf.int).isEqualTo(400) + } + + @Test + fun backFillStream_decodesG7Record() { + val currentDex = 10_000 + val nowMs = 1_700_000_000_000L + val dexTime = 9_700 // 300s ago + val record = ByteBuffer.allocate(9).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(dexTime) + record.putShort(120) // glucose + record.put(0x06) // Ok + record.put(0x00) // extra + record.put(0x00) // trend + val stream = OnePlusBackFillStream() + stream.pushG7(record.array()) + val samples = stream.decode(currentDexTimeSeconds = currentDex, nowMs = nowMs) + assertThat(samples).hasSize(1) + assertThat(samples[0].mgdl).isEqualTo(120.0) + assertThat(samples[0].timestampMs).isEqualTo(nowMs - 300_000L) + } + + @Test + fun backFillStream_skipsWarmingUp() { + val record = ByteBuffer.allocate(9).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(100) + record.putShort(90) + record.put(0x02) // WarmingUp + record.put(0x00) + record.put(0x00) + val stream = OnePlusBackFillStream() + stream.pushG7(record.array()) + assertThat(stream.decode(currentDexTimeSeconds = 200, nowMs = 1_000_000L)).isEmpty() + } + + @Test + fun `a display-only backfill record is skipped`() { + val record = ByteBuffer.allocate(9).order(ByteOrder.LITTLE_ENDIAN) + record.putInt(9_700) + record.putShort(120) + record.put(0x06) // Ok + record.put(OnePlusGlucoseParser.DISPLAY_ONLY_FLAG.toByte()) + record.put(0x00) + val stream = OnePlusBackFillStream() + stream.pushG7(record.array()) + assertThat(stream.decode(currentDexTimeSeconds = 10_000, nowMs = 1_700_000_000_000L)).isEmpty() + } + + @Test + fun backFillControlRx_ack() { + assertThat(OnePlusBackFillControlRx.isAck(byteArrayOf(0x59, 0x00))).isTrue() + assertThat(OnePlusBackFillControlRx.isAck(byteArrayOf(0x4e))).isFalse() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationMapperTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationMapperTest.kt new file mode 100644 index 000000000000..5b623084d053 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationMapperTest.kt @@ -0,0 +1,26 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusCalibrationMapperTest { + + @Test + fun `ok maps to READY`() { + val s = OnePlusCalibrationMapper.toWarmupState(OnePlusCalibrationState.Ok) + assertThat(s.phase).isEqualTo(OnePlusWarmupState.Phase.READY) + } + + @Test + fun `warmingUp maps to WARMING`() { + val s = OnePlusCalibrationMapper.toWarmupState(OnePlusCalibrationState.WarmingUp) + assertThat(s.phase).isEqualTo(OnePlusWarmupState.Phase.WARMING) + } + + @Test + fun `failed maps to FAILED`() { + val s = OnePlusCalibrationMapper.toWarmupState(OnePlusCalibrationState.SensorFailed) + assertThat(s.phase).isEqualTo(OnePlusWarmupState.Phase.FAILED) + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserEgvTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserEgvTest.kt new file mode 100644 index 000000000000..1bfca1932cb2 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserEgvTest.kt @@ -0,0 +1,64 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class OnePlusGlucoseParserEgvTest { + + @Test + fun `parseEgv1 accepts CRC packet with Ok state`() { + // opcode, status, sequence(4), timestamp(4), glucose(2), state, trend, predicted(2), crc(2) + val buf = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN) + buf.put(0x4f.toByte()) + buf.put(0x00) + buf.putInt(1) + buf.putInt(100) + buf.putShort(120) // glucose 120, not display-only + buf.put(0x06) // Ok + buf.put(0) // trend + buf.putShort(0) + val raw = buf.array() + val crc = OnePlusFastCrc16.calculate(raw, raw.size - 2) + raw[raw.size - 2] = crc[0] + raw[raw.size - 1] = crc[1] + + val parsed = OnePlusGlucoseParser.parseControlPacket(raw) + assertThat(parsed).isNotNull() + assertThat(parsed!!.calibration).isEqualTo(OnePlusCalibrationState.Ok) + assertThat(parsed.usable).isTrue() + assertThat(parsed.sample!!.mgdl).isEqualTo(120.0) + } + + @Test + fun `parseEgv2 warming up yields no sample but WarmingUp`() { + val buf = ByteBuffer.allocate(19).order(ByteOrder.LITTLE_ENDIAN) + buf.put(0x4e.toByte()) + buf.put(0x00) // status + buf.putInt(600) // session age seconds (~10 min) + buf.putShort(1) // sequence + buf.putShort(0) // bogus + buf.putShort(60) // age + buf.putShort(100) // glucose while warming — not usable + buf.put(0x02) // WarmingUp + buf.put(0) // trend + buf.putShort(0) // predicted + buf.put(0) // info — need 19 bytes: 1+1+4+2+2+2+2+1+1+2+1 = 19 + + val parsed = OnePlusGlucoseParser.parseControlPacket(buf.array()) + assertThat(parsed).isNotNull() + assertThat(parsed!!.calibration).isEqualTo(OnePlusCalibrationState.WarmingUp) + assertThat(parsed.usable).isFalse() + assertThat(parsed.sample).isNull() + } + + @Test + fun `egv tx short and crc lengths`() { + assertThat(OnePlusEGlucoseTx.requestShort()).isEqualTo(byteArrayOf(0x4e)) + val withCrc = OnePlusEGlucoseTx.requestWithCrc() + assertThat(withCrc).hasLength(3) + assertThat(withCrc[0]).isEqualTo(0x4e.toByte()) + assertThat(OnePlusFastCrc16.check(withCrc)).isTrue() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserTest.kt new file mode 100644 index 000000000000..7a5838e4d014 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParserTest.kt @@ -0,0 +1,198 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import java.nio.ByteBuffer +import java.nio.ByteOrder +import org.junit.jupiter.api.Test + +/** + * Synthetic hex fixtures match upstream field layouts from + * `EGlucoseRxMessage` / `EGlucoseRxMessage2` (pin 1e86d9a2a525…). + * No captured device traffic claimed. + */ +class OnePlusGlucoseParserTest { + + @Test + fun `inRange bounds 20 to 600`() { + assertThat(OnePlusGlucoseParser.inRange(19.9)).isFalse() + assertThat(OnePlusGlucoseParser.inRange(20.0)).isTrue() + assertThat(OnePlusGlucoseParser.inRange(600.0)).isTrue() + assertThat(OnePlusGlucoseParser.inRange(600.1)).isFalse() + } + + @Test + fun `toSample drops out of range`() { + assertThat(OnePlusGlucoseParser.toSample(10.0, timestampMs = 1L)).isNull() + val ok = OnePlusGlucoseParser.toSample(120.0, timestampMs = 2L, trendSlopeMgdlPerMin = 0.0, sequence = 7L) + requireNotNull(ok) + assertThat(ok.mgdl).isEqualTo(120.0) + assertThat(ok.timestampMs).isEqualTo(2L) + assertThat(ok.trendSlopeMgdlPerMin).isEqualTo(0.0) + assertThat(ok.sequence).isEqualTo(7L) + } + + @Test + fun `parse EGV2 opcode 4e maps glucose age trend sequence`() { + // Hex (LE): 4e | status | clock | seq | bogus | age | gluc | state | trend | pred + // 4E 00 10 27 00 00 2A 00 00 00 1E 00 78 00 06 0C 00 00 00 + val packet = hex( + "4E00" + // opcode + status + "10270000" + // session clock 0x2710 = 10000s + "2A00" + // sequence 42 + "0000" + // bogus + "1E00" + // age 30s + "7800" + // glucose 120 + "06" + // Ok + "0C" + // trend +1.2 mg/dL/min + "0000" + // predicted + "00", // info (Message2 trailing; ignored) + ) + val now = 1_700_000_000_000L + val parsed = OnePlusGlucoseParser.parseControlPacket(packet, nowMs = now) + requireNotNull(parsed) + assertThat(parsed.opcode).isEqualTo(0x4e) + assertThat(parsed.calibration).isEqualTo(OnePlusCalibrationState.Ok) + assertThat(parsed.ageSeconds).isEqualTo(30) + assertThat(parsed.sessionAgeSeconds).isEqualTo(10_000) + val sample = requireNotNull(parsed.sample) + assertThat(sample.mgdl).isEqualTo(120.0) + assertThat(sample.timestampMs).isEqualTo(now - 30_000L) + assertThat(sample.sequence).isEqualTo(42L) + assertThat(sample.trendSlopeMgdlPerMin).isEqualTo(1.2) + assertThat(OnePlusGlucoseParser.parse(packet, now)).isEqualTo(sample) + } + + @Test + fun `a display-only EGV2 value never becomes a sample`() { + val packet = buildEgv2(flags = OnePlusGlucoseParser.DISPLAY_ONLY_FLAG) + val parsed = OnePlusGlucoseParser.parseControlPacket(packet, nowMs = 1000L) + requireNotNull(parsed) + assertThat(parsed.glucoseIsDisplayOnly).isTrue() + assertThat(parsed.flags).isEqualTo(0x10) + assertThat(parsed.sample).isNull() + assertThat(parsed.usable).isFalse() + // The state is still read, so the session still counts as alive. + assertThat(parsed.calibration).isEqualTo(OnePlusCalibrationState.Ok) + } + + @Test + fun `the top bits of the glucose field are not the display-only flag on a G7`() { + // xDrip's G6 reading of the flag. On a G7 these bits are 0 and the flag is byte 18. + val packet = buildEgv2(glucoseMasked = 0x1078) + val parsed = requireNotNull(OnePlusGlucoseParser.parseControlPacket(packet, nowMs = 1000L)) + assertThat(parsed.glucoseIsDisplayOnly).isFalse() + assertThat(parsed.sample?.mgdl).isEqualTo(120.0) + } + + @Test + fun `an invalid trend gives a sample without a slope`() { + val packet = buildEgv2(trend = OnePlusGlucoseParser.TREND_INVALID) + val parsed = requireNotNull(OnePlusGlucoseParser.parseControlPacket(packet, nowMs = 1000L)) + assertThat(parsed.sample?.trendSlopeMgdlPerMin).isNull() + } + + @Test + fun `parse EGV2 warming up yields no sample`() { + val packet = buildEgv2(state = OnePlusCalibrationState.WarmingUp.value) + val parsed = OnePlusGlucoseParser.parseControlPacket(packet, nowMs = 1000L) + requireNotNull(parsed) + assertThat(parsed.calibration).isEqualTo(OnePlusCalibrationState.WarmingUp) + assertThat(parsed.sample).isNull() + assertThat(parsed.usable).isFalse() + } + + @Test + fun `parse EGV2 rejects glucose outside 20-600`() { + val low = buildEgv2(glucoseMasked = 15) + assertThat(OnePlusGlucoseParser.parse(low, nowMs = 1000L)).isNull() + val high = buildEgv2(glucoseMasked = 601) + assertThat(OnePlusGlucoseParser.parse(high, nowMs = 1000L)).isNull() + } + + @Test + fun `parse EGV1 opcode 4f with CRC`() { + // 14 payload bytes through trend + 2 CRC (predicted omitted; remaining unused). + val body = hex( + "4F" + // opcode + "00" + // status + "07000000" + // sequence 7 + "00000000" + // tx timestamp + "6400" + // glucose 100 + "06" + // Ok + "00", // trend flat + ) + val packet = appendCrc(body) + assertThat(packet.size).isEqualTo(16) + assertThat(OnePlusFastCrc16.check(packet)).isTrue() + + val now = 5_000L + val parsed = OnePlusGlucoseParser.parseControlPacket(packet, nowMs = now) + requireNotNull(parsed) + assertThat(parsed.opcode).isEqualTo(0x4f) + val sample = requireNotNull(parsed.sample) + assertThat(sample.mgdl).isEqualTo(100.0) + assertThat(sample.timestampMs).isEqualTo(now) + assertThat(sample.sequence).isEqualTo(7L) + assertThat(sample.trendSlopeMgdlPerMin).isEqualTo(0.0) + } + + @Test + fun `parse EGV1 rejects bad CRC`() { + val body = hex("4F00070000000000000064000600") + val packet = appendCrc(body) + packet[packet.lastIndex] = (packet[packet.lastIndex].toInt() xor 0xff).toByte() + assertThat(OnePlusGlucoseParser.parseControlPacket(packet, nowMs = 1L)).isNull() + } + + @Test + fun `parse rejects unknown opcode and short packets`() { + assertThat(OnePlusGlucoseParser.parseControlPacket(byteArrayOf(0x01), nowMs = 1L)).isNull() + assertThat(OnePlusGlucoseParser.parseControlPacket(ByteArray(10) { 0x4e }, nowMs = 1L)).isNull() + } + + @Test + fun `negative trend rate`() { + val packet = buildEgv2(trend = -5) // -0.5 mg/dL/min + val sample = OnePlusGlucoseParser.parse(packet, nowMs = 10_000L) + requireNotNull(sample) + assertThat(sample.trendSlopeMgdlPerMin).isEqualTo(-0.5) + } + + private fun buildEgv2( + glucoseMasked: Int = 120, + sequence: Int = 1, + age: Int = 5, + state: Int = OnePlusCalibrationState.Ok.value, + trend: Int = 0, + sessionAge: Int = 1000, + status: Int = 0, + flags: Int = 0, + ): ByteArray { + val buf = ByteBuffer.allocate(19).order(ByteOrder.LITTLE_ENDIAN) + buf.put(0x4e.toByte()) + buf.put(status.toByte()) + buf.putInt(sessionAge) + buf.putShort(sequence.toShort()) + buf.putShort(0) // bogus + buf.putShort(age.toShort()) + buf.putShort(glucoseMasked.toShort()) + buf.put(state.toByte()) + buf.put(trend.toByte()) + buf.putShort(0) // predicted + buf.put(flags.toByte()) + return buf.array() + } + + private fun appendCrc(body: ByteArray): ByteArray { + val crc = OnePlusFastCrc16.calculate(body, body.size) + return body + crc + } + + private fun hex(s: String): ByteArray { + val clean = s.replace(" ", "").replace("-", "") + require(clean.length % 2 == 0) + return ByteArray(clean.length / 2) { i -> + clean.substring(i * 2, i * 2 + 2).toInt(16).toByte() + } + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartMessageTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartMessageTest.kt new file mode 100644 index 000000000000..588360a90c9b --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartMessageTest.kt @@ -0,0 +1,65 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class OnePlusSessionStartMessageTest { + + @Test + fun sessionStartTx_lengthAndCrc() { + val packet = OnePlusSessionStartTx.build( + dexTimeSeconds = 100, + startTimeEpochMs = 1_700_000_000_000L, + ) + assertThat(packet).hasLength(OnePlusSessionStartTx.PACKET_LENGTH) + assertThat(packet[0]).isEqualTo(OnePlusSessionStartTx.OPCODE) + assertThat(OnePlusFastCrc16.check(packet)).isTrue() + val buf = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN) + buf.get() + assertThat(buf.int).isEqualTo(100) + assertThat(buf.int).isEqualTo(1_700_000_000) + } + + @Test + fun sessionStartRx_parsesOkay() { + val body = ByteBuffer.allocate(17).order(ByteOrder.LITTLE_ENDIAN) + body.put(OnePlusSessionStartRx.OPCODE) + body.put(0x00) // status + body.put(0x01) // info OK + body.putInt(10) + body.putInt(20) + body.putInt(30) + val packet = body.array() + val crc = OnePlusFastCrc16.calculate(packet, 15) + packet[15] = crc[0] + packet[16] = crc[1] + + val rx = OnePlusSessionStartRx.parse(packet) + assertThat(rx).isNotNull() + assertThat(rx!!.isOkay()).isTrue() + assertThat(rx.sessionStartTime).isEqualTo(20) + assertThat(rx.transmitterTime).isEqualTo(30) + assertThat(rx.message()).isEqualTo("OK") + } + + @Test + fun sessionStartRx_alreadyStarted() { + val body = ByteBuffer.allocate(17).order(ByteOrder.LITTLE_ENDIAN) + body.put(OnePlusSessionStartRx.OPCODE) + body.put(0x00) + body.put(0x02) + body.putInt(1) + body.putInt(2) + body.putInt(3) + val packet = body.array() + val crc = OnePlusFastCrc16.calculate(packet, 15) + packet[15] = crc[0] + packet[16] = crc[1] + + val rx = OnePlusSessionStartRx.parse(packet)!! + assertThat(rx.isAlreadyStarted()).isTrue() + assertThat(rx.isOkay()).isFalse() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopMessageTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopMessageTest.kt new file mode 100644 index 000000000000..c6b49d5fe92b --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopMessageTest.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class OnePlusSessionStopMessageTest { + + @Test + fun sessionStopTx_lengthAndCrc() { + val packet = OnePlusSessionStopTx.build(stopTimeDexSeconds = 12345) + assertThat(packet).hasLength(OnePlusSessionStopTx.PACKET_LENGTH) + assertThat(packet[0]).isEqualTo(OnePlusSessionStopTx.OPCODE) + assertThat(OnePlusFastCrc16.check(packet)).isTrue() + val buf = ByteBuffer.wrap(packet).order(ByteOrder.LITTLE_ENDIAN) + buf.get() + assertThat(buf.int).isEqualTo(12345) + } + + @Test + fun sessionStopRx_parsesOkay() { + val body = ByteBuffer.allocate(17).order(ByteOrder.LITTLE_ENDIAN) + body.put(OnePlusSessionStopRx.OPCODE) + body.put(0x00) // status + body.put(0x01) // received + body.putInt(50) // stop + body.putInt(10) // start + body.putInt(60) // tx time + val packet = body.array() + val crc = OnePlusFastCrc16.calculate(packet, 15) + packet[15] = crc[0] + packet[16] = crc[1] + + val rx = OnePlusSessionStopRx.parse(packet) + assertThat(rx).isNotNull() + assertThat(rx!!.isOkay()).isTrue() + assertThat(rx.sessionStopTime).isEqualTo(50) + assertThat(rx.transmitterTime).isEqualTo(60) + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeMessageTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeMessageTest.kt new file mode 100644 index 000000000000..2da77a5eed06 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeMessageTest.kt @@ -0,0 +1,55 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder + +class OnePlusTransmitterTimeMessageTest { + + @Test + fun transmitterTimeTx_lengthAndCrc() { + val packet = OnePlusTransmitterTimeTx.request() + assertThat(packet).hasLength(OnePlusTransmitterTimeTx.PACKET_LENGTH) + assertThat(packet[0]).isEqualTo(OnePlusTransmitterTimeTx.OPCODE) + assertThat(OnePlusFastCrc16.check(packet)).isTrue() + } + + @Test + fun transmitterTimeRx_sessionInProgress() { + // Minimal 10-byte body + CRC padding to make FastCRC16.check pass over full packet. + // Packet: op | status | current(4) | sessionStart(4) | crc(2) = 12 bytes common in Ob1. + val body = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN) + body.put(OnePlusTransmitterTimeRx.OPCODE) + body.put(0x00) // status + body.putInt(3600) // currentTime + body.putInt(0) // sessionStart + val packet = body.array() + val crc = OnePlusFastCrc16.calculate(packet, 10) + packet[10] = crc[0] + packet[11] = crc[1] + + val rx = OnePlusTransmitterTimeRx.parse(packet) + assertThat(rx).isNotNull() + assertThat(rx!!.sessionInProgress()).isTrue() + assertThat(rx.sessionAgeSeconds()).isEqualTo(3600L) + assertThat(rx.currentTimeSeconds).isEqualTo(3600) + } + + @Test + fun transmitterTimeRx_notStarted() { + val body = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN) + body.put(OnePlusTransmitterTimeRx.OPCODE) + body.put(0x00) + body.putInt(100) + body.putInt(-1) // INVALID_TIME + val packet = body.array() + val crc = OnePlusFastCrc16.calculate(packet, 10) + packet[10] = crc[0] + packet[11] = crc[1] + + val rx = OnePlusTransmitterTimeRx.parse(packet)!! + assertThat(rx.sessionInProgress()).isFalse() + assertThat(rx.realSessionStartEpochMs()).isNull() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OemAwareReconnectPolicyTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OemAwareReconnectPolicyTest.kt new file mode 100644 index 000000000000..94a658ba83e1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OemAwareReconnectPolicyTest.kt @@ -0,0 +1,39 @@ +package app.aaps.plugins.dexcomoneplus.reconnect + +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OemAwareReconnectPolicyTest { + + private val policy = OemAwareReconnectPolicy() + + @Test + fun `pixel profile retries within connectRetryCount`() { + val profile = DeviceProfileRegistry.PixelDefault + assertThat(policy.shouldRetry(0, profile)).isTrue() + assertThat(policy.shouldRetry(profile.connectRetryCount - 1, profile)).isTrue() + assertThat(policy.shouldRetry(profile.connectRetryCount, profile)).isFalse() + // Non-aggressive: flat base delay, independent of attempt index. + assertThat(policy.nextDelayMs(0, profile)).isEqualTo(profile.connectRetryDelayMs) + assertThat(policy.nextDelayMs(5, profile)).isEqualTo(profile.connectRetryDelayMs) + } + + @Test + fun `aggressive profile uses fast first retry then capped linear backoff`() { + val profile = DeviceProfileRegistry.SamsungDefault + assertThat(profile.aggressiveReconnect).isTrue() + assertThat(profile.connectRetryDelayMs).isEqualTo(10_000L) + assertThat(profile.requestMtuOnConnect).isFalse() + assertThat(profile.autoConnectFromAttempt).isEqualTo(0) + assertThat(profile.requireAdvBeforeConnect).isTrue() + assertThat(profile.preConnectScanMs).isEqualTo(8_000L) + // First reconnect is fast to catch the next ADV window (was base*2 = 20 s). + assertThat(policy.nextDelayMs(1, profile)).isEqualTo(OemAwareReconnectPolicy.FIRST_RETRY_MS) + // Then linear from the base… + assertThat(policy.nextDelayMs(2, profile)).isEqualTo(profile.connectRetryDelayMs) + assertThat(policy.nextDelayMs(3, profile)).isEqualTo(profile.connectRetryDelayMs * 2) + // …capped so late attempts never stretch to minute-scale gaps. + assertThat(policy.nextDelayMs(10, profile)).isEqualTo(OemAwareReconnectPolicy.MAX_RECONNECT_DELAY_MS) + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt new file mode 100644 index 000000000000..bc17311c7732 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt @@ -0,0 +1,207 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import android.bluetooth.le.ScanCallback +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusBleScannerAndroidTest { + + @Test + fun `nameMatches accepts DX02 DX01 DXCM family only`() { + assertThat(OnePlusBleScannerAndroid.nameMatches("DXCM12")).isTrue() + assertThat(OnePlusBleScannerAndroid.nameMatches("DX02aS")).isTrue() + assertThat(OnePlusBleScannerAndroid.nameMatches("DX01xx")).isTrue() + assertThat(OnePlusBleScannerAndroid.nameMatches("DexcomONE")).isFalse() + assertThat(OnePlusBleScannerAndroid.nameMatches("Dexcom65")).isFalse() + } + + @Test + fun `one silent scan window is not enough to back off`() { + val state = OnePlusBleScannerAndroid.nextSilentScanState(previousSilentScans = 0, heardAnything = false) + + assertThat(state.silentScans).isEqualTo(1) + assertThat(state.backOff).isFalse() + } + + @Test + fun `two silent windows in a row trigger the cool-down and restart the counter`() { + val first = OnePlusBleScannerAndroid.nextSilentScanState(previousSilentScans = 0, heardAnything = false) + val second = OnePlusBleScannerAndroid.nextSilentScanState(first.silentScans, heardAnything = false) + + assertThat(second.backOff).isTrue() + assertThat(second.silentScans).isEqualTo(0) + } + + @Test + fun `a still blind scanner backs off again after the next pair of silent windows`() { + // The back-off must be repeatable, not a one-shot: a sensor out of range for hours keeps the + // app scanning less until it answers again. + var silent = 0 + val backOffs = (1..4).count { + val state = OnePlusBleScannerAndroid.nextSilentScanState(silent, heardAnything = false) + silent = state.silentScans + state.backOff + } + + assertThat(backOffs).isEqualTo(2) + } + + @Test + fun `hearing any advertisement clears the silent counter`() { + val state = OnePlusBleScannerAndroid.nextSilentScanState(previousSilentScans = 1, heardAnything = true) + + assertThat(state.silentScans).isEqualTo(0) + assertThat(state.backOff).isFalse() + } + + @Test + fun `filtered silence does not itself request a probe until five windows`() { + assertThat(OnePlusBleScannerAndroid.shouldRunUnfilteredThrottleProbe(0)).isFalse() + assertThat(OnePlusBleScannerAndroid.shouldRunUnfilteredThrottleProbe(2)).isFalse() + assertThat(OnePlusBleScannerAndroid.shouldRunUnfilteredThrottleProbe(4)).isFalse() + assertThat(OnePlusBleScannerAndroid.shouldRunUnfilteredThrottleProbe(5)).isTrue() + assertThat(OnePlusBleScannerAndroid.shouldRunUnfilteredThrottleProbe(10)).isTrue() + } + + @Test + fun `scan-failed back-off is the OS refusal codes only`() { + assertThat( + OnePlusBleScannerAndroid.shouldBackOffOnScanFailed( + ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED, + ), + ).isTrue() + assertThat( + OnePlusBleScannerAndroid.shouldBackOffOnScanFailed( + ScanCallback.SCAN_FAILED_ALREADY_STARTED, + ), + ).isFalse() + } + + @Test + fun `nameMatches rejects unrelated names`() { + assertThat(OnePlusBleScannerAndroid.nameMatches(null)).isFalse() + assertThat(OnePlusBleScannerAndroid.nameMatches("")).isFalse() + assertThat(OnePlusBleScannerAndroid.nameMatches("Eversense365")).isFalse() + assertThat(OnePlusBleScannerAndroid.nameMatches("Galaxy Watch")).isFalse() + } + + @Test + fun `target address is normalized for hardware scan filter`() { + assertThat( + OnePlusBleScannerAndroid.normalizeTargetAddress("da:3b:12:0d:5b:b7"), + ).isEqualTo("DA:3B:12:0D:5B:B7") + } + + @Test + fun `FEBC neighbours count as G7 family unless they carry a G6 marketing name`() { + // G7 / ONE+ frequently advertise without a local name. + assertThat(OnePlusBleScannerAndroid.isG7FamilyAdvertisement(null)).isTrue() + assertThat(OnePlusBleScannerAndroid.isG7FamilyAdvertisement("DX021H")).isTrue() + assertThat(OnePlusBleScannerAndroid.isG7FamilyAdvertisement("DXCM99")).isTrue() + assertThat(OnePlusBleScannerAndroid.isG7FamilyAdvertisement("Dexcom65")).isFalse() + assertThat(OnePlusBleScannerAndroid.isG7FamilyAdvertisement("Galaxy Watch")).isFalse() + } + + @Test + fun `wait result exposes the strongest foreign transmitter for the stale-MAC diagnostic`() { + val weak = OnePlusScanResult(address = "AA:BB:CC:DD:EE:01", name = "DX021H", rssi = -88) + val strong = OnePlusScanResult(address = "AA:BB:CC:DD:B8:92", name = "DX021H", rssi = -51) + + val result = OnePlusAdvWaitResult(target = null, foreign = listOf(weak, strong)) + + assertThat(result.strongestForeign()).isEqualTo(strong) + assertThat(OnePlusAdvWaitResult().strongestForeign()).isNull() + } + + // ------------ autoSelectSingle(): what the screen may decide on its own ------------ + + @Test + fun `nothing heard is nothing to connect to`() { + assertThat(OnePlusBleScannerAndroid.autoSelectSingle(emptyList())).isNull() + } + + @Test + fun `one sensor in range may be selected for the user`() { + val only = OnePlusScanResult(address = "AA:BB:CC:DD:EE:01", name = "DX021H", rssi = -60) + + assertThat(OnePlusBleScannerAndroid.autoSelectSingle(listOf(only))).isEqualTo(only) + } + + @Test + fun `two sensors in range are a question for the user, not a score`() { + // The 4-digit code is not in the advertisement, so nothing here can tell them apart. + val near = OnePlusScanResult(address = "AA:BB:CC:DD:EE:01", name = "DX021H", rssi = -45) + val far = OnePlusScanResult(address = "AA:BB:CC:DD:EE:02", name = "DX02aS", rssi = -85) + + assertThat(OnePlusBleScannerAndroid.autoSelectSingle(listOf(near, far))).isNull() + } + + @Test + fun `the sensor being replaced is not picked again when another one answers`() { + // Old sensor still on the arm and loud, new sensor just applied and quiet. Selecting the + // loud one would connect the user back to the sensor they are replacing. + val storedSensor = OnePlusScanResult(address = "AA:BB:CC:DD:EE:FF", name = "DX02aS", rssi = -45) + val newSensor = OnePlusScanResult(address = "11:22:33:44:55:66", name = "DX021H", rssi = -80) + + assertThat(OnePlusBleScannerAndroid.autoSelectSingle(listOf(storedSensor, newSensor))).isNull() + } + + // ------------ autoSelect(): the code on screen decides whether anything is sticky ------------ + + @Test + fun `a new code selects nothing while two sensors answer`() { + // scanHintFor drops the stored MAC when the code is another sensor's, so nothing is sticky. + val hintForNewSensor = OnePlusStoredSession(identity = OnePlusSensorIdentity(pin = "5678")) + val first = OnePlusScanResult(address = STORED_MAC, name = "DX02aS", rssi = -45) + val second = OnePlusScanResult(address = "11:22:33:44:55:66", name = "DX021H", rssi = -80) + + assertThat(OnePlusBleScannerAndroid.autoSelect(listOf(first, second), hintForNewSensor)).isNull() + } + + @Test + fun `a new code still takes the single sensor that answers`() { + val hintForNewSensor = OnePlusStoredSession(identity = OnePlusSensorIdentity(pin = "5678")) + val only = OnePlusScanResult(address = "11:22:33:44:55:66", name = "DX021H", rssi = -70) + + assertThat(OnePlusBleScannerAndroid.autoSelect(listOf(only), hintForNewSensor)).isEqualTo(only) + } + + @Test + fun `the stored sensor stays selected while its own code is on screen`() { + // A reconnect: the user is not choosing a sensor, so it is theirs even among several, and + // even before the scan has heard it. + val reconnect = storedSession() + val neighbour = OnePlusScanResult(address = "11:22:33:44:55:66", name = "DX021H", rssi = -50) + + val beforeAnyScan = OnePlusBleScannerAndroid.autoSelect(emptyList(), reconnect)!! + assertThat(beforeAnyScan.address).isEqualTo(STORED_MAC) + assertThat(beforeAnyScan.name).isEqualTo("DX02aS") + + val amongOthers = OnePlusBleScannerAndroid.autoSelect(listOf(neighbour), reconnect)!! + assertThat(amongOthers.address).isEqualTo(STORED_MAC) + } + + @Test + fun `a live sighting of the stored sensor wins over the stored one`() { + // The live hit carries the fresh ADV the driver connects in-window with. + val live = OnePlusScanResult(address = STORED_MAC, name = "DX02aS", rssi = -62) + val neighbour = OnePlusScanResult(address = "11:22:33:44:55:66", name = "DX021H", rssi = -50) + + val picked = OnePlusBleScannerAndroid.autoSelect(listOf(neighbour, live), storedSession()) + + assertThat(picked).isSameInstanceAs(live) + } + + private fun storedSession() = OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = "1234"), + lastMac = STORED_MAC, + lastDeviceName = "DX02aS", + ) + + private companion object { + + const val STORED_MAC = "AA:BB:CC:DD:EE:FF" + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudgetTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudgetTest.kt new file mode 100644 index 000000000000..b7bf098c4d49 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudgetTest.kt @@ -0,0 +1,120 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class OnePlusScanBudgetTest { + + @BeforeEach + fun reset() { + OnePlusScanBudget.reset() + } + + @Test + fun `starts below the reserve are never delayed`() { + repeat(OnePlusScanBudget.MAX_STARTS_PER_WINDOW - 1) { OnePlusScanBudget.record(1_000L) } + + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(0L) + } + + @Test + fun `a full window defers the next start until the oldest start ages out`() { + repeat(OnePlusScanBudget.MAX_STARTS_PER_WINDOW) { OnePlusScanBudget.record(1_000L + it) } + + // Oldest start is at 1_000; the window frees at 1_000 + WINDOW_MS. + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(OnePlusScanBudget.WINDOW_MS) + assertThat(OnePlusScanBudget.waitMsFor(11_000L)).isEqualTo(OnePlusScanBudget.WINDOW_MS - 10_000L) + assertThat(OnePlusScanBudget.waitMsFor(1_000L + OnePlusScanBudget.WINDOW_MS)).isEqualTo(0L) + } + + @Test + fun `budget keeps one platform slot free for the UI discovery scan`() { + assertThat(OnePlusScanBudget.MAX_STARTS_PER_WINDOW) + .isLessThan(OnePlusScanBudget.MAX_STARTS_PER_WINDOW_PLATFORM) + } + + @Test + fun `two slots waiting concurrently stay inside the platform quota`() { + // Both slots restart a bounded 8 s wait every ~8.25 s. Without the shared budget that is + // ~15 starts per minute — over the platform throttle, which blinds both silently. + var now = 0L + var starts = 0 + val cadenceMs = 8_250L / 2 // two slots interleaved + while (now < 60_000L) { + val wait = OnePlusScanBudget.reserve(now) + if (wait > 0L) { + now += wait + continue + } + starts++ + now += cadenceMs + } + + // Any 30 s window must never exceed what we allow ourselves. + assertThat(OnePlusScanBudget.startsInWindow(60_000L)) + .isAtMost(OnePlusScanBudget.MAX_STARTS_PER_WINDOW) + assertThat(starts).isAtMost(2 * OnePlusScanBudget.MAX_STARTS_PER_WINDOW + 1) + } + + @Test + fun `reserve books the slot atomically so two racing slots cannot share it`() { + repeat(OnePlusScanBudget.MAX_STARTS_PER_WINDOW - 1) { OnePlusScanBudget.reserve(1_000L) } + + // Last free slot goes to the first caller; the racing one is deferred. + assertThat(OnePlusScanBudget.reserve(1_000L)).isEqualTo(0L) + assertThat(OnePlusScanBudget.reserve(1_000L)).isGreaterThan(0L) + assertThat(OnePlusScanBudget.startsInWindow(1_000L)) + .isEqualTo(OnePlusScanBudget.MAX_STARTS_PER_WINDOW) + } + + @Test + fun `an explicit block holds back starts even when the quota is free`() { + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(0L) + + OnePlusScanBudget.blockFor(nowMs = 1_000L, durationMs = 5_000L) + + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(5_000L) + assertThat(OnePlusScanBudget.waitMsFor(3_000L)).isEqualTo(3_000L) + assertThat(OnePlusScanBudget.waitMsFor(6_000L)).isEqualTo(0L) + } + + @Test + fun `a longer block wins and a shorter one cannot shorten it`() { + OnePlusScanBudget.blockFor(nowMs = 1_000L, durationMs = 10_000L) + OnePlusScanBudget.blockFor(nowMs = 1_000L, durationMs = 2_000L) + + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(10_000L) + } + + @Test + fun `reserve does not book a slot while blocked`() { + OnePlusScanBudget.blockFor(nowMs = 1_000L, durationMs = 5_000L) + + assertThat(OnePlusScanBudget.reserve(1_000L)).isGreaterThan(0L) + assertThat(OnePlusScanBudget.startsInWindow(1_000L)).isEqualTo(0) + } + + @Test + fun `reset clears an active block`() { + OnePlusScanBudget.blockFor(nowMs = 1_000L, durationMs = 30_000L) + + OnePlusScanBudget.reset() + + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(0L) + } + + @Test + fun `a negative block duration is treated as no block`() { + OnePlusScanBudget.blockFor(nowMs = 1_000L, durationMs = -5_000L) + + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(0L) + } + + @Test + fun `a backwards clock jump cannot wedge the budget`() { + repeat(OnePlusScanBudget.MAX_STARTS_PER_WINDOW) { OnePlusScanBudget.record(500_000L) } + + assertThat(OnePlusScanBudget.waitMsFor(1_000L)).isEqualTo(0L) + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRxTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRxTest.kt new file mode 100644 index 000000000000..98247528c71b --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRxTest.kt @@ -0,0 +1,45 @@ +package app.aaps.plugins.dexcomoneplus.session + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusAuthStatusRxTest { + + @Test + fun parse_auth2_bonded1_isRejected() { + val status = OnePlusAuthStatusRx.parse(byteArrayOf(0x05, 0x02, 0x01)) + assertThat(status).isNotNull() + assertThat(status!!.authenticated).isEqualTo(2) + assertThat(status.bonded).isEqualTo(1) + assertThat(status.isAuthenticated).isFalse() + assertThat(status.sensorReportsBonded).isTrue() + assertThat(status.needsKeyRefresh).isFalse() + } + + @Test + fun parse_auth1_bonded1_isOk() { + val status = OnePlusAuthStatusRx.parse(byteArrayOf(0x05, 0x01, 0x01)) + assertThat(status!!.isAuthenticated).isTrue() + assertThat(status.sensorReportsBonded).isTrue() + } + + @Test + fun parse_bond3_needsKeyRefresh() { + val status = OnePlusAuthStatusRx.parse(byteArrayOf(0x05, 0x01, 0x03)) + assertThat(status!!.needsKeyRefresh).isTrue() + } + + @Test + fun parse_ignoresNonAuthStatus() { + assertThat(OnePlusAuthStatusRx.parse(byteArrayOf(0x04, 0x01, 0x01))).isNull() + assertThat(OnePlusAuthStatusRx.parse(byteArrayOf(0x05))).isNull() + } + + @Test + fun authResult_invalidateFlag_equals() { + val a = AuthResult(ok = false, message = "key refresh", invalidateSharedKey = true) + val b = AuthResult(ok = false, message = "key refresh", invalidateSharedKey = true) + assertThat(a).isEqualTo(b) + assertThat(a.invalidateSharedKey).isTrue() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionCyclePolicyTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionCyclePolicyTest.kt new file mode 100644 index 000000000000..db1f0f1ce959 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionCyclePolicyTest.kt @@ -0,0 +1,403 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import app.aaps.plugins.dexcomoneplus.oem.OemProfileId +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanBudget +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusBleSessionCyclePolicyTest { + + @Test + fun `successful collection waits for advertisement and suppresses SessionStart`() { + val reconnectAttempt = OnePlusBleSessionCyclePolicy.POST_COLLECTION_RECONNECT_ATTEMPT + + assertThat( + OnePlusBleSessionCyclePolicy.waitForAdvertisementAfterExit( + sessionProvedHealthy = true, + ), + ).isTrue() + assertThat( + OnePlusSessionStartPolicy.wantSessionStartOnAttempt( + requestNewSensorStart = true, + attempt = reconnectAttempt, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.applyFailureBudget( + preparedPostCollectionAdvertisement = true, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.requireFreshAdvertisementBeforeReconnect( + persistentAdvertisementMode = true, + ), + ).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.allowConnection( + restoredSessionMode = true, + advertisementFresh = false, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.allowConnection( + restoredSessionMode = true, + advertisementFresh = true, + ), + ).isTrue() + } + + @Test + fun `a restored session can leave the persistent wait through the blind-connect escape`() { + val silence = OnePlusBleSessionCyclePolicy.BLIND_CONNECT_AFTER_ADV_SILENCE_MS + + // Before the escape delay the restored session still refuses an ADV-less connect… + assertThat(OnePlusBleSessionCyclePolicy.authorizeBlindConnect(silence - 1)).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.allowConnection( + restoredSessionMode = true, + advertisementFresh = false, + blindFallbackAuthorized = false, + ), + ).isFalse() + + // …and once the silence is long enough it may connect without a sighting. Without this the + // wait is unbounded (field log 2026-08-03: 18 min, no glucose, no error, no retry). + assertThat(OnePlusBleSessionCyclePolicy.authorizeBlindConnect(silence)).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.allowConnection( + restoredSessionMode = true, + advertisementFresh = false, + blindFallbackAuthorized = true, + ), + ).isTrue() + } + + @Test + fun `stale MAC is suspected from silence alone — a foreign ONE+ is not required`() { + val threshold = OnePlusBleSessionCyclePolicy.STALE_MAC_SUSPICION_AFTER_MS + + assertThat( + OnePlusBleSessionCyclePolicy.suspectStaleMac(continuousAdvSilenceMs = threshold, foreignSightings = 0), + ).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.suspectStaleMac(continuousAdvSilenceMs = threshold - 1, foreignSightings = 0), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.suspectStaleMac(continuousAdvSilenceMs = threshold - 1, foreignSightings = 1), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.suspectStaleMac(continuousAdvSilenceMs = threshold, foreignSightings = 1), + ).isTrue() + } + + @Test + fun `the wait reports whole minutes of silence`() { + assertThat(OnePlusBleSessionCyclePolicy.advSilenceMinutes(-5L)).isEqualTo(0L) + assertThat(OnePlusBleSessionCyclePolicy.advSilenceMinutes(59_999L)).isEqualTo(0L) + assertThat(OnePlusBleSessionCyclePolicy.advSilenceMinutes(60_000L)).isEqualTo(1L) + assertThat(OnePlusBleSessionCyclePolicy.advSilenceMinutes(11L * 60_000L)).isEqualTo(11L) + } + + @Test + fun `blind-connect escape fires before the stale-MAC suspicion is conclusive`() { + assertThat(OnePlusBleSessionCyclePolicy.BLIND_CONNECT_AFTER_ADV_SILENCE_MS) + .isLessThan(OnePlusBleSessionCyclePolicy.STALE_MAC_SUSPICION_AFTER_MS) + } + + @Test + fun `warm-up Control traffic proves the session so a duty cycle does not burn the retry budget`() { + // The reported field failure: a warming sensor never sends usable glucose, so every duty + // cycle used the bounded budget and warm-up always ended in FAILED. + assertThat( + OnePlusBleSessionCyclePolicy.controlTrafficProvesSession(OnePlusWarmupState.Phase.WARMING), + ).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.controlTrafficProvesSession(OnePlusWarmupState.Phase.READY), + ).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.waitForAdvertisementAfterExit( + sessionProvedHealthy = OnePlusBleSessionCyclePolicy.controlTrafficProvesSession( + OnePlusWarmupState.Phase.WARMING, + ), + ), + ).isTrue() + + // A stopped / expired / failed sensor keeps the bounded budget: waiting for its advertisement + // would hide a real failure. + listOf( + OnePlusWarmupState.Phase.FAILED, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.PAIRING, + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING, + ).forEach { phase -> + assertThat(OnePlusBleSessionCyclePolicy.controlTrafficProvesSession(phase)).isFalse() + } + } + + @Test + fun `a session with proven Control traffic recovers from an exhausted retry budget`() { + assertThat( + OnePlusBleSessionCyclePolicy.recoverExhaustedBudgetWithPersistentWait( + sessionEverProvedControlChannel = true, + ), + ).isTrue() + } + + @Test + fun `a sensor that never sent Control traffic still ends in the terminal failure`() { + // Wrong PIN or wrong sensor — but also the case that made a working pairing impossible: + // a sensor with no session started authenticates fully, then hangs up on the first glucose + // request. Recovering there would loop for ever, and SessionStart (attempt 0 only) could + // never be re-issued. The terminal failure is what lets the user start the sensor again. + assertThat( + OnePlusBleSessionCyclePolicy.recoverExhaustedBudgetWithPersistentWait( + sessionEverProvedControlChannel = false, + ), + ).isFalse() + } + + @Test + fun `the warm-up deadline survives the connection phases and is dropped when warm-up ends`() { + val endsAt = 1_700_000_000_000L + + // Learned from a WARMING packet… + assertThat( + OnePlusBleSessionCyclePolicy.warmupDeadlineAfter( + previousEndsAtMs = null, + state = OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + endsAtEpochMs = endsAt, + ), + ), + ).isEqualTo(endsAt) + + // …kept while the link is re-established (the UI countdown used to blank out here)… + listOf( + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING, + OnePlusWarmupState.Phase.PAIRING, + ).forEach { phase -> + assertThat( + OnePlusBleSessionCyclePolicy.warmupDeadlineAfter( + previousEndsAtMs = endsAt, + state = OnePlusWarmupState(phase = phase), + ), + ).isEqualTo(endsAt) + } + + // …a WARMING packet without its own clock keeps the known deadline… + assertThat( + OnePlusBleSessionCyclePolicy.warmupDeadlineAfter( + previousEndsAtMs = endsAt, + state = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.WARMING), + ), + ).isEqualTo(endsAt) + + // …and it is dropped once warm-up is over, stopped or failed. + listOf( + OnePlusWarmupState.Phase.READY, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.FAILED, + ).forEach { phase -> + assertThat( + OnePlusBleSessionCyclePolicy.warmupDeadlineAfter( + previousEndsAtMs = endsAt, + state = OnePlusWarmupState(phase = phase), + ), + ).isNull() + } + } + + @Test + fun `exit before any control traffic and unprepared retry retain failure budget`() { + assertThat( + OnePlusBleSessionCyclePolicy.waitForAdvertisementAfterExit( + sessionProvedHealthy = false, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.applyFailureBudget( + preparedPostCollectionAdvertisement = false, + ), + ).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.requireFreshAdvertisementBeforeReconnect( + persistentAdvertisementMode = false, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.allowConnection( + restoredSessionMode = false, + advertisementFresh = false, + ), + ).isTrue() + } + + @Test + fun `persistent failure raises the strategy index instead of pinning it at 1`() { + assertThat(OnePlusBleSessionCyclePolicy.nextPersistentAttempt(1)).isEqualTo(2) + assertThat(OnePlusBleSessionCyclePolicy.nextPersistentAttempt(2)).isEqualTo(3) + } + + @Test + fun `Samsung still parks autoConnect on attempt 1 when there is no fresh ADV`() { + // SamsungDefault.autoConnectFromAttempt = 0. This is the field-proven park; do not change it. + assertThat( + OnePlusBleSessionCyclePolicy.useAutoConnect( + advFresh = false, + attempt = 1, + autoConnectFromAttempt = 0, + ), + ).isTrue() + assertThat( + OnePlusBleSessionCyclePolicy.useAutoConnect( + advFresh = true, + attempt = 1, + autoConnectFromAttempt = 0, + ), + ).isFalse() + } + + @Test + fun `Generic reaches autoConnect on attempt 2, not on the pinned attempt 1`() { + assertThat( + OnePlusBleSessionCyclePolicy.useAutoConnect( + advFresh = false, + attempt = 1, + autoConnectFromAttempt = 2, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.useAutoConnect( + advFresh = false, + attempt = 2, + autoConnectFromAttempt = 2, + ), + ).isTrue() + } + + @Test + fun `Generic skips the ADV wait after a failed hard connect so autoConnect can run now`() { + assertThat( + OnePlusBleSessionCyclePolicy.skipAdvWaitAfterFailedConnect( + lastConnectUsedAutoConnect = false, + nextAttempt = 2, + autoConnectFromAttempt = 2, + ), + ).isTrue() + } + + @Test + fun `Samsung does not skip the ADV wait after a failed autoConnect — no GATT storm`() { + assertThat( + OnePlusBleSessionCyclePolicy.skipAdvWaitAfterFailedConnect( + lastConnectUsedAutoConnect = true, + nextAttempt = 2, + autoConnectFromAttempt = 0, + ), + ).isFalse() + } + + @Test + fun `a second blind connect waits a full silence window after the last one`() { + val silence = OnePlusBleSessionCyclePolicy.BLIND_CONNECT_AFTER_ADV_SILENCE_MS + + assertThat( + OnePlusBleSessionCyclePolicy.authorizeBlindConnect( + continuousAdvSilenceMs = silence, + msSinceLastBlindConnect = 30_000L, + ), + ).isFalse() + assertThat( + OnePlusBleSessionCyclePolicy.authorizeBlindConnect( + continuousAdvSilenceMs = silence + silence, + msSinceLastBlindConnect = silence, + ), + ).isTrue() + } + + @Test + fun `the persistent ADV wait stays inside the platform scan quota with both slots running`() { + val cycleMs = OnePlusBleSessionCyclePolicy.PERSISTENT_ADV_SCAN_MS + + OnePlusBleSessionCyclePolicy.ADV_WAIT_RESTART_DELAY_MS + val startsPerWindowPerSlot = OnePlusScanBudget.WINDOW_MS.toDouble() / cycleMs + val bothSlots = 2 * startsPerWindowPerSlot + + // The regression this guards: the wait used OemDeviceProfile.preConnectScanMs (3 s on + // Generic, 2 s on Pixel) plus a 250 ms pause, i.e. a 3.25 s / 2.25 s cycle. That is 18 and + // 27 scan starts per minute against a platform allowance of 10 — a single slot was over + // quota on its own, and the app throttled itself blind trying to compensate. + assertThat(bothSlots).isLessThan(OnePlusScanBudget.MAX_STARTS_PER_WINDOW.toDouble()) + assertThat(startsPerWindowPerSlot).isLessThan( + OnePlusScanBudget.MAX_STARTS_PER_WINDOW_PLATFORM.toDouble() / 2, + ) + } + + /** + * The busy-radio case: car Bluetooth, a headset playing audio, a crowded metro. Every connect + * fails and no ADV is heard for an hour. The session must keep trying, and must not turn that + * into a burst of connects. See the KDoc of [OnePlusBleSessionCyclePolicy]. + */ + @Test + fun `an hour of failed connects on a busy radio never ends the session and never bursts connects`() { + val hourMs = 60L * 60_000L + val stepMs = 10_000L + for (id in OemProfileId.entries) { + val profile = DeviceProfileRegistry.byId(id) + + // Asking for more radio time than audio leaves us correlated with peer status 19. + assertThat(profile.forceHighConnectionPriority).isFalse() + + // Never a terminal failure once the sensor has sent Control traffic. + assertThat(OnePlusBleSessionCyclePolicy.recoverExhaustedBudgetWithPersistentWait(true)).isTrue() + assertThat(OnePlusBleSessionCyclePolicy.applyFailureBudget(preparedPostCollectionAdvertisement = true)).isFalse() + + // A failed connect is retried without an ADV wait at most once in a row. + var attempt = OnePlusBleSessionCyclePolicy.POST_COLLECTION_RECONNECT_ATTEMPT + var lastUsedAutoConnect = false + var skipsInARow = 0 + repeat(50) { + val skip = OnePlusBleSessionCyclePolicy.skipAdvWaitAfterFailedConnect( + lastConnectUsedAutoConnect = lastUsedAutoConnect, + nextAttempt = OnePlusBleSessionCyclePolicy.nextPersistentAttempt(attempt), + autoConnectFromAttempt = profile.autoConnectFromAttempt, + ) + skipsInARow = if (skip) skipsInARow + 1 else 0 + assertThat(skipsInARow).isAtMost(1) + attempt = OnePlusBleSessionCyclePolicy.nextPersistentAttempt(attempt) + lastUsedAutoConnect = OnePlusBleSessionCyclePolicy.useAutoConnect( + advFresh = false, + attempt = attempt, + autoConnectFromAttempt = profile.autoConnectFromAttempt, + ) + } + + // Without any ADV, a connect is still tried once per silence window: never less, never more. + val blindAt = mutableListOf() + var t = 0L + while (t <= hourMs) { + val sinceBlind = blindAt.lastOrNull()?.let { t - it } + if (OnePlusBleSessionCyclePolicy.authorizeBlindConnect(t, sinceBlind)) blindAt += t + t += stepMs + } + val window = OnePlusBleSessionCyclePolicy.BLIND_CONNECT_AFTER_ADV_SILENCE_MS + assertThat(blindAt.first()).isEqualTo(window) + blindAt.zipWithNext { a, b -> assertThat(b - a).isEqualTo(window) } + assertThat(blindAt.size.toLong()).isEqualTo(hourMs / window) + } + } + + @Test + fun `the post-cycle guard outlasts a residual burst but never hides the next duty cycle`() { + val guard = OnePlusBleSessionCyclePolicy.POST_CYCLE_ADV_GUARD_MS + + // Field log 2026-08-20: the residual advertisement arrived 127 ms after the cycle closed. + assertThat(guard).isGreaterThan(1_000L) + // A G7 duty cycle is ~5 min, and the blind-connect escape fires at 4 min; the guard must be + // far below both so it can never swallow a genuine window or delay the escape. + assertThat(guard).isLessThan(OnePlusBleSessionCyclePolicy.BLIND_CONNECT_AFTER_ADV_SILENCE_MS / 10) + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiterTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiterTest.kt new file mode 100644 index 000000000000..5b29e7712982 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiterTest.kt @@ -0,0 +1,86 @@ +package app.aaps.plugins.dexcomoneplus.session + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +/** + * The invariant: one transmitter, one slot. Two sessions on one sensor corrupt both KEKS handshakes, + * so a refusal here is what keeps an activation from failing — see [OnePlusMacArbiter]. + */ +class OnePlusMacArbiterTest { + + private val mac = "C8:4E:07:B2:31:1F" + private val other = "D1:22:9C:4E:80:74" + + @BeforeEach + fun clear() { + OnePlusMacArbiter.reset() + } + + @Test + fun `the first slot to ask gets the sensor`() { + assertThat(OnePlusMacArbiter.claim(mac, "prod")).isTrue() + assertThat(OnePlusMacArbiter.ownerOf(mac)).isEqualTo("prod") + } + + @Test + fun `the other slot is refused the same sensor`() { + OnePlusMacArbiter.claim(mac, "prod") + assertThat(OnePlusMacArbiter.claim(mac, "staging")).isFalse() + assertThat(OnePlusMacArbiter.ownerOf(mac)).isEqualTo("prod") + } + + @Test + fun `case and padding do not let a second slot slip through`() { + // A MAC reaches the stores from a scan hit, an applicator parse or a restored session, and + // only some of those upper-case it. + OnePlusMacArbiter.claim(mac, "prod") + assertThat(OnePlusMacArbiter.claim(" c8:4e:07:b2:31:1f ", "staging")).isFalse() + } + + @Test + fun `a slot may re-claim what it already holds`() { + // Reconnects and repairs inside one slot are normal and must not be refused. + assertThat(OnePlusMacArbiter.claim(mac, "prod")).isTrue() + assertThat(OnePlusMacArbiter.claim(mac, "prod")).isTrue() + assertThat(OnePlusMacArbiter.claim(mac.lowercase(), "prod")).isTrue() + } + + @Test + fun `the two slots may hold two different sensors`() { + assertThat(OnePlusMacArbiter.claim(mac, "prod")).isTrue() + assertThat(OnePlusMacArbiter.claim(other, "staging")).isTrue() + } + + @Test + fun `moving a slot to another sensor frees the one it left`() { + OnePlusMacArbiter.claim(mac, "prod") + assertThat(OnePlusMacArbiter.claim(other, "prod")).isTrue() + assertThat(OnePlusMacArbiter.ownerOf(mac)).isNull() + // The sensor production walked away from is now available to the other slot. + assertThat(OnePlusMacArbiter.claim(mac, "staging")).isTrue() + } + + @Test + fun `release hands the sensor back`() { + OnePlusMacArbiter.claim(mac, "prod") + OnePlusMacArbiter.release("prod") + assertThat(OnePlusMacArbiter.ownerOf(mac)).isNull() + assertThat(OnePlusMacArbiter.claim(mac, "staging")).isTrue() + } + + @Test + fun `releasing a slot that holds nothing is harmless`() { + OnePlusMacArbiter.claim(mac, "prod") + OnePlusMacArbiter.release("staging") + assertThat(OnePlusMacArbiter.ownerOf(mac)).isEqualTo("prod") + } + + @Test + fun `a blank address is never claimable`() { + assertThat(OnePlusMacArbiter.claim("", "prod")).isFalse() + assertThat(OnePlusMacArbiter.claim(" ", "prod")).isFalse() + assertThat(OnePlusMacArbiter.ownerOf("")).isNull() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicyTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicyTest.kt new file mode 100644 index 000000000000..2530bc536aee --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicyTest.kt @@ -0,0 +1,66 @@ +package app.aaps.plugins.dexcomoneplus.session + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusSessionStartPolicyTest { + + @Test + fun attachOnly_whenSessionAlreadyInProgress() { + assertThat( + OnePlusSessionStartPolicy.decide( + requestNewSensorStart = true, + sessionAlreadyInProgress = true, + ), + ).isEqualTo(OnePlusSessionStartPolicy.Action.AttachOnly) + + assertThat( + OnePlusSessionStartPolicy.decide( + requestNewSensorStart = false, + sessionAlreadyInProgress = true, + ), + ).isEqualTo(OnePlusSessionStartPolicy.Action.AttachOnly) + } + + @Test + fun sessionStart_onlyWhenIdleAndRequested() { + assertThat( + OnePlusSessionStartPolicy.decide( + requestNewSensorStart = true, + sessionAlreadyInProgress = false, + ), + ).isEqualTo(OnePlusSessionStartPolicy.Action.SessionStart) + } + + @Test + fun egvOnly_whenIdleAndNotRequested() { + assertThat( + OnePlusSessionStartPolicy.decide( + requestNewSensorStart = false, + sessionAlreadyInProgress = false, + ), + ).isEqualTo(OnePlusSessionStartPolicy.Action.EgvOnly) + } + + @Test + fun reconnectAttempts_neverRequestSessionStart() { + assertThat( + OnePlusSessionStartPolicy.wantSessionStartOnAttempt( + requestNewSensorStart = true, + attempt = 0, + ), + ).isTrue() + assertThat( + OnePlusSessionStartPolicy.wantSessionStartOnAttempt( + requestNewSensorStart = true, + attempt = 1, + ), + ).isFalse() + assertThat( + OnePlusSessionStartPolicy.wantSessionStartOnAttempt( + requestNewSensorStart = false, + attempt = 0, + ), + ).isFalse() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartTest.kt new file mode 100644 index 000000000000..0f39dd73ae9b --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartTest.kt @@ -0,0 +1,30 @@ +package app.aaps.plugins.dexcomoneplus.session + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusSessionStartTest { + + @Test + fun `accepts 4 digit pairing code`() { + assertThat(OnePlusSessionStart.isValidPairingCode("1234")).isTrue() + assertThat(OnePlusSessionStart.isValidPairingCode(" 5678 ")).isTrue() + assertThat(OnePlusSessionStart.validationError("1234")).isNull() + } + + @Test + fun `rejects non digit or wrong length`() { + assertThat(OnePlusSessionStart.isValidPairingCode("12")).isFalse() + assertThat(OnePlusSessionStart.isValidPairingCode("12345")).isFalse() + assertThat(OnePlusSessionStart.isValidPairingCode("12ab")).isFalse() + assertThat(OnePlusSessionStart.validationError("abcd")).isNotNull() + } + + @Test + fun `rejects reserved short pairing codes from xDrip list`() { + assertThat(OnePlusSessionStart.isValidPairingCode("0006")).isFalse() + assertThat(OnePlusSessionStart.isValidPairingCode("6666")).isFalse() + assertThat(OnePlusSessionStart.isValidPairingCode("9999")).isFalse() + assertThat(OnePlusSessionStart.validationError("0006")).contains("reserved") + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClockTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClockTest.kt new file mode 100644 index 000000000000..c7a185f6f487 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClockTest.kt @@ -0,0 +1,53 @@ +package app.aaps.plugins.dexcomoneplus.warmup + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusWarmupClockTest { + + @Test + fun `resolveRemainingMs prefers remainingMs`() { + val state = OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + remainingMs = 12_000L, + endsAtEpochMs = 9_999_999L, + ) + assertThat(OnePlusWarmupClock.resolveRemainingMs(state, nowMs = 0L)).isEqualTo(12_000L) + } + + @Test + fun `resolveRemainingMs uses endsAt when remaining null`() { + val state = OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + remainingMs = null, + endsAtEpochMs = 50_000L, + ) + assertThat(OnePlusWarmupClock.resolveRemainingMs(state, nowMs = 20_000L)).isEqualTo(30_000L) + } + + @Test + fun `resolveRemainingMs returns null when no clock`() { + val state = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + assertThat(OnePlusWarmupClock.resolveRemainingMs(state, nowMs = 1L)).isNull() + } + + @Test + fun `warmingFromStart uses default 30 min and READY when elapsed`() { + val start = 1_000_000L + val mid = OnePlusWarmupClock.warmingFromStart( + startEpochMs = start, + nowMs = start + 10 * 60 * 1000L, + ) + assertThat(mid.phase).isEqualTo(OnePlusWarmupState.Phase.WARMING) + assertThat(mid.remainingMs).isEqualTo(20 * 60 * 1000L) + assertThat(mid.endsAtEpochMs).isEqualTo(start + OnePlusWarmupClock.DEFAULT_WARMUP_MS) + + val done = OnePlusWarmupClock.warmingFromStart( + startEpochMs = start, + nowMs = start + OnePlusWarmupClock.DEFAULT_WARMUP_MS + 1L, + ) + assertThat(done.phase).isEqualTo(OnePlusWarmupState.Phase.READY) + assertThat(done.remainingMs).isEqualTo(0L) + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml b/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml new file mode 100644 index 000000000000..12d22f0fe647 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusAndroidPlatform.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusAndroidPlatform.kt new file mode 100644 index 000000000000..0324185fefb6 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusAndroidPlatform.kt @@ -0,0 +1,44 @@ +package app.aaps.plugins.dexcomoneplus + +import android.content.Context +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClientAndroid +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefsAndroid +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerAndroid +import app.aaps.plugins.dexcomoneplus.session.OnePlusAndroidCpuLease +import app.aaps.plugins.dexcomoneplus.session.OnePlusCpuLease + +/** + * [OnePlusPlatform] on Android: the same four pieces the driver used to build from a `Context` + * itself, now built here so the driver no longer knows what a `Context` is. + */ +class OnePlusAndroidPlatform(context: Context) : OnePlusPlatform { + + private val appContext: Context = context.applicationContext + + override fun sensorPrefs(fileName: String): OnePlusSensorPrefs = + OnePlusSensorPrefsAndroid(appContext, fileName) + + override fun scanner(hint: OnePlusStoredSession?, slot: String): OnePlusBleScanner = + OnePlusBleScannerAndroid(appContext, sessionHint = hint, slot = slot) + + override fun gattClient(profile: OemDeviceProfile): OnePlusGattClient = + OnePlusGattClientAndroid(appContext, profile) + + override fun cpuLease(slot: String): OnePlusCpuLease = OnePlusAndroidCpuLease(appContext, slot) +} + +/** + * Attach an Android host to a driver. + * + * Kept so the screens and the plugin still read the way they always did. It is an extension, not a + * method on [OnePlusCgmDriver], because a `Context` has no place in a contract that two platforms + * share. + */ +fun OnePlusCgmDriver.setContext(context: Context) { + attach(OnePlusAndroidPlatform(context)) +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorAndroid.kt new file mode 100644 index 000000000000..15986852d567 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorAndroid.kt @@ -0,0 +1,29 @@ +package app.aaps.plugins.dexcomoneplus + +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors + +internal actual fun onePlusBleExecutor(): OnePlusBleExecutor = OnePlusAndroidBleExecutor() + +/** + * The single-threaded executor the driver has always used, behind [OnePlusBleExecutor]. + * + * Daemon, so a stuck session cannot keep the process alive, and named so a thread dump says which + * thread is blocked in the handshake. + */ +private class OnePlusAndroidBleExecutor : OnePlusBleExecutor { + + private val delegate: ExecutorService = Executors.newSingleThreadExecutor { r -> + Thread(r, "OnePlusBleExecutor").apply { isDaemon = true } + } + + /** Throws `RejectedExecutionException` after [shutdownNow], exactly as before. */ + override fun execute(block: () -> Unit) { + delegate.execute(block) + } + + /** Also interrupts the running cycle, which is what cuts `onePlusSleep` short. */ + override fun shutdownNow() { + delegate.shutdownNow() + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsedAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsedAndroid.kt new file mode 100644 index 000000000000..9efd3cc86e7c --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsedAndroid.kt @@ -0,0 +1,5 @@ +package app.aaps.plugins.dexcomoneplus + +import android.os.SystemClock + +internal actual fun onePlusElapsedMs(): Long = SystemClock.elapsedRealtime() diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogAndroid.kt new file mode 100644 index 000000000000..b457ff74da8f --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogAndroid.kt @@ -0,0 +1,19 @@ +package app.aaps.plugins.dexcomoneplus + +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +private val logger: Logger = LoggerFactory.getLogger(OnePlusLogMarkers.TAG) + +/** + * Android sink: slf4j, which AAPS already copies into `AndroidAPS.log` and into logcat under the + * same tag as before. See `OnePlusLog` for why this driver does not log straight to Android. + */ +internal actual fun onePlusLogWrite(level: OnePlusLogLevel, message: String, cause: Throwable?) { + when (level) { + OnePlusLogLevel.DEBUG -> logger.debug(message) + OnePlusLogLevel.INFO -> logger.info(message) + OnePlusLogLevel.WARN -> logger.warn(message) + OnePlusLogLevel.ERROR -> if (cause == null) logger.error(message) else logger.error(message, cause) + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleepAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleepAndroid.kt new file mode 100644 index 000000000000..fd5dfcf425ed --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleepAndroid.kt @@ -0,0 +1,10 @@ +package app.aaps.plugins.dexcomoneplus + +internal actual fun onePlusSleep(millis: Long): Boolean = + try { + Thread.sleep(millis) + true + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + false + } diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkState.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkState.kt new file mode 100644 index 000000000000..e6b9f06be3b1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusAudioLinkState.kt @@ -0,0 +1,55 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothProfile +import android.content.Context +import android.media.AudioManager +import android.os.Build + +/** + * The phone's Bluetooth audio links (car kit, headset) as one log fragment. + * + * Audio uses the same radio as BLE and goes first. The sensor link fails much more often while a + * car or a headset is connected, so every link loss is logged with this state. Without it a field + * log cannot show whether a lost reading came with audio in use. + */ +internal object OnePlusAudioLinkState { + + /** Never throws: a missing permission or service shows as `?` in the log. */ + fun describe(context: Context, adapter: BluetoothAdapter?): String { + val leAudio = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + profileState(adapter, BluetoothProfile.LE_AUDIO) + } else { + null + } + val musicActive = try { + (context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.isMusicActive + } catch (_: Throwable) { + null + } + return format( + a2dp = profileState(adapter, BluetoothProfile.A2DP), + headset = profileState(adapter, BluetoothProfile.HEADSET), + leAudio = leAudio, + musicActive = musicActive, + ) + } + + fun format(a2dp: Int?, headset: Int?, leAudio: Int?, musicActive: Boolean?): String = + "audio a2dp=${stateName(a2dp)} headset=${stateName(headset)} " + + "leAudio=${stateName(leAudio)} music=${musicActive?.let { if (it) "on" else "off" } ?: "?"}" + + private fun profileState(adapter: BluetoothAdapter?, profile: Int): Int? = try { + adapter?.getProfileConnectionState(profile) + } catch (_: Throwable) { + null + } + + private fun stateName(state: Int?): String = when (state) { + BluetoothProfile.STATE_CONNECTED -> "on" + BluetoothProfile.STATE_DISCONNECTED -> "off" + BluetoothProfile.STATE_CONNECTING -> "connecting" + BluetoothProfile.STATE_DISCONNECTING -> "disconnecting" + else -> "?" + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClientAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClientAndroid.kt new file mode 100644 index 000000000000..1d9e397423a1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClientAndroid.kt @@ -0,0 +1,1062 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCallback +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothStatusCodes +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import java.util.UUID +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * Platform GATT client for ONE+ / G7 Direct family UUIDs. + * + * Auth/ExtraData for KEKS; Control for EGV (Ob1 style). + * + * Mirrors Ob1/xDrip constraints: + * - **one outstanding GATT op** at a time (avoids Android 13+ status 201 / + * [BluetoothStatusCodes.ERROR_GATT_WRITE_REQUEST_BUSY]) + * - CCCD: ExtraData notify → Authentication **indication** before ready + * - ExtraData writes use [WRITE_TYPE_NO_RESPONSE]; Auth and **Control** use [WRITE_TYPE_DEFAULT] + * (Control write-with-response is required by ONE+; no-response → peer status 19 after auth) + * + * ⚠️ ASYNC IMPACT: callbacks on binder thread; await* / connect / writes block bleExecutor only. + */ +@SuppressLint("MissingPermission") +class OnePlusGattClientAndroid( + private val appContext: Context, + private val profile: OemDeviceProfile = DeviceProfileRegistry.resolve(), +) : OnePlusGattClient { + + private val bluetoothManager = + appContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + + @Volatile private var gatt: BluetoothGatt? = null + @Volatile private var device: BluetoothDevice? = null + @Volatile private var authChar: BluetoothGattCharacteristic? = null + @Volatile private var extraChar: BluetoothGattCharacteristic? = null + @Volatile private var controlChar: BluetoothGattCharacteristic? = null + @Volatile private var backfillChar: BluetoothGattCharacteristic? = null + @Volatile private var connected = false + /** True while an optional post-ready MTU request is in flight (do not re-discover). */ + @Volatile private var pendingPostReadyMtu = false + @Volatile private var lastCloseElapsedMs = 0L + + private val mainHandler = Handler(Looper.getMainLooper()) + private val readyLatch = AtomicReferenceLatch() + /** Tagged Auth/ExtraData frames for KEKS (Ob1 routes by UUID). */ + private val keksQueue = LinkedBlockingQueue(32) + private val controlQueue = LinkedBlockingQueue(32) + private val backfillQueue = LinkedBlockingQueue(64) + + /** Serializes writeCharacteristic / writeDescriptor from bleExecutor. */ + private val gattOpLock = Any() + private val pendingOpLatch = AtomicReferenceLatch() + private val pendingOpStatus = AtomicInteger(BluetoothGatt.GATT_SUCCESS) + + /** + * CCCD setup state machine (runs on binder callbacks — must not block waiting for itself). + * Ob1 order: ExtraData notification, then Authentication indication. + */ + private enum class CccdPhase { NONE, EXTRA, AUTH, DONE } + + @Volatile private var cccdPhase = CccdPhase.NONE + + /** Juggluco-style bond wait — counted down from [bondReceiver] on BOND_BONDED. */ + @Volatile private var bondCompleteLatch: CountDownLatch? = null + @Volatile private var bondReceiverRegistered = false + /** True after Auth/Extra CCCD teardown until restored — forces restore even on early bonded. */ + @Volatile private var keksCccdTornDown = false + /** Set from bond receiver; consumed on bleExecutor under [gattOpLock]. */ + @Volatile private var requestKeksTeardown = false + + private val bondReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + if (intent?.action != BluetoothDevice.ACTION_BOND_STATE_CHANGED) return + val d = readBondIntentDevice(intent) ?: return + val current = device + if (current == null || !d.address.equals(current.address, ignoreCase = true)) return + val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE) + when (state) { + BluetoothDevice.BOND_BONDING -> { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: BOND_BONDING — request KEKS CCCD teardown (Juggluco)", + ) + // Do not touch GATT from the receiver thread — bleExecutor performs teardown. + requestKeksTeardown = true + } + BluetoothDevice.BOND_BONDED -> { + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: BOND_BONDED (receiver)") + bondCompleteLatch?.countDown() + } + BluetoothDevice.BOND_NONE -> { + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: BOND_NONE during wait") + } + } + } + } + + private val callback = object : BluetoothGattCallback() { + override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) { + if (!isCurrentGatt(g)) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: ignore stale gatt state=$newState status=$status", + ) + return + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: gatt state=$newState status=$status", + ) + if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { + connected = true + // Juggluco's Dex/ONE+ path lets the OS negotiate the interval. Forcing HIGH + // (7.5 ms) correlated with peer status 19 right after the post-auth 0x4E, so this + // is off by default (see [OemDeviceProfile.forceHighConnectionPriority]). + if (profile.forceHighConnectionPriority) { + try { + g.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH) + } catch (_: Throwable) { + } + } + // Juggluco: wait out BOND_BONDING before discoverServices. + val bond = g.device?.bondState ?: BluetoothDevice.BOND_NONE + if (bond == BluetoothDevice.BOND_BONDING) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: wait BOND_BONDING before discover", + ) + scheduleDiscoverWhenBondReady(g) + } else { + beginPostConnect(g) + } + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: link down status=$status " + + OnePlusAudioLinkState.describe(appContext, bluetoothManager.adapter), + ) + connected = false + readyLatch.fail("disconnected status=$status") + completePendingOp(BluetoothGatt.GATT_FAILURE) + poisonNotifyQueues() + } + } + + override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) { + if (!isCurrentGatt(g)) return + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: mtu=$mtu status=$status") + if (pendingPostReadyMtu) { + pendingPostReadyMtu = false + return + } + g.discoverServices() + } + + override fun onServicesDiscovered(g: BluetoothGatt, status: Int) { + if (!isCurrentGatt(g)) return + if (status != BluetoothGatt.GATT_SUCCESS) { + readyLatch.fail("discover status=$status") + return + } + val delayMs = profile.postDiscoverDelayMs + if (delayMs > 0L) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: post-discover settle ${delayMs}ms", + ) + // Never sleep on the binder thread — schedule CCCD after Ob1-style pause. + mainHandler.postDelayed({ beginCccdSetup(g) }, delayMs) + } else { + beginCccdSetup(g) + } + } + + override fun onDescriptorWrite( + g: BluetoothGatt, + descriptor: BluetoothGattDescriptor, + status: Int, + ) { + if (!isCurrentGatt(g)) return + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: descriptorWrite uuid=${descriptor.uuid} status=$status phase=$cccdPhase", + ) + // bleExecutor-driven CCCD (Control / Backfill / bond teardown) uses the op latch. + if (cccdPhase == CccdPhase.DONE || cccdPhase == CccdPhase.NONE) { + completePendingOp(status) + return + } + if (status != BluetoothGatt.GATT_SUCCESS) { + readyLatch.fail("CCCD write status=$status phase=$cccdPhase") + cccdPhase = CccdPhase.NONE + return + } + when (cccdPhase) { + CccdPhase.EXTRA -> { + cccdPhase = CccdPhase.AUTH + if (!submitAuthCccd(g)) { + readyLatch.fail("Auth CCCD submit failed") + cccdPhase = CccdPhase.NONE + } + } + CccdPhase.AUTH -> { + cccdPhase = CccdPhase.DONE + readyLatch.complete() + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: gatt ready control=${controlChar != null} " + + "backfill=${backfillChar != null}", + ) + maybeRequestMtuAfterReady(g) + } + else -> Unit + } + } + + override fun onCharacteristicWrite( + g: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + status: Int, + ) { + if (!isCurrentGatt(g)) return + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: charWrite uuid=${characteristic.uuid} status=$status", + ) + completePendingOp(status) + } + + @Deprecated("Deprecated in Java") + override fun onCharacteristicChanged(g: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { + if (!isCurrentGatt(g)) return + onNotify(characteristic.uuid, characteristic.value) + } + + override fun onCharacteristicChanged( + g: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + value: ByteArray, + ) { + if (!isCurrentGatt(g)) return + onNotify(characteristic.uuid, value) + } + + private fun onNotify(uuid: UUID, value: ByteArray?) { + if (value == null) return + val copy = value.copyOf() + when (uuid) { + OnePlusGattUuids.Authentication -> + keksQueue.offer(TaggedKeksNotify(OnePlusKeksNotifySource.AUTHENTICATION, copy)) + OnePlusGattUuids.ExtraData -> + keksQueue.offer(TaggedKeksNotify(OnePlusKeksNotifySource.EXTRA_DATA, copy)) + OnePlusGattUuids.Control -> controlQueue.offer(copy) + OnePlusGattUuids.ProbablyBackfill -> backfillQueue.offer(copy) + } + } + } + + override fun connect(deviceAddress: String, autoConnect: Boolean) { + // Close any prior GATT without poisoning queues — then clear. Previously + // clear()+disconnectInternal() re-inserted empty sentinels so KEKS awaitNotify + // returned immediately ("notify timeout step=0" in the same ms as Auth write). + disconnectInternal(poisonQueues = false) + awaitPostCloseSettle() + keksQueue.clear() + controlQueue.clear() + backfillQueue.clear() + readyLatch.reset() + cccdPhase = CccdPhase.NONE + pendingPostReadyMtu = false + pendingOpLatch.reset() + if (deviceAddress.isBlank()) { + error("ONEPLUS_GATT: device address blank — scan UI required") + } + val adapter = bluetoothManager.adapter + ?: error("ONEPLUS_GATT: Bluetooth adapter null") + if (!adapter.isEnabled) { + error("ONEPLUS_GATT: Bluetooth disabled") + } + val handoff = profile.scanHandoffMs.coerceAtLeast(0L) + if (handoff > 0L) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: scan→connect handoff ${handoff}ms", + ) + sleepQuiet(handoff) + } + val remote: BluetoothDevice = try { + adapter.getRemoteDevice(deviceAddress) + } catch (_: Throwable) { + error("ONEPLUS_GATT: invalid address") + } + device = remote + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: connectGatt autoConnect=$autoConnect " + + "mtuOnConnect=${profile.requestMtuOnConnect}", + ) + gatt = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + remote.connectGatt(appContext, autoConnect, callback, BluetoothDevice.TRANSPORT_LE) + } else { + @Suppress("DEPRECATION") + remote.connectGatt(appContext, autoConnect, callback) + } + val timeout = if (autoConnect) { + profile.connectTimeoutMs.coerceAtLeast(60_000L) + } else { + profile.connectTimeoutMs + } + val ok = readyLatch.await(timeout) + if (!ok) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: connect timeout autoConnect=$autoConnect " + + OnePlusAudioLinkState.describe(appContext, adapter), + ) + disconnectInternal(poisonQueues = true) + error("ONEPLUS_GATT: connect/discover timeout ${timeout}ms") + } + val err = readyLatch.error + if (err != null) { + disconnectInternal(poisonQueues = true) + error("ONEPLUS_GATT: $err") + } + // Drop CCCD-setup noise / late disconnect sentinels before KEKS awaits Auth notifies. + keksQueue.clear() + controlQueue.clear() + backfillQueue.clear() + } + + override fun disconnect() { + disconnectInternal(poisonQueues = true) + } + + override fun isConnected(): Boolean = connected && gatt != null + + override fun writeAuthentication(payload: ByteArray?) { + // Ob1: Authentication uses WRITE_TYPE_DEFAULT. + writeChar( + characteristic = authChar, + payload = payload, + label = "Auth", + writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, + ) + } + + override fun writeExtraData(payload: ByteArray?) { + if (payload == null || payload.isEmpty()) return + // Ob1 doNext: ExtraData in ≤20-byte chunks, WRITE_TYPE_NO_RESPONSE, short gaps. + var offset = 0 + while (offset < payload.size) { + val end = minOf(offset + EXTRA_DATA_CHUNK, payload.size) + writeChar( + characteristic = extraChar, + payload = payload.copyOfRange(offset, end), + label = "ExtraData", + writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE, + ) + offset = end + if (offset < payload.size) { + sleepQuiet(EXTRA_DATA_CHUNK_GAP_MS) + } + } + sleepQuiet(EXTRA_DATA_AFTER_MS) + } + + override fun writeControl(payload: ByteArray?) { + // Control (0x4E EGlucose request, 0x59 backfill, 0x26 SessionStart) MUST be written WITH + // response. Juggluco forces charact[0].setWriteType(WRITE_TYPE_DEFAULT) (DexGattCallback); + // sending 0x4E as WRITE_TYPE_NO_RESPONSE made the ONE+ terminate the link with peer + // status 19 ~3 s after auth (field log 00:29:54, no EGV ever streamed). + writeChar( + characteristic = controlChar, + payload = payload, + label = "Control", + writeType = BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, + ) + } + + override fun enableControlNotifications() { + val g = gatt ?: error("ONEPLUS_GATT: not connected") + val c = controlChar ?: error("ONEPLUS_GATT: Control characteristic missing") + // Juggluco Dex path: Control NOTIFY then immediate 0x4E. Ob1 uses indications — + // try notify first, fall back to indicate if the stack rejects it. + try { + runBlockingDescriptorWrite(g, c, indicate = false) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: Control notifications enabled") + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: Control NOTIFY failed (${t.message}) — INDICATE fallback", + ) + enableControlIndications() + } + } + + override fun enableControlIndications() { + val g = gatt ?: error("ONEPLUS_GATT: not connected") + val c = controlChar ?: error("ONEPLUS_GATT: Control characteristic missing") + runBlockingDescriptorWrite(g, c, indicate = true) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: Control indications enabled") + } + + override fun enableBackfillNotifications() { + val g = gatt ?: error("ONEPLUS_GATT: not connected") + val c = backfillChar ?: error("ONEPLUS_GATT: ProbablyBackfill characteristic missing") + // Ob1 uses notifications (not indications) on ProbablyBackfill. + runBlockingDescriptorWrite(g, c, indicate = false) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: Backfill notifications enabled") + } + + override fun isBonded(): Boolean { + val d = device ?: return false + return d.bondState == BluetoothDevice.BOND_BONDED + } + + override fun createBond(): Boolean { + val d = device ?: error("ONEPLUS_GATT: no device for bond") + ensureBondReceiverRegistered() + // Arm latch BEFORE createBond so a fast BOND_BONDED cannot be missed + // (race between createBond() and awaitBondComplete latch assign). + if (bondCompleteLatch == null) { + bondCompleteLatch = CountDownLatch(1) + } + if (d.bondState == BluetoothDevice.BOND_BONDED) { + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: already bonded") + bondCompleteLatch?.countDown() + return true + } + // Juggluco: createBond(TRANSPORT_LE) via reflection — critical on Samsung. + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: createBond TRANSPORT_LE") + return createBondLe(d) + } + + override fun removeBond(): Boolean { + val d = device ?: return false + val state = try { + d.bondState + } catch (_: Throwable) { + return false + } + if (state == BluetoothDevice.BOND_NONE) { + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: removeBond no-op (already BOND_NONE)") + return true + } + return try { + val method = d.javaClass.getMethod("removeBond") + val ok = method.invoke(d) as Boolean + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: removeBond (hidden API) result=$ok wasState=$state", + ) + ok + } catch (t: Throwable) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: removeBond unavailable: ${t.message}", + t, + ) + false + } + } + + override fun awaitBondComplete(timeoutMs: Long): Boolean { + ensureBondReceiverRegistered() + val latch = bondCompleteLatch ?: CountDownLatch(1).also { bondCompleteLatch = it } + + // Already bonded (including race where BOND_BONDED arrived before this call). + if (isBonded()) { + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: Android bond already complete") + return finishBondWithKeksCccdRestore() + } + + val state = try { + device?.bondState + } catch (_: Throwable) { + null + } + if (state == BluetoothDevice.BOND_BONDING || requestKeksTeardown) { + tearDownKeksCccdsBlocking() + } + + val deadline = SystemClock.elapsedRealtime() + timeoutMs.coerceAtLeast(1L) + var bonded = false + try { + while (SystemClock.elapsedRealtime() < deadline) { + if (!isConnected()) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: GATT disconnected during bond wait", + ) + return false + } + if (requestKeksTeardown) { + tearDownKeksCccdsBlocking() + } + if (isBonded()) { + bonded = true + break + } + try { + latch.await(200L, TimeUnit.MILLISECONDS) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + return false + } + } + if (!bonded) { + bonded = isBonded() + } + } finally { + bondCompleteLatch = null + } + + if (bonded && isConnected()) { + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: Android bond complete — restore KEKS CCCDs") + return finishBondWithKeksCccdRestore() + } + + // Timed out: still try restore so the next KEKS step is not deaf. + if (isConnected() && keksCccdTornDown) { + restoreKeksSubscriptionsAfterBond() + } + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: bond wait timed out / not bonded after ${timeoutMs}ms", + ) + return false + } + + /** Bond OK only if KEKS CCCDs are usable again after optional Juggluco teardown. */ + private fun finishBondWithKeksCccdRestore(): Boolean { + if (!keksCccdTornDown) return true + val restored = restoreKeksSubscriptionsAfterBond() + if (!restored) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: bond OK but KEKS CCCD restore failed", + ) + } + return restored + } + + private fun beginPostConnect(g: BluetoothGatt) { + if (profile.requestMtu && profile.requestMtuOnConnect) { + val mtu = profile.preferredMtu.coerceIn(23, 517) + if (!g.requestMtu(mtu)) { + g.discoverServices() + } + } else { + // Juggluco Dex/ONE+ never requests MTU (stays at 23). Discover straight away. + g.discoverServices() + } + } + + private fun scheduleDiscoverWhenBondReady(g: BluetoothGatt) { + val deadline = SystemClock.elapsedRealtime() + BOND_BONDING_WAIT_MS + fun tick() { + if (!isCurrentGatt(g) || !connected) return + val state = try { + g.device?.bondState + } catch (_: Throwable) { + null + } + if (state == null || state != BluetoothDevice.BOND_BONDING) { + beginPostConnect(g) + return + } + if (SystemClock.elapsedRealtime() >= deadline) { + readyLatch.fail("bond stuck in BOND_BONDING") + return + } + mainHandler.postDelayed({ tick() }, 100L) + } + mainHandler.post { tick() } + } + + private fun createBondLe(device: BluetoothDevice): Boolean { + return try { + val intType = Int::class.javaPrimitiveType ?: Integer.TYPE + val method = device.javaClass.getMethod("createBond", intType) + val ok = method.invoke(device, BluetoothDevice.TRANSPORT_LE) as Boolean + if (!ok) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: createBond(TRANSPORT_LE) returned false — fallback", + ) + device.createBond() + } else { + true + } + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: createBond(TRANSPORT_LE) unavailable: ${t.message}", + ) + device.createBond() + } + } + + private fun ensureBondReceiverRegistered() { + if (bondReceiverRegistered) return + val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED) + try { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + appContext.registerReceiver(bondReceiver, filter, Context.RECEIVER_NOT_EXPORTED) + } else { + @Suppress("UnspecifiedRegisterReceiverFlag") + appContext.registerReceiver(bondReceiver, filter) + } + bondReceiverRegistered = true + OnePlusLog.d("${OnePlusLogMarkers.SESSION}: bond receiver registered") + } catch (t: Throwable) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: bond receiver ${t.message}", t) + } + } + + private fun unregisterBondReceiver() { + if (!bondReceiverRegistered) return + try { + appContext.unregisterReceiver(bondReceiver) + } catch (_: Throwable) { + } + bondReceiverRegistered = false + bondCompleteLatch = null + } + + private fun readBondIntentDevice(intent: Intent): BluetoothDevice? { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE, BluetoothDevice::class.java) + } else { + @Suppress("DEPRECATION") + intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) + } + } + + /** + * Juggluco `bonded()` BOND_BONDING: drop Auth/Extra subscriptions on **bleExecutor** + * under [gattOpLock] (never from the BroadcastReceiver — avoids pendingOpLatch races). + */ + private fun tearDownKeksCccdsBlocking() { + requestKeksTeardown = false + if (keksCccdTornDown) return + val g = gatt ?: return + try { + authChar?.let { runBlockingDescriptorDisable(g, it) } + extraChar?.let { runBlockingDescriptorDisable(g, it) } + keksCccdTornDown = true + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: KEKS CCCDs torn down for bonding") + } catch (t: Throwable) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: KEKS CCCD teardown failed: ${t.message}", + t, + ) + } + } + + /** + * After BOND_BONDED: re-enable Extra notify + Auth indication so libkeks can finish + * AuthStatus → GET_DATA (we do not jump to Control here — that is [OnePlusEgvSession]). + * @return false if enable writes failed (caller must not treat bond as auth-ready) + */ + private fun restoreKeksSubscriptionsAfterBond(): Boolean { + val g = gatt ?: return false + if (!connected) { + keksCccdTornDown = false + return false + } + return try { + val extra = extraChar + if (extra != null) { + runBlockingDescriptorWrite(g, extra, indicate = false) + } + val auth = authChar + if (auth != null) { + val indicate = auth.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0 + runBlockingDescriptorWrite(g, auth, indicate = indicate) + } + keksQueue.clear() + keksCccdTornDown = false + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS CCCDs restored after bond", + ) + true + } catch (t: Throwable) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: restore KEKS CCCDs after bond: ${t.message}", + t, + ) + // Best-effort rediscover if subscriptions are dead (Juggluco rediscovers when needed). + try { + g.discoverServices() + } catch (_: Throwable) { + } + false + } + } + + private fun runBlockingDescriptorDisable( + g: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + ) { + synchronized(gattOpLock) { + pendingOpLatch.reset() + pendingOpStatus.set(BluetoothGatt.GATT_SUCCESS) + g.setCharacteristicNotification(characteristic, false) + val cccd = characteristic.getDescriptor(OnePlusGattUuids.CharacteristicUpdateNotification) + ?: return + val disable = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE + val submitted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val status = g.writeDescriptor(cccd, disable) + if (status != BluetoothStatusCodes.SUCCESS && status != BluetoothGatt.GATT_SUCCESS) { + error("ONEPLUS_GATT: disableDescriptor status=$status") + } + true + } else { + @Suppress("DEPRECATION") + cccd.value = disable + @Suppress("DEPRECATION") + g.writeDescriptor(cccd) + } + if (!submitted) { + error("ONEPLUS_GATT: disableDescriptor failed") + } + if (!pendingOpLatch.await(GATT_OP_TIMEOUT_MS)) { + error("ONEPLUS_GATT: disableDescriptor timeout") + } + val err = pendingOpLatch.error + if (err != null) error("ONEPLUS_GATT: $err") + val status = pendingOpStatus.get() + if (status != BluetoothGatt.GATT_SUCCESS) { + error("ONEPLUS_GATT: disable descriptor status=$status") + } + } + } + + override fun awaitKeksNotify(timeoutMs: Long): OnePlusKeksNotify? { + val v = keksQueue.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: return null + if (v === KEKS_DISCONNECT_SENTINEL) return null + return OnePlusKeksNotify(v.source, v.payload) + } + + override fun awaitNotify(timeoutMs: Long): ByteArray? = awaitKeksNotify(timeoutMs)?.payload + + override fun awaitControlNotify(timeoutMs: Long): ByteArray? = pollNotify(controlQueue, timeoutMs) + + override fun awaitBackfillNotify(timeoutMs: Long): ByteArray? = pollNotify(backfillQueue, timeoutMs) + + /** + * Only the identity [DISCONNECT_SENTINEL] means "stop waiting". + * Do not treat any empty [ByteArray] as disconnect — that raced with connect(). + */ + private fun pollNotify(queue: LinkedBlockingQueue, timeoutMs: Long): ByteArray? { + val v = queue.poll(timeoutMs, TimeUnit.MILLISECONDS) ?: return null + if (v === DISCONNECT_SENTINEL) return null + return v + } + + private fun beginCccdSetup(g: BluetoothGatt) { + if (!isCurrentGatt(g)) return + val service = g.getService(OnePlusGattUuids.CgmService) + if (service == null) { + readyLatch.fail("CGM service missing") + return + } + authChar = service.getCharacteristic(OnePlusGattUuids.Authentication) + extraChar = service.getCharacteristic(OnePlusGattUuids.ExtraData) + controlChar = service.getCharacteristic(OnePlusGattUuids.Control) + backfillChar = service.getCharacteristic(OnePlusGattUuids.ProbablyBackfill) + if (authChar == null) { + readyLatch.fail("Authentication characteristic missing") + return + } + if (extraChar != null) { + cccdPhase = CccdPhase.EXTRA + if (!submitEnableCccd(g, extraChar!!, indicate = false)) { + readyLatch.fail("ExtraData CCCD submit failed") + } + } else { + cccdPhase = CccdPhase.AUTH + if (!submitAuthCccd(g)) { + readyLatch.fail("Auth CCCD submit failed") + } + } + } + + private fun maybeRequestMtuAfterReady(g: BluetoothGatt) { + // Off by default for ONE+ (Juggluco Dex never requests MTU — see OemDeviceProfile.requestMtu). + if (!profile.requestMtu) return + if (profile.requestMtuOnConnect) return + val mtu = profile.preferredMtu.coerceIn(23, 517) + if (mtu <= 23) return + pendingPostReadyMtu = true + if (!g.requestMtu(mtu)) { + pendingPostReadyMtu = false + } else { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: post-ready requestMtu=$mtu", + ) + } + } + + private fun awaitPostCloseSettle() { + val settle = profile.postCloseSettleMs.coerceAtLeast(0L) + if (settle <= 0L || lastCloseElapsedMs <= 0L) return + val elapsed = SystemClock.elapsedRealtime() - lastCloseElapsedMs + val remaining = settle - elapsed + if (remaining > 0L) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: post-close settle ${remaining}ms (floor=${settle}ms)", + ) + sleepQuiet(remaining) + } + } + + private fun refreshGatt(g: BluetoothGatt?) { + if (!profile.useGattRefresh || g == null) return + try { + val method = BluetoothGatt::class.java.getMethod("refresh") + val ok = method.invoke(g) as? Boolean ?: false + OnePlusLog.d("${OnePlusLogMarkers.SESSION}: gatt.refresh()=$ok") + } catch (t: Throwable) { + OnePlusLog.d("${OnePlusLogMarkers.SESSION}: gatt.refresh unavailable: ${t.message}") + } + } + + private fun submitAuthCccd(g: BluetoothGatt): Boolean { + val auth = authChar ?: return false + // Ob1 KEKS path: setupIndication(Authentication); fall back to notify if needed. + val indicate = auth.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0 + return submitEnableCccd(g, auth, indicate = indicate) + } + + /** + * Non-blocking CCCD submit for the discover-time state machine (binder thread). + */ + private fun submitEnableCccd( + g: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + indicate: Boolean, + ): Boolean { + g.setCharacteristicNotification(characteristic, true) + val cccd = characteristic.getDescriptor(OnePlusGattUuids.CharacteristicUpdateNotification) + ?: return false + val enable = if (indicate) { + BluetoothGattDescriptor.ENABLE_INDICATION_VALUE + } else { + BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + } + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val status = g.writeDescriptor(cccd, enable) + status == BluetoothStatusCodes.SUCCESS || status == BluetoothGatt.GATT_SUCCESS + } else { + @Suppress("DEPRECATION") + cccd.value = enable + @Suppress("DEPRECATION") + g.writeDescriptor(cccd) + } + } + + private fun runBlockingDescriptorWrite( + g: BluetoothGatt, + characteristic: BluetoothGattCharacteristic, + indicate: Boolean, + ) { + synchronized(gattOpLock) { + pendingOpLatch.reset() + pendingOpStatus.set(BluetoothGatt.GATT_SUCCESS) + g.setCharacteristicNotification(characteristic, true) + val cccd = characteristic.getDescriptor(OnePlusGattUuids.CharacteristicUpdateNotification) + ?: error("ONEPLUS_GATT: CCCD missing") + val enable = if (indicate) { + BluetoothGattDescriptor.ENABLE_INDICATION_VALUE + } else { + BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + } + val submitted = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val status = g.writeDescriptor(cccd, enable) + if (status != BluetoothStatusCodes.SUCCESS && status != BluetoothGatt.GATT_SUCCESS) { + error("ONEPLUS_GATT: writeDescriptor status=$status") + } + true + } else { + @Suppress("DEPRECATION") + cccd.value = enable + @Suppress("DEPRECATION") + g.writeDescriptor(cccd) + } + if (!submitted) { + error("ONEPLUS_GATT: writeDescriptor failed") + } + if (!pendingOpLatch.await(GATT_OP_TIMEOUT_MS)) { + error("ONEPLUS_GATT: writeDescriptor timeout") + } + val err = pendingOpLatch.error + if (err != null) error("ONEPLUS_GATT: $err") + val status = pendingOpStatus.get() + if (status != BluetoothGatt.GATT_SUCCESS) { + error("ONEPLUS_GATT: descriptor status=$status") + } + } + } + + private fun writeChar( + characteristic: BluetoothGattCharacteristic?, + payload: ByteArray?, + label: String, + writeType: Int?, + ) { + if (payload == null || payload.isEmpty()) return + val g = gatt ?: error("ONEPLUS_GATT: not connected ($label)") + val c = characteristic ?: error("ONEPLUS_GATT: missing $label characteristic") + val resolvedType = writeType ?: if ( + c.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0 + ) { + BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE + } else { + BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT + } + + synchronized(gattOpLock) { + pendingOpLatch.reset() + pendingOpStatus.set(BluetoothGatt.GATT_SUCCESS) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val status = g.writeCharacteristic(c, payload, resolvedType) + if (status != BluetoothStatusCodes.SUCCESS && status != BluetoothGatt.GATT_SUCCESS) { + // 201 = ERROR_GATT_WRITE_REQUEST_BUSY — surface clearly for logcat. + error("ONEPLUS_GATT: write $label status=$status") + } + } else { + @Suppress("DEPRECATION") + c.value = payload + @Suppress("DEPRECATION") + c.writeType = resolvedType + @Suppress("DEPRECATION") + if (!g.writeCharacteristic(c)) { + error("ONEPLUS_GATT: write $label failed") + } + } + if (!pendingOpLatch.await(GATT_OP_TIMEOUT_MS)) { + error("ONEPLUS_GATT: write $label timeout") + } + val err = pendingOpLatch.error + if (err != null) error("ONEPLUS_GATT: write $label $err") + val cbStatus = pendingOpStatus.get() + if (cbStatus != BluetoothGatt.GATT_SUCCESS) { + error("ONEPLUS_GATT: write $label callback status=$cbStatus") + } + OnePlusLog.d("${OnePlusLogMarkers.SESSION}: wrote $label ${payload.size}b") + } + } + + private fun completePendingOp(status: Int) { + pendingOpStatus.set(status) + if (status != BluetoothGatt.GATT_SUCCESS) { + pendingOpLatch.fail("status=$status") + } else { + pendingOpLatch.complete() + } + } + + /** Ignore binder callbacks from a GATT instance we already closed/replaced. */ + private fun isCurrentGatt(g: BluetoothGatt): Boolean = g === gatt + + private fun disconnectInternal(poisonQueues: Boolean) { + connected = false + cccdPhase = CccdPhase.NONE + pendingPostReadyMtu = false + keksCccdTornDown = false + requestKeksTeardown = false + bondCompleteLatch?.countDown() + unregisterBondReceiver() + mainHandler.removeCallbacksAndMessages(null) + completePendingOp(BluetoothGatt.GATT_FAILURE) + if (poisonQueues) { + poisonNotifyQueues() + } + // Detach before close so async DISCONNECTED on the old instance cannot fail the + // next connect()'s readyLatch (classic Android BLE race → ONEPLUS_GATT: disconnected). + val closing = gatt + gatt = null + device = null + authChar = null + extraChar = null + controlChar = null + backfillChar = null + refreshGatt(closing) + try { + closing?.disconnect() + } catch (_: Throwable) { + } + try { + closing?.close() + } catch (_: Throwable) { + } + if (closing != null) { + lastCloseElapsedMs = SystemClock.elapsedRealtime() + } + } + + private fun poisonNotifyQueues() { + keksQueue.offer(KEKS_DISCONNECT_SENTINEL) + controlQueue.offer(DISCONNECT_SENTINEL) + backfillQueue.offer(DISCONNECT_SENTINEL) + } + + private fun sleepQuiet(ms: Long) { + try { + Thread.sleep(ms) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + } + } + + private class AtomicReferenceLatch { + @Volatile var error: String? = null + private set + private var latch = CountDownLatch(1) + + fun reset() { + error = null + latch = CountDownLatch(1) + } + + fun complete() { + error = null + latch.countDown() + } + + fun fail(reason: String) { + error = reason + latch.countDown() + } + + fun await(timeoutMs: Long): Boolean = latch.await(timeoutMs, TimeUnit.MILLISECONDS) + } + + /** Internal KEKS queue frame; [KEKS_DISCONNECT_SENTINEL] is identity-checked. */ + private class TaggedKeksNotify( + val source: OnePlusKeksNotifySource, + val payload: ByteArray, + ) + + companion object { + private const val GATT_OP_TIMEOUT_MS = 10_000L + private const val EXTRA_DATA_CHUNK = 20 + private const val EXTRA_DATA_CHUNK_GAP_MS = 40L + private const val BOND_BONDING_WAIT_MS = 45_000L + /** Ob1 sleeps ~500ms after ExtraData chunks before Auth write. */ + private const val EXTRA_DATA_AFTER_MS = 500L + + /** Identity sentinel for Control/Backfill await* unblock on disconnect. */ + private val DISCONNECT_SENTINEL = ByteArray(0) + + /** Identity sentinel for KEKS await* unblock on disconnect. */ + private val KEKS_DISCONNECT_SENTINEL = TaggedKeksNotify( + OnePlusKeksNotifySource.AUTHENTICATION, + ByteArray(0), + ) + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattUuids.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattUuids.kt new file mode 100644 index 000000000000..d32ddad34a92 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattUuids.kt @@ -0,0 +1,28 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +import java.util.UUID + +/** + * The shared [OnePlusBluetoothUuids] text, as the `java.util.UUID` values the Android BLE stack + * takes. Built once, so a `when` branch can compare them by identity the way it always did. + */ +object OnePlusGattUuids { + + val DeviceInfo: UUID = UUID.fromString(OnePlusBluetoothUuids.DeviceInfo) + val Advertisement: UUID = UUID.fromString(OnePlusBluetoothUuids.Advertisement) + val CgmService: UUID = UUID.fromString(OnePlusBluetoothUuids.CgmService) + val ServiceB: UUID = UUID.fromString(OnePlusBluetoothUuids.ServiceB) + + val ManufacturerNameString: UUID = UUID.fromString(OnePlusBluetoothUuids.ManufacturerNameString) + + val Communication: UUID = UUID.fromString(OnePlusBluetoothUuids.Communication) + val Control: UUID = UUID.fromString(OnePlusBluetoothUuids.Control) + val Authentication: UUID = UUID.fromString(OnePlusBluetoothUuids.Authentication) + val ProbablyBackfill: UUID = UUID.fromString(OnePlusBluetoothUuids.ProbablyBackfill) + val ExtraData: UUID = UUID.fromString(OnePlusBluetoothUuids.ExtraData) + + val CharacteristicE: UUID = UUID.fromString(OnePlusBluetoothUuids.CharacteristicE) + val CharacteristicF: UUID = UUID.fromString(OnePlusBluetoothUuids.CharacteristicF) + + val CharacteristicUpdateNotification: UUID = UUID.fromString(OnePlusBluetoothUuids.CharacteristicUpdateNotification) +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefsAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefsAndroid.kt new file mode 100644 index 000000000000..0611deb772be --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefsAndroid.kt @@ -0,0 +1,66 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import android.content.Context +import android.content.SharedPreferences + +/** + * Android [OnePlusSensorPrefs]: the same private `SharedPreferences` file the store always used, + * under the same name, so an install keeps its stored sensor across this change. + */ +internal class OnePlusSensorPrefsAndroid(context: Context, prefsName: String) : OnePlusSensorPrefs { + + private val prefs: SharedPreferences = + context.applicationContext.getSharedPreferences(prefsName, Context.MODE_PRIVATE) + + override fun getString(key: String): String? = prefs.getString(key, null) + + override fun getLong(key: String, defaultValue: Long): Long = prefs.getLong(key, defaultValue) + + override fun getInt(key: String, defaultValue: Int): Int = prefs.getInt(key, defaultValue) + + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = prefs.getBoolean(key, defaultValue) + + override fun contains(key: String): Boolean = prefs.contains(key) + + override fun edit(block: OnePlusSensorPrefs.Editor.() -> Unit) { + val editor = prefs.edit() + AndroidEditor(editor).block() + editor.apply() + } + + private class AndroidEditor(private val editor: SharedPreferences.Editor) : OnePlusSensorPrefs.Editor { + + override fun putString(key: String, value: String?) { + editor.putString(key, value) + } + + override fun putLong(key: String, value: Long) { + editor.putLong(key, value) + } + + override fun putInt(key: String, value: Int) { + editor.putInt(key, value) + } + + override fun putBoolean(key: String, value: Boolean) { + editor.putBoolean(key, value) + } + + override fun remove(key: String) { + editor.remove(key) + } + + override fun clear() { + editor.clear() + } + } +} + +/** + * Builds a store on this phone's private file for [namespace]. + * + * Named like the class on purpose: every caller still writes `OnePlusSensorStore(context)`, and the + * class itself no longer knows anything about Android. + */ +fun OnePlusSensorStore(context: Context, namespace: String? = null): OnePlusSensorStore = + OnePlusSensorStore(OnePlusSensorPrefsAndroid(context, OnePlusSensorStore.prefsFileName(namespace))) diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfoAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfoAndroid.kt new file mode 100644 index 000000000000..bea88e8ef2d2 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfoAndroid.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.dexcomoneplus.oem + +import android.os.Build + +/** + * `Build.MANUFACTURER` and `Build.MODEL` are declared non-null by the framework, and are null on + * the unit test classpath, where every `android.os.Build` field is a stub. The empty string is + * read by [DeviceProfileRegistry] as "no OEM I know", which is the generic profile - the same + * answer an unknown phone gets, and the right one when the phone will not say who made it. + */ +internal actual fun onePlusDeviceManufacturer(): String = Build.MANUFACTURER ?: "" + +internal actual fun onePlusDeviceModel(): String = Build.MODEL ?: "" diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt new file mode 100644 index 000000000000..e3de85c1ab66 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt @@ -0,0 +1,478 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothManager +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanFilter +import android.bluetooth.le.ScanResult +import android.bluetooth.le.ScanSettings +import android.content.Context +import android.os.ParcelUuid +import android.os.PowerManager +import android.os.SystemClock +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattUuids +import app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvCandidate +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +/** + * Platform LE scanner for Dexcom ONE+ / G7-family ADV. + * + * Soft filters (Juggluco `isG7`): + * - Local name `DXCM` / `DX02` / `DX01`, and/or + * - Advertisement includes service UUID FEBC ([OnePlusGattUuids.Advertisement]) + * **without** a G6-style `Dexcom*` marketing name. + * - Optional [sessionHint] sticky-matches last MAC / ADV name / serial. + * + * The discovery scan remains unfiltered so nameless transmitters still appear. + * The known-MAC pre-connect wait uses a platform [ScanFilter], allowing delivery while the screen + * is off on Android/Samsung. + * + * The 4-digit pairing code plays no part on this path. It is the KEKS password and is checked at + * Connect only. It is not carried in the advertisement, so the scan can narrow the list down to the + * G7/ONE+ family and rank it, and no further: telling two ONE+ apart is the user's call — see + * [autoSelectSingle]. + * + * ⚠️ ASYNC IMPACT: [OnePlusScanListener.onDevice] on binder thread — hop to main for Compose. + */ +@SuppressLint("MissingPermission") +class OnePlusBleScannerAndroid( + context: Context, + /** Optional stored session for Juggluco-style candidate ranking / sticky match. */ + @Volatile var sessionHint: OnePlusStoredSession? = null, + /** Sensor slot owning this scanner (`prod` / `staging`) — logged so field traces are attributable. */ + private val slot: String = OnePlusLogMarkers.SLOT_PRODUCTION, +) : OnePlusBleScanner { + + private val appContext = context.applicationContext + private val bluetoothManager = + appContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + + /** Screen state — the unfiltered throttle probe is only meaningful while the screen is on. */ + private val powerManager = + appContext.getSystemService(Context.POWER_SERVICE) as PowerManager + + private val scanning = AtomicBoolean(false) + private val seen = ConcurrentHashMap() + + /** Consecutive filtered `awaitTarget` windows that heard nothing — see unfiltered probe. */ + @Volatile + private var consecutiveFilteredSilent = 0 + + /** Consecutive **unfiltered** silent probes — see [noteScanOutcome]. */ + @Volatile + private var silentScans = 0 + + @Volatile + private var listener: OnePlusScanListener? = null + + private val callback = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + handle(result) + } + + override fun onBatchScanResults(results: MutableList) { + results.forEach { handle(it) } + } + + override fun onScanFailed(errorCode: Int) { + OnePlusLog.e("${OnePlusLogMarkers.SCAN}: [$slot] failed errorCode=$errorCode") + scanning.set(false) + } + } + + override fun startScan(listener: OnePlusScanListener) { + val adapter = bluetoothManager.adapter + val leScanner = adapter?.bluetoothLeScanner + if (adapter == null || !adapter.isEnabled || leScanner == null) { + OnePlusLog.e("${OnePlusLogMarkers.SCAN}: [$slot] adapter unavailable") + return + } + stopScan() + seen.clear() + this.listener = listener + val settings = ScanSettings.Builder() + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build() + // UI discovery runs on the main thread: book the platform quota slot but never wait for one + // (the reserve kept by OnePlusScanBudget is precisely what makes this always affordable). + OnePlusScanBudget.record(SystemClock.elapsedRealtime()) + leScanner.startScan(null, settings, callback) + scanning.set(true) + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: [$slot] started") + } + + override fun stopScan() { + val leScanner = bluetoothManager.adapter?.bluetoothLeScanner + try { + leScanner?.stopScan(callback) + } catch (_: Throwable) { + } + scanning.set(false) + listener = null + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: [$slot] stopped") + } + + override fun isScanning(): Boolean = scanning.get() + + override fun updateSessionHint(session: OnePlusStoredSession?) { + sessionHint = session + } + + /** + * Pre-connect ADV wait isolated from UI [stopScan] (own [ScanCallback]). + * Field log: StartActivity onDispose stopped shared scan ~0.6s into prepareConnect. + * + * The platform filter list is OR'ed: the target MAC **plus** the ONE+/G7 advertisement service + * (FEBC). The extra filter costs no additional scan start, and lets a wait that never hears its + * own MAC still report that another ONE+ is nearby — the stale-stored-MAC signature. + * + * ⚠️ ASYNC IMPACT: blocks the calling BLE executor for up to [timeoutMs] plus any wait imposed + * by [OnePlusScanBudget]; [OnePlusBleSession.stop] does not need this to return (it clears + * `running` and disconnects GATT). + */ + override fun awaitTarget(address: String, timeoutMs: Long): OnePlusAdvWaitResult { + val adapter = bluetoothManager.adapter + val leScanner = adapter?.bluetoothLeScanner + if (adapter == null || !adapter.isEnabled || leScanner == null) { + OnePlusLog.e("${OnePlusLogMarkers.SCAN}: [$slot] awaitTarget adapter unavailable") + return OnePlusAdvWaitResult() + } + val target = normalizeTargetAddress(address) + val found = AtomicReference(null) + val foreign = ConcurrentHashMap() + val latch = CountDownLatch(1) + // Any callback at all proves the scan really registered with the OS — see silentScans. + val heardAnything = AtomicBoolean(false) + val cb = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + heardAnything.set(true) + val device = result.device ?: return + val addr = device.address ?: return + val name = device.name ?: result.scanRecord?.deviceName + if (addr.uppercase() != target) { + // FEBC-matched neighbour: keep it only if it looks like a G7-family transmitter + // (never a G6 `Dexcom*` companion), so the diagnostic cannot cry wolf. + if (isG7FamilyAdvertisement(name)) { + foreign[addr.uppercase()] = OnePlusScanResult(addr, name, result.rssi) + .apply { seenElapsedMs = SystemClock.elapsedRealtime() } + } + return + } + val hit = OnePlusScanResult(addr, name, result.rssi) + .apply { seenElapsedMs = SystemClock.elapsedRealtime() } + if (found.compareAndSet(null, hit)) { + latch.countDown() + } + } + + override fun onBatchScanResults(results: MutableList) { + results.forEach { onScanResult(0, it) } + } + + override fun onScanFailed(errorCode: Int) { + if (shouldBackOffOnScanFailed(errorCode)) { + OnePlusScanBudget.blockFor(SystemClock.elapsedRealtime(), OnePlusScanBudget.WINDOW_MS) + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: [$slot] awaitTarget failed errorCode=$errorCode — " + + "OS refused the scan; backing off one budget window", + ) + } else { + OnePlusLog.e( + "${OnePlusLogMarkers.SCAN}: [$slot] awaitTarget failed errorCode=$errorCode", + ) + } + heardAnything.set(true) + latch.countDown() + } + } + val settings = ScanSettings.Builder() + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build() + awaitScanBudgetSlot() + return try { + val targetFilter = ScanFilter.Builder() + .setDeviceAddress(target) + .build() + val familyFilter = ScanFilter.Builder() + .setServiceUuid(ParcelUuid(OnePlusGattUuids.Advertisement)) + .build() + leScanner.startScan(listOf(targetFilter, familyFilter), settings, cb) + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] awaitTarget filtered started " + + "mac=***${target.takeLast(5)} timeoutMs=$timeoutMs", + ) + latch.await(timeoutMs.coerceAtLeast(1L), TimeUnit.MILLISECONDS) + OnePlusAdvWaitResult(target = found.get(), foreign = foreign.values.toList()) + } catch (t: Throwable) { + OnePlusLog.w("${OnePlusLogMarkers.SCAN}: [$slot] awaitTarget ${t.message}") + // An exception is not evidence about the OS, so do not let it feed the throttle + // heuristic: claim we heard something and leave the counters alone. + heardAnything.set(true) + OnePlusAdvWaitResult(foreign = foreign.values.toList()) + } finally { + try { + leScanner.stopScan(cb) + } catch (_: Throwable) { + } + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: [$slot] awaitTarget stopped") + }.also { result -> + // Deliberately after the `finally`: the probe below starts its own scanner, and running + // it while this one is still registered doubled the registration pressure at exactly the + // moment the platform quota was tightest (CUBOT field log 2026-08-20, "unfiltered + // throttle probe started" logged before the matching "awaitTarget stopped"). + noteFilteredWindowOutcome( + heardAnything = heardAnything.get(), + foundTarget = result.target != null, + ) + } + } + + /** + * A filtered pre-connect window cannot tell "OS refused the scan" from "my sensor is asleep". + * The MAC+FEBC filter never delivers a neighbour phone or watch, so silence is the normal + * one-sensor house (CUBOT field log 2026-08-16). Back-off is fed only by: + * - a direct [ScanCallback.onScanFailed] refusal, or + * - a short **unfiltered** probe every [UNFILTERED_THROTTLE_PROBE_EVERY] silent filtered windows. + * An unfiltered 1 s window in a lived-in room almost always hears something; if it hears + * nothing, throttling is a fair guess. + */ + private fun noteFilteredWindowOutcome(heardAnything: Boolean, foundTarget: Boolean) { + if (foundTarget || heardAnything) { + consecutiveFilteredSilent = 0 + silentScans = 0 + return + } + consecutiveFilteredSilent = nextFilteredSilentWindows(consecutiveFilteredSilent) + if (!shouldRunUnfilteredThrottleProbe(consecutiveFilteredSilent)) return + consecutiveFilteredSilent = 0 + // AOSP ScanManager suspends UNFILTERED scans while the screen is off ("Cannot start + // unfiltered scan in screen-off. This scan will be resumed later"), so with the screen off + // the probe can only ever report silence and the back-off would fire on a premise the OS + // guarantees false. CUBOT field log 2026-08-20: 16 probes, 16 refusals, 0 valid samples — + // the probe was causing the very throttling it was meant to detect. + if (!powerManager.isInteractive) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] throttle probe skipped — screen off " + + "(the OS suspends unfiltered scans, so silence would prove nothing)", + ) + // Do not carry half a count into the next screen-on period. + silentScans = 0 + return + } + val heardOpen = probeUnfiltered(UNFILTERED_THROTTLE_PROBE_MS) + noteScanOutcome(heardOpen, UNFILTERED_THROTTLE_PROBE_MS) + } + + /** + * Open 1 s scan used only as a throttle detector. Counts against [OnePlusScanBudget] like any + * other start. ⚠️ ASYNC IMPACT: blocks the BLE executor for up to [timeoutMs] plus budget wait. + */ + private fun probeUnfiltered(timeoutMs: Long): Boolean { + val leScanner = bluetoothManager.adapter?.bluetoothLeScanner ?: return false + val heard = AtomicBoolean(false) + val latch = CountDownLatch(1) + val cb = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + heard.set(true) + latch.countDown() + } + + override fun onBatchScanResults(results: MutableList) { + if (results.isNotEmpty()) { + heard.set(true) + latch.countDown() + } + } + + override fun onScanFailed(errorCode: Int) { + if (shouldBackOffOnScanFailed(errorCode)) { + OnePlusScanBudget.blockFor(SystemClock.elapsedRealtime(), OnePlusScanBudget.WINDOW_MS) + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: [$slot] unfiltered probe failed errorCode=$errorCode — " + + "backing off one budget window", + ) + } + heard.set(true) + latch.countDown() + } + } + awaitScanBudgetSlot() + return try { + val settings = ScanSettings.Builder() + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build() + leScanner.startScan(null, settings, cb) + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] unfiltered throttle probe started timeoutMs=$timeoutMs", + ) + latch.await(timeoutMs.coerceAtLeast(1L), TimeUnit.MILLISECONDS) + heard.get() + } catch (t: Throwable) { + OnePlusLog.w("${OnePlusLogMarkers.SCAN}: [$slot] unfiltered probe ${t.message}") + false + } finally { + try { + leScanner.stopScan(cb) + } catch (_: Throwable) { + } + } + } + + /** + * Direct OS refusal. Some builds still omit this callback and fail silent — that path is the + * unfiltered probe, not filtered-window silence. + */ + private fun noteScanOutcome(heardAnything: Boolean, timeoutMs: Long) { + val next = nextSilentScanState(silentScans, heardAnything) + silentScans = next.silentScans + if (!next.backOff) return + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: [$slot] $SILENT_SCANS_BEFORE_BACKOFF silent unfiltered probes " + + "(${timeoutMs}ms each, no advertisement at all) — the OS may be refusing our scans " + + "(\"scanning too frequently\"); backing off one budget window", + ) + OnePlusScanBudget.blockFor(SystemClock.elapsedRealtime(), OnePlusScanBudget.WINDOW_MS) + } + + /** + * Hold this (background) thread until the shared [OnePlusScanBudget] grants a start slot, so + * two slots waiting for their sensors cannot together trip the platform's silent scan throttle. + * Returns with the slot already booked. + */ + private fun awaitScanBudgetSlot() { + var logged = false + while (true) { + val wait = OnePlusScanBudget.reserve(SystemClock.elapsedRealtime()) + if (wait <= 0L) return + if (!logged) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] scan budget full — deferring startScan ${wait}ms", + ) + logged = true + } + try { + Thread.sleep(wait.coerceAtMost(OnePlusScanBudget.MAX_SLEEP_SLICE_MS)) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + return + } + } + } + + private fun handle(result: ScanResult) { + val device = result.device ?: return + val address = device.address ?: return + val name = device.name ?: result.scanRecord?.deviceName + val hasAdvUuid = result.scanRecord?.serviceUuids?.any { + it.uuid == OnePlusGattUuids.Advertisement + } == true + val hint = sessionHint + val candidate = OnePlusAdvCandidate.isCandidate(name, address, hint) + val g6MarketingName = name?.startsWith("Dexcom", ignoreCase = true) == true + // FEBC alone is OK for nameless G7 ADVs; reject FEBC+Dexcom* (G6 companions). + val febcOk = hasAdvUuid && !g6MarketingName + if (!candidate && !febcOk && !nameMatches(name)) return + // When we have a sticky session, drop weak unrelated FEBC noise unless name/MAC matches. + // "Sticky" means the hint really knows a transmitter. A hint that only carries the code on + // screen knows none, and must not hide the nameless FEBC advertisement of a new sensor. + val sticky = !hint?.lastMac.isNullOrBlank() || !hint?.lastDeviceName.isNullOrBlank() + if (sticky && !candidate && febcOk && !nameMatches(name)) return + + val hit = OnePlusScanResult(address = address, name = name, rssi = result.rssi) + .apply { seenElapsedMs = SystemClock.elapsedRealtime() } + val previous = seen.put(address, hit) + if (previous == null || previous.rssi != hit.rssi || previous.name != hit.name) { + val score = OnePlusAdvCandidate.rankScore(name, address, hit.rssi, hint) + OnePlusLog.d( + "${OnePlusLogMarkers.SCAN}: [$slot] device name=${name ?: "?"} rssi=${hit.rssi} " + + "score=$score addr=***${address.takeLast(5)}", + ) + listener?.onDevice(hit) + } + } + + companion object { + + /** + * Consecutive filtered windows with no callback at all before we run a 1 s unfiltered + * probe. Five, so a quiet sensor does not pay for a probe on every pair of 3 s waits. + */ + const val UNFILTERED_THROTTLE_PROBE_EVERY = 5 + + /** Length of the unfiltered throttle probe. Short: it only needs to hear *anything*. */ + const val UNFILTERED_THROTTLE_PROBE_MS = 1_000L + + /** + * Consecutive scan windows with no advertisement at all before we assume the OS is refusing + * our scans. Two, so a genuinely quiet moment (every sensor asleep, no neighbour) does not + * trigger a needless cool-down. Fed only by the unfiltered probe, never by a filtered wait. + */ + const val SILENT_SCANS_BEFORE_BACKOFF = 2 + + /** Result of one scan window: silent windows counted so far, and whether to cool down now. */ + internal data class SilentScanState(val silentScans: Int, val backOff: Boolean) + + /** + * Pure counter step of [noteScanOutcome], so the back-off rule can be tested without the + * Android BLE stack. The counter restarts after a back-off, so a permanently blind scanner + * cools down once per [SILENT_SCANS_BEFORE_BACKOFF] windows and not on every window. + */ + internal fun nextSilentScanState(previousSilentScans: Int, heardAnything: Boolean): SilentScanState = + when { + heardAnything -> SilentScanState(silentScans = 0, backOff = false) + previousSilentScans + 1 >= SILENT_SCANS_BEFORE_BACKOFF -> SilentScanState(silentScans = 0, backOff = true) + else -> SilentScanState(previousSilentScans + 1, backOff = false) + } + + internal fun nextFilteredSilentWindows(previous: Int): Int = previous + 1 + + internal fun shouldRunUnfilteredThrottleProbe(consecutiveFilteredSilentWindows: Int): Boolean = + consecutiveFilteredSilentWindows > 0 && + consecutiveFilteredSilentWindows % UNFILTERED_THROTTLE_PROBE_EVERY == 0 + + /** + * Direct `onScanFailed` codes that mean the OS refused or starved the scanner. + * `ALREADY_STARTED` is not a throttle. + */ + internal fun shouldBackOffOnScanFailed(errorCode: Int): Boolean = when (errorCode) { + ScanCallback.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED, + ScanCallback.SCAN_FAILED_INTERNAL_ERROR, + ScanCallback.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES, + ScanCallback.SCAN_FAILED_SCANNING_TOO_FREQUENTLY -> true + else -> false + } + + fun nameMatches(name: String?): Boolean = OnePlusAdvCandidate.nameMatchesSoft(name) + + /** Unchanged behaviour, kept here so the Android call sites and their tests still read the same. */ + fun autoSelectSingle(devices: List): OnePlusScanResult? = + OnePlusScanSelection.autoSelectSingle(devices) + + /** + * Unchanged behaviour - see [OnePlusScanSelection.autoSelect] for the rule itself. + * + * The rule is in shared code. This stays as the name Android already called. + */ + fun autoSelect(devices: List, hint: OnePlusStoredSession?): OnePlusScanResult? = + OnePlusScanSelection.autoSelect(devices, hint) + + internal fun normalizeTargetAddress(address: String): String = address.uppercase() + + /** + * A FEBC advertiser that is a G7-family transmitter: either a nameless ADV (G7/ONE+ often + * advertise without a local name) or a `DXCM`/`DX0x` name — never a G6 `Dexcom*` companion. + */ + internal fun isG7FamilyAdvertisement(name: String?): Boolean = when { + name.isNullOrBlank() -> true + name.startsWith("Dexcom", ignoreCase = true) -> false + else -> nameMatches(name) + } + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAndroidCpuLease.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAndroidCpuLease.kt new file mode 100644 index 000000000000..7ada72ea8958 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAndroidCpuLease.kt @@ -0,0 +1,39 @@ +package app.aaps.plugins.dexcomoneplus.session + +import android.content.Context +import android.os.PowerManager +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers + +/** + * Android [OnePlusCpuLease]: a partial wake lock, the same one the session used to take itself. + * + * @param slot which sensor slot asked for it, so the log line still says who is holding it. + */ +class OnePlusAndroidCpuLease(context: Context, private val slot: String) : OnePlusCpuLease { + + private val appContext = context.applicationContext + + override fun hold(maxMillis: Long): OnePlusCpuLease.Hold? = + try { + val pm = appContext.getSystemService(Context.POWER_SERVICE) as PowerManager + val lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS::DexcomOnePlusAuth") + lock.setReferenceCounted(false) + lock.acquire(maxMillis) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] wakeLock acquired ${maxMillis}ms") + WakeLockHold(lock) + } catch (t: Throwable) { + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: [$slot] wakeLock ${t.message}") + null + } + + private class WakeLockHold(private val lock: PowerManager.WakeLock) : OnePlusCpuLease.Hold { + + override fun release() { + try { + if (lock.isHeld) lock.release() + } catch (_: Throwable) { + } + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutor.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutor.kt new file mode 100644 index 000000000000..c803bd0f6b62 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutor.kt @@ -0,0 +1,36 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * The one thread the driver runs its blocking work on. + * + * A session is written as a blocking cycle - connect, authenticate, read a value, wait, go again - + * so it needs a thread it can hold for minutes. It has to be exactly one thread: two cycles at once + * on the same sensor would run two handshakes over the same link, which kills both. + * + * This is the slice of `Executors.newSingleThreadExecutor` the driver uses and nothing more, so + * the shared code does not depend on a JVM class. + */ +internal interface OnePlusBleExecutor { + + /** + * Queues [block] on this executor's thread, behind everything queued before it. + * + * Throws when the executor has already been stopped by [shutdownNow]. That is what the JVM + * executor did, so every call site in the driver already runs inside a `try`. + */ + fun execute(block: () -> Unit) + + /** + * Stops the executor for good. Nothing queued runs after this and nothing new is accepted. + * + * ⚠️ This is **not** how a running session is stopped. The driver stops the session itself + * first, and that is the signal the cycle reads. Android also interrupts the thread, which cuts + * a wait short, but not every platform can do that. Nothing may be built on the interrupt. + * + * A stopped executor is never reused: the driver builds a fresh one in its place. + */ + fun shutdownNow() +} + +/** A new executor, stopped only by [OnePlusBleExecutor.shutdownNow]. */ +internal expect fun onePlusBleExecutor(): OnePlusBleExecutor diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt new file mode 100644 index 000000000000..f249e82eeeb1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt @@ -0,0 +1,50 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanListener + +/** + * Native Dexcom ONE+ BLE driver façade. + * + * The implementation is [OnePlusCgmDriverReal], which is shared code: + * it builds and drives the session on both phones, and everything the phone itself owns is behind + * [OnePlusPlatform]. The KEKS handshake (`:plugins:libkeks`) and `OnePlusSessionAuthKeks` are + * shared too. + * + * ⚠️ ASYNC IMPACT: Real driver may invoke [OnePlusGlucoseWatcher] / scan listeners off the main + * thread (bleExecutor / binder). Callers must not assume main; do not run dosing or UI work there. + */ +interface OnePlusCgmDriver { + + /** + * Give the driver the phone it runs on, before anything else is asked of it. + * + * This replaced `setContext(Context)`. The driver needs four favours from its host and only a + * file store means the same thing on both platforms, so the favours are named one by one in + * [OnePlusPlatform] instead of being hidden behind one Android type. Calling it again is + * allowed and rebuilds the scanner and the store; a link that is already up is not dropped. + */ + fun attach(platform: OnePlusPlatform) + fun addWatcher(watcher: OnePlusGlucoseWatcher) + fun removeWatcher(watcher: OnePlusGlucoseWatcher) + fun startScan(listener: OnePlusScanListener) + fun stopScan() + fun connect(deviceAddress: String, pairingCode: String) + fun disconnect() + fun shutdown() + fun warmupState(): OnePlusWarmupState + fun isSessionUp(): Boolean + + /** + * Ask the driver to bring back the session it has stored, after the app was restarted. + * + * The driver keeps the sensor it last talked to - its address, its pairing code and its key - + * so it can connect again without the user doing anything. This asks it to do that now. + * + * Default is false, which is the honest answer for a driver that stores no session: it did not + * queue anything, and the caller must not show the sensor as coming back. + * + * @return true when a reconnect was queued. False when nothing was stored, when the stored + * session is incomplete, or when a session is already running. + */ + fun resumeStoredSession(): Boolean = false +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt new file mode 100644 index 000000000000..db5195857f5d --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt @@ -0,0 +1,637 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanListener +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanResult +import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession +import app.aaps.plugins.dexcomoneplus.session.OnePlusMacArbiter +import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSessionSkeleton +import app.aaps.plugins.dexcomoneplus.session.OnePlusConnectPrep +import app.aaps.plugins.dexcomoneplus.session.OnePlusSessionAuthKeks +import app.aaps.plugins.dexcomoneplus.session.OnePlusSessionStart +import kotlin.concurrent.Volatile +import kotlin.concurrent.atomics.AtomicInt +import kotlin.concurrent.atomics.ExperimentalAtomicApi +import kotlin.concurrent.atomics.incrementAndFetch + +internal object OnePlusCgmDriverResumePolicy { + fun canResume(storedSession: OnePlusStoredSession?): Boolean = + storedSession?.lastMac?.isNotBlank() == true && + OnePlusSessionStart.isValidPairingCode(storedSession.identity.pin) && + storedSession.sharedKey?.size == SHARED_KEY_SIZE + + private const val SHARED_KEY_SIZE = 16 +} + +/** + * Real driver: LE scan + GATT + KEKS + Control EGV loop. + * + * ⚠️ ASYNC IMPACT: scan on binder; connect/auth/EGV on [bleExecutor] (blocks that thread). + * [disconnect] / [shutdown] call [OnePlusBleSession.stop] directly so GATT disconnect can + * unblock [OnePlusGattClient.awaitControlNotify]. Watchers may be off main. + * + * ## One driver, two platforms + * + * This is shared code. It was Android only for as long as it used an Android clock and the JVM's + * threads and collections, none of which it needed for what it decides: everything the phone + * really owns is behind [OnePlusPlatform] and its four members. Keep it that way - a rule that + * lands here rather than behind the port is a rule only one of the two phones follows. + * + * @param storeNamespace per-slot key-value namespace for the sensor store (null = the original + * single-sensor file; "staging" = the pre-soak second sensor). Lets two driver instances run + * concurrently without sharing identity / MAC / KEKS key / ingest markers. **A second instance + * needs a platform that allows two Bluetooth scans at once**, as Android does. + */ +@OptIn(ExperimentalAtomicApi::class) +class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { + + /** + * Which preferences file this instance's sessions read and write. + * + * A `var` and not a constructor `val`: a promotion hands a **live link** from the staging slot + * over to production, and the link must not be dropped — but from that moment every new session + * this instance opens has to read and write the production file. See [rebindStore]. + */ + @Volatile + private var storeNamespace: String? = storeNamespace + + /** + * `prod` / `staging` — logged on every marker so a dual-sensor trace is attributable. + * + * Fixed for the whole life of the instance, even after a promotion, so a bug report stays + * readable across the swap: a promoted instance is production but still calls itself "staging" + * in the log. + */ + private val slot: String = OnePlusLogMarkers.slotOf(storeNamespace) + + /** + * [OnePlusMacArbiter] owner token for this instance: unique for its whole life, unlike [slot] + * which the next staging instance reuses. Keying the arbiter on [slot] would let that next + * pre-soak's claim silently release the promoted instance's claim on the sensor still feeding + * the loop — see [OnePlusMacArbiter]'s warning. + */ + private val arbiterOwner: String = "$slot#${nextInstance.incrementAndFetch()}" + + /** + * Guards [watchers] only, never anything else. + * + * This used to be a `CopyOnWriteArrayList`, which has no multiplatform form. The list is read + * far more often than it is written and it is read while a session thread is running, so + * [watchersSnapshot] copies it under this lock and the callers walk the copy - which is exactly + * what iterating a copy-on-write list did. [lifecycleLock] is never taken from inside this one, + * so the two cannot deadlock against each other. + */ + private val watchersLock = AapsLock() + private val watchers = mutableListOf() + private val lifecycleLock = AapsLock() + + /** The host this driver is attached to. Null until [attach]. */ + @Volatile + private var platform: OnePlusPlatform? = null + private var operationGeneration = 0L + private var resumeQueued = false + + @Volatile + private var bleExecutor: OnePlusBleExecutor = onePlusBleExecutor() + + @Volatile + private var scanner: OnePlusBleScanner = OnePlusBleScannerStub() + + @Volatile + private var session: OnePlusBleSession? = null + + @Volatile + private var profile: OemDeviceProfile = DeviceProfileRegistry.GenericFallback + + @Volatile + private var sensorStore: OnePlusSensorStore? = null + + /** Last ADV name seen for [connect] target — persisted on auth success. */ + @Volatile + private var pendingDeviceName: String? = null + + /** + * When the ADV sighting handed off from the UI for the [connect] target was seen, on the + * monotonic clock of [onePlusElapsedMs] (0 = none). Lets [prepareConnect] skip the blind + * re-scan when the sensor was just seen. + */ + @Volatile + private var pendingAdvSightingElapsedMs: Long = 0L + + override fun attach(platform: OnePlusPlatform) { + this.platform = platform + val store = storeFor(platform, storeNamespace) + sensorStore = store + scanner = platform.scanner(hint = store.load(), slot = slot) + profile = DeviceProfileRegistry.resolve() + } + + private fun storeFor(platform: OnePlusPlatform, namespace: String?): OnePlusSensorStore = + OnePlusSensorStore(platform.sensorPrefs(OnePlusSensorStore.prefsFileName(namespace))) + + fun sensorStore(): OnePlusSensorStore? = sensorStore + + /** + * Points this instance at another slot's preferences file, without dropping a running link. + * + * Used once, by a promotion. The running Control/EGV loop must follow the new file at once: it + * reconnects itself every few minutes and never ends before an app restart, and the promotion + * clears the staging file right after this call. So the session reads `sensorStore` on every + * call instead of keeping it in a local (see `createSession`). + */ + fun rebindStore(namespace: String?) { + storeNamespace = namespace + platform?.let { sensorStore = storeFor(it, namespace) } + } + + fun saveIdentity(identity: OnePlusSensorIdentity) { + sensorStore?.saveIdentity(identity) + scanner.updateSessionHint(sensorStore?.load()) + } + + /** + * KEKS key of the slot this instance owns **right now**, for the running session's short auth. + * + * Read through the live field, never through a captured store: a promotion rebinds this instance + * under its own running link (see [rebindStore]). + */ + fun savedSharedKey(): ByteArray? = sensorStore?.load()?.sharedKey + + /** + * Let go of a session that has ended on its own, so the reconnect watchdog can start a new one. + * + * `startWithPairingCode` blocks for the whole life of the link and returns when the link is + * over. That includes the terminal `OnePlusBleSession.fail` path (for example after + * `ONEPLUS_RECONNECT_EXHAUSTED` or a bad PIN), which sets its own `running` flag to false and + * **returns normally instead of throwing**. Before this, nothing then cleared [session] and + * [resumeQueued], so the driver stayed "busy" for ever with a link that was down: + * `isSessionUp()` said false, while every wake-up of the plugin's reconnect watchdog got the + * answer "auto-resume already active". The only ways out were an app restart or a manual + * Connect, and no glucose came in until then. + * + * Guarded on both the operation generation and the session identity: a newer connect may have + * replaced this one while its thread was ending, and the old session must not release the newer + * one. + */ + private fun releaseSessionIfCurrent(generation: Long, ended: OnePlusBleSession) { + lifecycleLock.withLock { + if (generation != operationGeneration || session !== ended) return + session = null + resumeQueued = false + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] session released — the watchdog may start a new one", + ) + } + + /** Persist the MAC / KEKS key of a successful auth into the slot this instance owns right now. */ + fun onAuthSucceeded(address: String, key: ByteArray) { + val store = sensorStore + store?.saveLastMac(address) + store?.saveSharedKey(key) + pendingDeviceName?.let { store?.saveLastDeviceName(it) } + scanner.updateSessionHint(store?.load()) + } + + /** Forget the stored KEKS key of the slot this instance owns right now (auth refused it). */ + fun onAuthInvalidated() { + val store = sensorStore + store?.clearSharedKey() + scanner.updateSessionHint(store?.load()) + } + + override fun addWatcher(watcher: OnePlusGlucoseWatcher) { + watchersLock.withLock { + if (!watchers.contains(watcher)) watchers.add(watcher) + } + } + + override fun removeWatcher(watcher: OnePlusGlucoseWatcher) { + watchersLock.withLock { watchers.remove(watcher) } + } + + /** + * The watchers as they are right now, for a caller that is about to walk them. + * + * A copy, so a watcher that adds or removes one while it is being told something cannot change + * the list under the walk. That is what iterating a copy-on-write list gave before. + */ + private fun watchersSnapshot(): List = + watchersLock.withLock { watchers.toList() } + + override fun startScan(listener: OnePlusScanListener) { + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: [$slot] start") + scanner.startScan(listener) + } + + override fun stopScan() { + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: [$slot] stop") + scanner.stopScan() + } + + override fun connect(deviceAddress: String, pairingCode: String) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] connect requested (Real GATT+KEKS+EGV)", + ) + // The transmitter has one owner — see OnePlusMacArbiter. Refused means the other slot is on + // this sensor, and opening a second session would corrupt both KEKS handshakes. Nothing is + // written to the store on a refusal: the slot must stay exactly as it was. + if (!OnePlusMacArbiter.claim(deviceAddress, arbiterOwner)) { + watchersSnapshot().forEach { + it.onError("ONEPLUS_SESSION: sensor already in use by the other slot", false) + } + return + } + scanner.stopScan() + // Stop any in-flight reconnect loop (may still be targeting a previous MAC). + // The three values come back as one result: `withLock` declares no callsInPlace contract, + // so a `val` cannot be assigned inside the block. + val (previousSession, generation, executor) = lifecycleLock.withLock { + operationGeneration++ + val newGeneration = operationGeneration + val previous = session + session = null + resumeQueued = false + Triple(previous, newGeneration, bleExecutor) + } + previousSession?.stop("superseded") + sensorStore?.saveIdentity( + OnePlusSensorIdentity( + pin = pairingCode, + serial = sensorStore?.load()?.identity?.serial, + gtin = sensorStore?.load()?.identity?.gtin, + rawGs1 = sensorStore?.load()?.identity?.rawGs1, + ), + ) + sensorStore?.saveLastMac(deviceAddress) + // Fresh (re)pairing from the UI: drop any stale KEKS shared key so attempt 0 runs full + // J-PAKE instead of a short-auth that the transmitter rejects (field: stale preload → + // auth=2 → a wasted connect cycle + FAILED). A successful auth re-persists a new key, so + // silent reconnects inside the session loop still short-auth. + sensorStore?.clearSharedKey() + scanner.updateSessionHint(sensorStore?.load()) + try { + lifecycleLock.withLock { + if (generation != operationGeneration || executor !== bleExecutor) return + executor.execute { + val created = lifecycleLock.withLock { + if (generation != operationGeneration) return@execute + createSession( + requestNewSensorStart = true, + generation = generation, + ).also { session = it } + } + try { + created.startWithPairingCode(deviceAddress, pairingCode) + } catch (t: Throwable) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: [$slot] ${t.message}", t) + watchersSnapshot().forEach { + it.onError(t.message ?: "ONEPLUS_CONNECT_FAILED", fatal = false) + it.onWarmup( + OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.FAILED, + message = t.message, + ), + ) + } + } finally { + releaseSessionIfCurrent(generation, created) + } + } + } + } catch (t: Throwable) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: [$slot] connect queue ${t.message}", + t, + ) + } + } + + /** + * Restores an authenticated sensor after process/plugin recreation without clearing its KEKS + * key and without allowing SessionStart. + * + * ⚠️ ASYNC IMPACT: queues at most one resume on [bleExecutor]. The resumed session itself owns + * persistent ADV waiting and all later reconnects. + */ + override fun resumeStoredSession(): Boolean { + val stored = sensorStore?.load() + if (!OnePlusCgmDriverResumePolicy.canResume(stored)) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] auto-resume skipped — stored session incomplete", + ) + return false + } + val deviceAddress = stored?.lastMac ?: return false + // The path that reproduced the collision on every plugin start for an install whose two + // stores already held the same MAC. Claim before queueing anything. + if (!OnePlusMacArbiter.claim(deviceAddress, arbiterOwner)) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] auto-resume skipped — the other slot owns this sensor", + ) + return false + } + val pairingCode = stored.identity.pin + // One result from the lock, see connect(): `withLock` declares no callsInPlace contract. + val (generation, executor) = lifecycleLock.withLock { + if (resumeQueued || session != null) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] auto-resume already active", + ) + return false + } + resumeQueued = true + operationGeneration++ + val queuedGeneration = operationGeneration + val queuedExecutor = bleExecutor + // A stored device name is identity metadata, not a fresh UI ADV selection. + pendingDeviceName = null + pendingAdvSightingElapsedMs = 0L + scanner.updateSessionHint(stored) + queuedGeneration to queuedExecutor + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] auto-resume queued mac=***${deviceAddress.takeLast(5)} " + + "savedKey=true newStart=false", + ) + try { + lifecycleLock.withLock { + if (generation != operationGeneration || executor !== bleExecutor) return false + executor.execute { + val created = lifecycleLock.withLock { + if (generation != operationGeneration) return@execute + createSession( + requestNewSensorStart = false, + generation = generation, + ).also { session = it } + } + try { + created.startWithPairingCode(deviceAddress, pairingCode) + } catch (t: Throwable) { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: [$slot] auto-resume ${t.message}", + t, + ) + watchersSnapshot().forEach { + it.onError(t.message ?: "ONEPLUS_AUTO_RESUME_FAILED", fatal = false) + } + } finally { + releaseSessionIfCurrent(generation, created) + } + } + } + } catch (t: Throwable) { + lifecycleLock.withLock { + if (generation == operationGeneration) { + resumeQueued = false + } + } + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: [$slot] auto-resume queue ${t.message}", + t, + ) + return false + } + return true + } + + /** + * UI entry point: hands off the freshest ADV [sighting] (name + `seenElapsedMs`) so + * [prepareConnect] can connect in-window without a blind re-scan. + */ + fun connect( + deviceAddress: String, + pairingCode: String, + sighting: OnePlusScanResult?, + ) { + val name = sighting?.name + pendingDeviceName = name + pendingAdvSightingElapsedMs = sighting?.seenElapsedMs ?: 0L + if (!name.isNullOrBlank()) { + sensorStore?.saveLastDeviceName(name) + } + connect(deviceAddress, pairingCode) + } + + override fun disconnect() { + // Must not queue behind a blocking Control/EGV loop on bleExecutor. + val previousSession = lifecycleLock.withLock { + operationGeneration++ + resumeQueued = false + session.also { session = null } + } + previousSession?.stop("disconnect") + OnePlusMacArbiter.release(arbiterOwner) + } + + override fun shutdown() { + try { + scanner.stopScan() + } catch (_: Throwable) { + } + // One result from the lock, see connect(): `withLock` declares no callsInPlace contract. + val (previousSession, previousExecutor) = lifecycleLock.withLock { + operationGeneration++ + resumeQueued = false + val previous = session + session = null + val oldExecutor = bleExecutor + bleExecutor = onePlusBleExecutor() + previous to oldExecutor + } + try { + previousSession?.stop("shutdown") + } catch (_: Throwable) { + } + watchersLock.withLock { watchers.clear() } + previousExecutor.shutdownNow() + OnePlusMacArbiter.release(arbiterOwner) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] shutdown") + } + + override fun warmupState(): OnePlusWarmupState = + session?.warmupState() ?: OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + + override fun isSessionUp(): Boolean = session?.isUp() == true + + private fun createSession( + requestNewSensorStart: Boolean, + generation: Long, + ): OnePlusBleSession { + val host = platform ?: error("ONEPLUS_SESSION: attach required") + val gatt = host.gattClient(profile) + val auth = OnePlusSessionAuthKeks(gatt) + val created = OnePlusBleSessionSkeleton( + gatt = gatt, + auth = auth, + profile = profile, + onWarmup = { state -> + ifCurrentOperation(generation) { + watchersSnapshot().forEach { it.onWarmup(state) } + } + }, + onSession = { up, reason -> + ifCurrentOperation(generation) { + watchersSnapshot().forEach { it.onSession(up, reason) } + } + }, + onError = { message, fatal -> + ifCurrentOperation(generation) { + watchersSnapshot().forEach { it.onError(message, fatal) } + } + }, + onGlucose = { sample -> + ifCurrentOperation(generation) { + watchersSnapshot().forEach { it.onGlucose(sample) } + } + }, + // Auto-resume always passes false; only an explicit new-sensor connect may start. + requestNewSensorStart = requestNewSensorStart, + beforeConnect = { address, attempt, scanMs -> prepareConnect(address, attempt, scanMs) }, + // Read `sensorStore` on every call, never through a captured local: a promotion calls + // [rebindStore] under a LIVE link, and that link then runs for the rest of the session. + // A captured store would keep reading the cleared staging file (no PIN -> load() null -> + // a full re-pair on every reconnect) and would write the new key back into it. + savedSharedKeyProvider = { savedSharedKey() }, + onAuthSuccess = { address, key -> + ifCurrentOperation(generation) { + onAuthSucceeded(address, key) + } + }, + onAuthInvalidate = { + ifCurrentOperation(generation) { + onAuthInvalidated() + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] cleared persisted KEKS shared key", + ) + } + }, + cpuLease = host.cpuLease(slot), + slot = slot, + ) + return created + } + + private fun ifCurrentOperation(generation: Long, action: () -> Unit) { + lifecycleLock.withLock { + if (generation == operationGeneration) { + action() + } + } + } + + /** + * Ob1 / Samsung recovery before the GATT `connect`, returning [OnePlusConnectPrep] + * (whether a **fresh ADV** is in hand → session does a fast direct connect). + * + * 1. **Handoff fast-path:** if the UI (or a prior in-window rescan) saw this MAC within + * [ADV_HANDOFF_FRESH_MS], connect immediately — no blind re-scan. This is what removes the + * ~8 s wasted scan + the ~48 s autoConnect park seen in the field log. + * 2. Otherwise LE-scan via [OnePlusBleScanner.awaitTarget] (private ScanCallback so UI + * [stopScan] cannot cancel it). A hit → fresh; a miss with + * [OemDeviceProfile.requireAdvBeforeConnect] on attempt 0 (and no UI selection) → defer. + * + * ⚠️ ASYNC IMPACT: blocks bleExecutor; binder delivers ADV into awaitTarget. + */ + private fun prepareConnect( + deviceAddress: String, + attempt: Int, + /** Overrides [app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile.preConnectScanMs]; null keeps the profile value. */ + scanMsOverride: Long? = null, + ): OnePlusConnectPrep { + val target = deviceAddress.uppercase() + val sightingAgeMs = + if (pendingAdvSightingElapsedMs > 0L) { + onePlusElapsedMs() - pendingAdvSightingElapsedMs + } else { + Long.MAX_VALUE + } + if (sightingAgeMs in 0..ADV_HANDOFF_FRESH_MS) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] pre-connect handoff — fresh ADV ${sightingAgeMs}ms old, " + + "skip rescan (attempt=$attempt mac=***${target.takeLast(5)})", + ) + return OnePlusConnectPrep(advFresh = true) + } + + // A long window costs the same single scan registration as a short one but hears the ADV the + // moment it arrives, so the persistent wait overrides the profile value here. + val scanMs = scanMsOverride ?: profile.preConnectScanMs + if (scanMs <= 0L) return OnePlusConnectPrep(advFresh = false) + // UI Connect just selected this ADV → don't hard-fail if re-scan misses briefly. + // + // A name alone is not enough. The start screen may pre-select a sensor it has only ever read + // from the store, and that entry carries the stored ADV name with no sighting behind it. Such + // an entry used to claim "the UI just selected this", which switched off + // [OemDeviceProfile.requireAdvBeforeConnect] — the one guard that stops a blind connect. The + // timestamp is what separates a real sighting from a remembered name. + val uiJustSelected = !pendingDeviceName.isNullOrBlank() && pendingAdvSightingElapsedMs > 0L + val hardRequireAdv = + profile.requireAdvBeforeConnect && attempt == 0 && !uiJustSelected + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] pre-connect awaitTarget ${scanMs}ms attempt=$attempt " + + "requireAdv=${profile.requireAdvBeforeConnect} hardRequire=$hardRequireAdv " + + "uiJustSelected=$uiJustSelected", + ) + try { + val wait = scanner.awaitTarget(target, scanMs) + val hit = wait.target + if (hit != null) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] pre-connect ADV name=${hit.name} " + + "rssi=${hit.rssi} mac=***${target.takeLast(5)}", + ) + if (!hit.name.isNullOrBlank()) pendingDeviceName = hit.name + return OnePlusConnectPrep(advFresh = true) + } + // Our MAC stayed silent. Any OTHER ONE+ heard in the same window is the signature of a + // stale stored MAC (sensor replaced, or started into the other slot) — the session turns + // this into a user-visible error once the silence is long enough to be conclusive. + val foreign = wait.strongestForeign()?.let { other -> + "name=${other.name ?: "?"} rssi=${other.rssi} mac=***${other.address.takeLast(5)}" + } + if (hardRequireAdv) { + throw IllegalStateException( + "ONEPLUS_SCAN: ADV not seen in ${scanMs}ms — defer connect (keep screen on, sensor close)", + ) + } + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: [$slot] pre-connect ADV not seen in ${scanMs}ms " + + "(attempt=$attempt known MAC uiJustSelected=$uiJustSelected foreign=${foreign ?: "-"})", + ) + return OnePlusConnectPrep(advFresh = false, foreignAdv = foreign) + } catch (t: IllegalStateException) { + throw t + } catch (t: Throwable) { + OnePlusLog.w("${OnePlusLogMarkers.SCAN}: [$slot] pre-connect ${t.message}") + if (hardRequireAdv) { + throw IllegalStateException( + "ONEPLUS_SCAN: pre-connect failed — ${t.message}", + t, + ) + } + return OnePlusConnectPrep(advFresh = false) + } + } + + private companion object { + /** + * Max age of a handed-off ADV sighting still treated as "fresh" (skip rescan, direct + * connect). G7/ONE+ advertises in short windows, so a sighting older than this may already + * be quiet and a direct connect would miss the window. + */ + const val ADV_HANDOFF_FRESH_MS = 6_000L + + /** Process-wide counter so every instance's [arbiterOwner] is unique — see its doc comment. */ + val nextInstance = AtomicInt(0) + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverStub.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverStub.kt new file mode 100644 index 000000000000..8f98b3c7a67c --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverStub.kt @@ -0,0 +1,96 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanListener +import kotlin.concurrent.Volatile + +/** + * A driver that never connects. Emits FAILED on connect. + * + * Production never uses it; it is for tests. It never reports a reading and never claims a + * session, so nothing downstream can mistake it for a working sensor. + */ +class OnePlusCgmDriverStub : OnePlusCgmDriver { + + /** + * Watchers, copied before every walk. + * + * Was a `CopyOnWriteArrayList`, which is JVM only. The list is read far more often than it is + * written, so a lock around the two writes plus a copy on read is the same bargain. + */ + private val watcherLock = AapsLock() + private val watchers = mutableListOf() + + @Volatile + private var platform: OnePlusPlatform? = null + + @Volatile + private var warmup = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + + @Volatile + private var sessionUp = false + + override fun attach(platform: OnePlusPlatform) { + this.platform = platform + } + + override fun addWatcher(watcher: OnePlusGlucoseWatcher) = watcherLock.withLock { + if (!watchers.contains(watcher)) watchers.add(watcher) + Unit + } + + override fun removeWatcher(watcher: OnePlusGlucoseWatcher) = watcherLock.withLock { + watchers.remove(watcher) + Unit + } + + private fun watcherSnapshot(): List = watcherLock.withLock { watchers.toList() } + + override fun startScan(listener: OnePlusScanListener) { + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: stub start (no LE scan)") + } + + override fun stopScan() { + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: stub stop") + } + + override fun connect(deviceAddress: String, pairingCode: String) { + val msg = "${OnePlusLogMarkers.STUB}: stub driver, no BLE" + warmup = OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.FAILED, + message = msg, + ) + sessionUp = false + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: stub connect → FAILED") + OnePlusLog.i( + "${OnePlusLogMarkers.WARMUP}: phase=${warmup.phase} remainingMs=null msg=${warmup.message}", + ) + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: $msg fatal=false") + val current = watcherSnapshot() + current.forEach { it.onWarmup(warmup) } + current.forEach { it.onError(msg, fatal = false) } + current.forEach { it.onSession(false, msg) } + } + + override fun disconnect() { + sessionUp = false + warmup = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: stub disconnect") + watcherSnapshot().forEach { it.onSession(false, "disconnect") } + } + + override fun shutdown() { + disconnect() + watcherLock.withLock { watchers.clear() } + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: stub shutdown") + } + + override fun warmupState(): OnePlusWarmupState = warmup + + override fun isSessionUp(): Boolean = sessionUp + + companion object { + val instance: OnePlusCgmDriverStub by lazy { OnePlusCgmDriverStub() } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt new file mode 100644 index 000000000000..ec2a6dc9368b --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt @@ -0,0 +1,110 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.core.interfaces.source.SensorSlot +import kotlin.concurrent.Volatile + +/** + * The driver instances for the two sensor slots. Production always runs the real driver, never + * [OnePlusCgmDriverStub]: a source that is switched on but never connects is worse than no source + * at all. + * + * The instances are plain nullable fields and not `by lazy` on purpose. + * + * A driver that was shut down can never open a session again, because `shutdown` also stops its + * executor for good. With `by lazy` the dead instance would be handed out for ever, and after one + * promotion there would be no working production driver left. A dropped field is rebuilt on the + * next call, so a second pre-soak and a second promotion still work. + */ +object OnePlusCgmDrivers { + + /** Key-value namespace for the staging slot's sensor store. */ + const val STAGING_NAMESPACE = "staging" + + private val lock = AapsLock() + + @Volatile + private var productionReal: OnePlusCgmDriverReal? = null + + /** + * Second, independent Real driver for the STAGING (pre-soak) sensor — its own BLE session, + * executor, scanner and namespaced sensor store, so it can run concurrently with production + * without sharing identity / key / ingest markers. + * + * ⚠️ This needs a platform that allows two Bluetooth scans at once, as Android does. + */ + @Volatile + private var stagingReal: OnePlusCgmDriverReal? = null + + /** + * Sensor-store namespace of a slot — the ONE definition, shared by the drivers and by any UI that + * opens a store (Start screen). null = production's original single-sensor file (non-breaking). + * + * Using the production store for the staging slot is what made a pre-soak silently adopt the + * sensor already in use: same stored MAC, same PIN, same KEKS key, so no second sensor was ever + * started and no new PIN could stick. + */ + fun storeNamespace(slot: SensorSlot): String? = when (slot) { + SensorSlot.PRODUCTION -> null + SensorSlot.STAGING -> STAGING_NAMESPACE + } + + /** The real production instance. Built on first use. */ + fun realProduction(): OnePlusCgmDriverReal = lock.withLock { + productionReal ?: OnePlusCgmDriverReal().also { productionReal = it } + } + + /** The dedicated STAGING driver instance (pre-soak second sensor). Built on first use. */ + fun staging(): OnePlusCgmDriverReal = lock.withLock { + stagingReal ?: OnePlusCgmDriverReal(storeNamespace = STAGING_NAMESPACE).also { stagingReal = it } + } + + /** The driver feeding the loop. */ + fun default(): OnePlusCgmDriver = realProduction() + + /** The production driver, with [watcher] attached. Adding the same watcher twice is harmless. */ + fun production(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = + realProduction().also { it.addWatcher(watcher) } + + /** + * Shuts both instances down and drops them, so the next call builds fresh ones. Tests use it to + * start from a registry with no live session and no leftover pre-soak. + */ + fun shutdownAll() { + val instances = lock.withLock { + val both = listOfNotNull(productionReal, stagingReal) + productionReal = null + stagingReal = null + both + } + // Outside the lock: shutdown disconnects GATT. + instances.forEach { runCatching { it.shutdown() } } + } + + /** + * Hands the staging instance the production role, keeping its live BLE link. + * + * Under [lock]: the promoted instance is pointed at the production preferences file and becomes + * the production instance; the staging pointer is freed so the next pre-soak builds a fresh + * instance. Without this swap, `default()` kept handing out the OLD (shut down) production + * instance for ever after a promotion — every screen that reads it directly (Status, Warmup) + * showed stale state, and the reconnect watchdog (which also reads `default()`) silently stopped + * protecting the promoted sensor. + * + * ⚠️ Do not turn these fields back into `by lazy`. A retired instance must be dropped, or the + * second promotion, days later, would hand out a driver whose executor is already stopped. + * + * @return the instance that has just been retired, for the caller to shut down **outside** the + * lock, or null when there was no staging instance to promote. + */ + fun promoteStagingInstance(): OnePlusCgmDriverReal? = + lock.withLock { + val promoted = stagingReal ?: return@withLock null + val retired = productionReal + promoted.rebindStore(null) + productionReal = promoted + stagingReal = null + retired + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsed.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsed.kt new file mode 100644 index 000000000000..c68524bcb6cb --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusElapsed.kt @@ -0,0 +1,15 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * Milliseconds on a clock that only moves forward and keeps counting while the phone sleeps. + * + * The driver measures two things with it: the age of an advertisement sighting, and the age of the + * current scan block. Neither may be measured on the wall clock, which the user and the network can + * move, and neither may be measured on a clock that stops in sleep - a wait that really took minutes + * would then look like milliseconds and the driver would act on it. + * + * On Android this is `SystemClock.elapsedRealtime()`. Only the difference between two readings + * means anything. + * `OnePlusScanResult.seenElapsedMs` is a value of this clock and nothing else. + */ +internal expect fun onePlusElapsedMs(): Long diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseSample.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseSample.kt new file mode 100644 index 000000000000..442b482cce73 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseSample.kt @@ -0,0 +1,20 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * Parsed glucose sample from the native One+ session. + */ +data class OnePlusGlucoseSample( + val mgdl: Double, + val timestampMs: Long, + /** + * Rate of change the sensor reports, in mg/dL per minute (EGV trend byte / 10), or null when the + * sensor sends the invalid marker. + * + * The unit is in the name on purpose. This used to be a `String?` called `trendArrowRaw`, which + * read like an arrow name — so the AAPS side fed it to `TrendArrow.fromString`, never matched a + * label, and silently stored `TrendArrow.NONE` on every single ONE+ reading. Turning the slope + * into an arrow is the ingest layer's job, see `DexcomOnePlusIngest.trendArrowFor`. + */ + val trendSlopeMgdlPerMin: Double? = null, + val sequence: Long? = null, +) diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseWatcher.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseWatcher.kt new file mode 100644 index 000000000000..5477a571b2b7 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusGlucoseWatcher.kt @@ -0,0 +1,11 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * Callback surface for `OnePlusCgmDriver`. + */ +interface OnePlusGlucoseWatcher { + fun onWarmup(state: OnePlusWarmupState) + fun onGlucose(sample: OnePlusGlucoseSample) + fun onSession(up: Boolean, reason: String?) + fun onError(message: String, fatal: Boolean) +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLog.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLog.kt new file mode 100644 index 000000000000..ee4eb092c6dd --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLog.kt @@ -0,0 +1,43 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * How bad a driver log line is, so each platform can map it onto its own levels. + */ +internal enum class OnePlusLogLevel { DEBUG, INFO, WARN, ERROR } + +/** + * Writes one driver log line on the platform the driver is running on. + * + * This is the only part of the driver's logging that is platform specific. Everything else - what + * is logged, when, and under which marker - is shared code, so the two platforms cannot drift. + */ +internal expect fun onePlusLogWrite(level: OnePlusLogLevel, message: String, cause: Throwable?) + +/** + * Where this driver writes what it is doing. + * + * On Android it goes through slf4j rather than `android.util.Log` for one reason: AAPS already + * writes everything that comes through slf4j to `AndroidAPS.log`, a rolling file with months of + * history, and **Maintenance, Send logs** already collects those files. A driver that logged + * straight to Android would be invisible to that: its lines would live only in the phone's own ring + * buffer, which holds minutes on a busy phone and which an app may not even be allowed to read back. + * + * The line still reaches the phone's log as well, under the same tag as before, so + * `adb logcat | grep DEXCOM_ONEPLUS` keeps working while a developer is watching. + * + * Note that this writes whatever it is given, without asking the AAPS log settings. That is on + * purpose for a CGM driver: the whole point of these lines is to exist + * when something fails, and a user who has hit a failure cannot go back and turn logging on. + */ +internal object OnePlusLog { + + fun d(message: String) = onePlusLogWrite(OnePlusLogLevel.DEBUG, message, null) + + fun i(message: String) = onePlusLogWrite(OnePlusLogLevel.INFO, message, null) + + fun w(message: String) = onePlusLogWrite(OnePlusLogLevel.WARN, message, null) + + fun e(message: String) = onePlusLogWrite(OnePlusLogLevel.ERROR, message, null) + + fun e(message: String, cause: Throwable) = onePlusLogWrite(OnePlusLogLevel.ERROR, message, cause) +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogMarkers.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogMarkers.kt new file mode 100644 index 000000000000..4412f1d2cf4b --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusLogMarkers.kt @@ -0,0 +1,28 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * Logcat greppable markers for ONE+ native session. + * Prefer logging the constant as a substring so filters like `DEXCOM_ONEPLUS_SESSION` work. + */ +object OnePlusLogMarkers { + const val TAG = "DEXCOM_ONEPLUS" + + const val SESSION = "DEXCOM_ONEPLUS_SESSION" + const val WARMUP = "DEXCOM_ONEPLUS_WARMUP" + const val BG = "DEXCOM_ONEPLUS_BG" + const val ERROR = "DEXCOM_ONEPLUS_ERROR" + const val SCAN = "DEXCOM_ONEPLUS_SCAN" + const val RECONNECT = "DEXCOM_ONEPLUS_RECONNECT" + const val STUB = "ONEPLUS_DRIVER_STUB" + + /** + * Slot label logged as `MARKER: [slot] …` (after the colon, so existing `DEXCOM_ONEPLUS_*` + * filters keep matching). Without it a dual-sensor field trace cannot be attributed to the + * production or the staging driver — both emit the same markers from their own threads. + */ + const val SLOT_PRODUCTION = "prod" + + /** Slot label for a namespaced (non-production) driver — [namespace] is the store namespace. */ + fun slotOf(namespace: String?): String = + if (namespace.isNullOrBlank()) SLOT_PRODUCTION else namespace +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusPlatform.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusPlatform.kt new file mode 100644 index 000000000000..c2cd5ffa595f --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusPlatform.kt @@ -0,0 +1,44 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.session.OnePlusCpuLease + +/** + * Everything the driver needs from the phone it is running on. + * + * This used to be an Android `Context` handed to `OnePlusCgmDriver.setContext`. A `Context` is four + * different favours rolled into one - a private key-value file, an LE scanner, a GATT stack and a + * wake lock - and only the first of those means anything on a second platform. So the favours are + * named here instead, and each platform answers the four it can answer. + * + * The driver asks for these once, in [OnePlusCgmDriver.attach], and keeps the platform for as long + * as it lives: a session is rebuilt on every reconnect and needs a fresh GATT client each time. + * + * ⚠️ Nothing here may return something that pretends to work. A platform that cannot honour one of + * these says so - [cpuLease] returns a lease that hands back null, and a GATT client refuses the + * calls it cannot make. A CGM that quietly reports nothing is read by the dosing engine as "no + * glucose", which is not the same as a reading. + */ +interface OnePlusPlatform { + + /** + * The private key-value file named [fileName], for one sensor slot. + * + * @param fileName from `OnePlusSensorStore.prefsFileName`, which already carries the slot + * namespace. The platform only has to find or make a file of that name. + */ + fun sensorPrefs(fileName: String): OnePlusSensorPrefs + + /** The LE scanner for [slot], ranking what it hears against [hint]. */ + fun scanner(hint: OnePlusStoredSession?, slot: String): OnePlusBleScanner + + /** A fresh GATT client for one connection attempt, honouring the quirks in [profile]. */ + fun gattClient(profile: OemDeviceProfile): OnePlusGattClient + + /** Keeps the processor awake while [slot] connects and authenticates. */ + fun cpuLease(slot: String): OnePlusCpuLease +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleep.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleep.kt new file mode 100644 index 000000000000..db53a733a657 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusSleep.kt @@ -0,0 +1,14 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * Blocks the calling thread for [millis]. + * + * The driver's session loops are written as blocking cycles on their own thread - write a request, + * wait for the answer, settle, go again - so they need a blocking wait rather than a suspending + * one. `Thread.sleep` is JVM only, which is the only reason this exists. + * + * @return true when the whole wait was served, false when it was cut short. On Android that means + * the thread was interrupted, and the interrupt flag is put back so the caller can still see it. + * Callers use the false to stop what they were doing, so this must never pretend it slept. + */ +internal expect fun onePlusSleep(millis: Long): Boolean diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusWarmupState.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusWarmupState.kt new file mode 100644 index 000000000000..b3d419462e29 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusWarmupState.kt @@ -0,0 +1,39 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * Warm-up clock exposed to UI. Prefer protocol remainingMs when available. + * + * Helpers for remaining resolution live in `warmup.OnePlusWarmupClock` (pure, unit-tested). + */ +data class OnePlusWarmupState( + val phase: Phase, + val remainingMs: Long? = null, + val endsAtEpochMs: Long? = null, + val message: String? = null, + /** + * Whole minutes the session has been waiting for the sensor's advertisement while + * [Phase.RECONNECTING] (null outside that wait). Typed rather than parsed back out of + * [message], so the UI can tell "reconnecting, normal duty cycle" from "silent for 12 min". + */ + val advSilenceMinutes: Long? = null, + /** + * Another ONE+ transmitter is advertising while the stored MAC never does — the sensor was + * probably replaced, or started into the other slot. Surfaced so the user is told to re-run the + * sensor start instead of waiting forever on a MAC that will never answer. + */ + val staleMacSuspected: Boolean = false, +) { + enum class Phase { + IDLE, + PAIRING, + + /** GATT connect / service discovery in progress (first attempt). */ + CONNECTING, + + /** Transient failure — retry loop is actively re-establishing (NOT terminal). */ + RECONNECTING, + WARMING, + READY, + FAILED, + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusBluetoothUuids.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusBluetoothUuids.kt new file mode 100644 index 000000000000..dda841db448b --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusBluetoothUuids.kt @@ -0,0 +1,34 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +/** + * Dex family GATT UUIDs used by xDrip Direct / Ob1 path. + * + * They are kept as text, not as a platform UUID type. The text is the protocol, so it lives here + * and the platform turns it into its own type once - see `OnePlusGattUuids` on Android. + * + * Provenance: NightscoutFoundation/xDrip `BluetoothServices.java` + * at pin `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + * See `plugins/dexcom_oneplus/NOTICE`. + * + * Historical file comment upstream: "Created by joeginley on 3/16/16." + */ +object OnePlusBluetoothUuids { + + const val DeviceInfo: String = "0000180A-0000-1000-8000-00805F9B34FB" + const val Advertisement: String = "0000FEBC-0000-1000-8000-00805F9B34FB" + const val CgmService: String = "F8083532-849E-531C-C594-30F1F86A4EA5" + const val ServiceB: String = "F8084532-849E-531C-C594-30F1F86A4EA5" + + const val ManufacturerNameString: String = "00002A29-0000-1000-8000-00805F9B34FB" + + const val Communication: String = "F8083533-849E-531C-C594-30F1F86A4EA5" + const val Control: String = "F8083534-849E-531C-C594-30F1F86A4EA5" + const val Authentication: String = "F8083535-849E-531C-C594-30F1F86A4EA5" + const val ProbablyBackfill: String = "F8083536-849E-531C-C594-30F1F86A4EA5" + const val ExtraData: String = "F8083538-849E-531C-C594-30F1F86A4EA5" + + const val CharacteristicE: String = "F8084533-849E-531C-C594-30F1F86A4EA5" + const val CharacteristicF: String = "F8084534-849E-531C-C594-30F1F86A4EA5" + + const val CharacteristicUpdateNotification: String = "00002902-0000-1000-8000-00805F9B34FB" +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClient.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClient.kt new file mode 100644 index 000000000000..4f99e7e7022e --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusGattClient.kt @@ -0,0 +1,96 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +/** + * GATT connect / discovery / notify routing. + * + * ⚠️ ASYNC IMPACT: `BluetoothGattCallback` arrives on the binder thread. + * Sequential work (MTU, discover, CCCD, write) must run on a single bleExecutor. + * Platform impl must serialize GATT ops (one outstanding write/descriptor) — Android 13+ + * returns status 201 (`ERROR_GATT_WRITE_REQUEST_BUSY`) otherwise. + * [awaitNotify] / [awaitControlNotify] / [awaitBackfillNotify] block the caller — + * Auth/ExtraData, Control, and ProbablyBackfill use **separate** queues. + * [disconnect] must unblock all three via an identity disconnect sentinel (not any empty + * byte array). Do not block that executor with network or dosing work. + */ +interface OnePlusGattClient { + /** + * Connect + discover + Auth/Extra CCCD until ready. + * @param autoConnect Ob1 CONNECT path — true after hard-connect failures on flaky stacks + */ + fun connect(deviceAddress: String, autoConnect: Boolean = false) + fun disconnect() + fun isConnected(): Boolean + + fun writeAuthentication(payload: ByteArray?) + fun writeExtraData(payload: ByteArray?) + fun writeControl(payload: ByteArray?) + + /** + * Enable Control CCCD for the EGV path. + * Prefer **notifications** (Juggluco Dex path); fall back to indications (Ob1) if the write fails. + */ + fun enableControlNotifications() + + /** + * Force Control **indications** (Ob1). Used when NOTIFY CCCD succeeded but no Control + * traffic arrives (silent firmware/stack mismatch). + */ + fun enableControlIndications() + + /** + * Enable notifications on ProbablyBackfill (Ob1 `setupNotification(ProbablyBackfill)`). + */ + fun enableBackfillNotifications() + + /** True when the remote device is Android-bonded (`BluetoothDevice.BOND_BONDED`). */ + fun isBonded(): Boolean + + /** + * Request Android bonding (system pairing UI may appear). No-op if already bonded. + * Registers a bond-state receiver; pair with [awaitBondComplete]. + * @return false if createBond could not be started + */ + fun createBond(): Boolean + + /** + * Drop the Android OS bond via hidden [BluetoothDevice.removeBond] (Juggluco-style). + * Used when KEKS AuthStatus rejects (`authenticated != 1`) while the phone is still bonded — + * otherwise the next reconnect short-auths / stalls with sensor `bonded=1`. + * + * ⚠️ ASYNC IMPACT: may drop the GATT link; caller should treat as reconnect trigger. + * @return true if already unbonded or removeBond returned true + */ + fun removeBond(): Boolean + + /** + * Block until [BluetoothDevice.BOND_BONDED] (BroadcastReceiver), Juggluco-style: + * tear down Auth/Extra CCCDs while [BluetoothDevice.BOND_BONDING], restore after bonded. + * + * ⚠️ ASYNC IMPACT: blocks bleExecutor; receiver runs on main/binder and must not + * serialize against a concurrent GATT write from this thread. + */ + fun awaitBondComplete(timeoutMs: Long): Boolean + + /** + * Block until next Auth or ExtraData notification (KEKS path), with source tag. + * Prefer this over [awaitNotify] so KEKS can route Ob1-style. + */ + fun awaitKeksNotify(timeoutMs: Long): OnePlusKeksNotify? + + /** + * Block until next Auth or ExtraData notification (KEKS path). + * Payload only — prefer [awaitKeksNotify] for handshake. + */ + fun awaitNotify(timeoutMs: Long): ByteArray? + + /** + * Block until next Control characteristic indication/notification (EGV path). + * Separate from [awaitKeksNotify] so KEKS and EGV do not cross-consume packets. + */ + fun awaitControlNotify(timeoutMs: Long): ByteArray? + + /** + * Block until next ProbablyBackfill notification (history stream). + */ + fun awaitBackfillNotify(timeoutMs: Long): ByteArray? +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusKeksNotify.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusKeksNotify.kt new file mode 100644 index 000000000000..5fbf7b1da452 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/gatt/OnePlusKeksNotify.kt @@ -0,0 +1,25 @@ +package app.aaps.plugins.dexcomoneplus.gatt + +/** + * Tagged Auth / ExtraData notify for the KEKS handshake. + * + * Ob1 routes by characteristic UUID: Auth → `receivedResponse`, ExtraData → `receivedData`. + * Mixing both into one byte stream corrupts the Round1/2/3 160-byte accumulator. + */ +enum class OnePlusKeksNotifySource { + AUTHENTICATION, + EXTRA_DATA, +} + +data class OnePlusKeksNotify( + val source: OnePlusKeksNotifySource, + val payload: ByteArray, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is OnePlusKeksNotify) return false + return source == other.source && payload.contentEquals(other.payload) + } + + override fun hashCode(): Int = 31 * source.hashCode() + payload.contentHashCode() +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt new file mode 100644 index 000000000000..079b8771e3ec --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt @@ -0,0 +1,137 @@ +package app.aaps.plugins.dexcomoneplus.identity + +/** + * Juggluco-aligned ADV name / candidate matching for ONE+ / G7 family. + * + * Juggluco `isG7`: local name starts with `DX` + (`CM`|`02`|`01`). + * Once a device name is known from a successful session, prefer exact match. + * + * Do **not** treat marketing names like `Dexcom65` / `DexcomONE` as ONE+ candidates — + * field logs showed pre-connect latching on a G6-style `Dexcom65` while the real + * transmitter was `DX02aS`. + * + * What this file can and cannot do: + * - The 4-digit code is the KEKS password. It is used at Connect and nowhere else. It is **not** + * part of the advertisement, so nothing here can pick one transmitter out of several by code. + * - The serial may raise a score when it happens to appear in the ADV name. It must never filter: + * the ADV encoding is opaque and a real sensor often advertises as a short `DX02*` name. + */ +object OnePlusAdvCandidate { + + fun isG7FamilyName(name: String?): Boolean { + if (name.isNullOrBlank()) return false + val n = name.trim() + if (n.length < 4) return false + if (!n.startsWith("DX", ignoreCase = true)) return false + val rest = n.substring(2, 4) + return rest.equals("CM", ignoreCase = true) || + rest.equals("02", ignoreCase = true) || + rest.equals("01", ignoreCase = true) + } + + /** + * Open-scan name filter: G7/ONE+ family only (`DX02` / `DX01` / `DXCM`). + * Intentionally excludes `Dex*` marketing names (G6 / phone companions). + */ + fun nameMatchesSoft(name: String?): Boolean = isG7FamilyName(name) + + /** + * Whether this ADV should be offered / preferred for [session]. + * - Exact stored ADV name wins (reconnect sticky). + * - Stored MAC wins even if name is missing/odd. + * - Else G7-family name only. + */ + fun isCandidate( + name: String?, + address: String?, + session: OnePlusStoredSession?, + ): Boolean { + val storedName = session?.lastDeviceName + if (!storedName.isNullOrBlank() && name != null && name.equals(storedName, ignoreCase = true)) { + return true + } + val storedMac = session?.lastMac + if (!storedMac.isNullOrBlank() && address != null && + address.equals(storedMac, ignoreCase = true) + ) { + return true + } + if (!isG7FamilyName(name)) return false + val serial = session?.identity?.serial + if (!serial.isNullOrBlank() && !name.isNullOrBlank()) { + // Prefer ADV that embeds serial characters when present; do not hard-reject + // when serial encoding in ADV is opaque (G7 often uses short DX02* names). + if (name.contains(serial, ignoreCase = true)) return true + } + return true + } + + /** + * Stored session to rank **this** scan with. + * + * The start screen used to rank every scan with whatever the slot store held. When the user was + * starting a new sensor, that pushed the sensor being replaced to the top of the list and the + * code on screen was ignored. The code cannot name a transmitter, but it can say "this is not + * the stored one any more", and that is enough to stop the old MAC and the old ADV name from + * winning. + * + * @param stored what the slot store holds, or null on a first pairing. + * @param onScreen identity read from the code or QR the user has in front of them. + * @return [stored] when both describe the same sensor (a reconnect or a repair), otherwise a + * session carrying the on-screen identity only: no MAC and no name, so the serial hint still + * applies as a boost while the sticky boost of the old transmitter is gone. + */ + fun scanHintFor( + stored: OnePlusStoredSession?, + onScreen: OnePlusSensorIdentity?, + ): OnePlusStoredSession? { + if (onScreen == null) return stored + val storedIdentity = stored?.identity ?: return OnePlusStoredSession(identity = onScreen) + return if (isSameSensor(storedIdentity, onScreen)) stored else OnePlusStoredSession(identity = onScreen) + } + + /** + * Whether two identities describe the same sensor. + * + * The serial decides whenever both sides carry one: it is the only part that is unique. The + * 4-digit code is not — two sensors may carry the same four digits — so it only decides when a + * serial is missing. + */ + private fun isSameSensor(stored: OnePlusSensorIdentity, onScreen: OnePlusSensorIdentity): Boolean { + val storedSerial = stored.serial?.trim()?.takeIf { it.isNotEmpty() } + val screenSerial = onScreen.serial?.trim()?.takeIf { it.isNotEmpty() } + if (storedSerial != null && screenSerial != null) return storedSerial.equals(screenSerial, ignoreCase = true) + return stored.pin.trim() == onScreen.pin.trim() + } + + /** + * Score used to sort the scan list. Higher is shown first. + * + * Every part is a boost, never a filter — see the note on this object. Feed it the session from + * [scanHintFor], not the raw store, or a new sensor is ranked with the old sensor's fingerprint. + */ + fun rankScore( + name: String?, + address: String?, + rssi: Int, + session: OnePlusStoredSession?, + ): Int { + var score = rssi + if (!session?.lastDeviceName.isNullOrBlank() && + name.equals(session?.lastDeviceName, ignoreCase = true) + ) { + score += 10_000 + } + if (!session?.lastMac.isNullOrBlank() && + address.equals(session?.lastMac, ignoreCase = true) + ) { + score += 5_000 + } + val serial = session?.identity?.serial + if (!serial.isNullOrBlank() && name?.contains(serial, ignoreCase = true) == true) { + score += 1_000 + } + if (isG7FamilyName(name)) score += 100 + return score + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParser.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParser.kt new file mode 100644 index 000000000000..fa327284b29d --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusGs1ApplicatorParser.kt @@ -0,0 +1,104 @@ +package app.aaps.plugins.dexcomoneplus.identity + +/** + * Parses Dexcom ONE+ / G7 applicator Data Matrix (GS1) payloads. + * + * Mirrors Juggluco [BarCode] AIs used for Dexcom: + * - `01` GTIN + * - `21` Serial + * - `240` PIN / additional product id (4-digit KEKS password, often trailing) + * + * Also accepts a bare 4-digit PIN (manual entry without QR). + */ +object OnePlusGs1ApplicatorParser { + + private const val GS: Char = 0x1D.toChar() + + fun parse(raw: String): OnePlusSensorIdentity? { + val trimmed = raw.trim() + if (trimmed.isEmpty()) return null + + val digitsOnly = trimmed.filter { it.isDigit() } + if (digitsOnly.length == 4 && trimmed.all { it.isDigit() || it.isWhitespace() }) { + return OnePlusSensorIdentity(pin = digitsOnly) + } + + val normalized = normalizeGs(trimmed) + val fields = parseFields(normalized) ?: return null + val pinRaw = fields["240"] ?: return null + val pin = extractPin(pinRaw) ?: return null + return OnePlusSensorIdentity( + pin = pin, + serial = fields["21"]?.takeIf { it.isNotBlank() }, + gtin = fields["01"]?.takeIf { it.isNotBlank() }, + rawGs1 = trimmed, + ) + } + + /** Extract trailing 4-digit KEKS PIN from AI 240 (Juggluco `dexcomEnd` style). */ + fun extractPin(ai240: String): String? { + val digits = ai240.filter { it.isDigit() } + if (digits.length >= 4) return digits.takeLast(4) + return null + } + + internal fun normalizeGs(raw: String): String { + val withGs = raw + .replace("^]", GS.toString()) + .replace("\\u001d", GS.toString(), ignoreCase = true) + return withGs.trimStart(GS).trim() + } + + private fun parseFields(s: String): Map? { + if (s.isEmpty()) return null + val out = linkedMapOf() + var pos = 0 + while (pos < s.length) { + if (s[pos] == GS) { + pos++ + continue + } + val ai = readAi(s, pos) ?: return if (out.isEmpty()) null else out + pos = ai.nextPos + val value = readValue(s, pos, ai.fixedLen) + pos = value.nextPos + out[ai.code] = value.text + } + return out.ifEmpty { null } + } + + private data class AiRead(val code: String, val fixedLen: Int?, val nextPos: Int) + private data class ValueRead(val text: String, val nextPos: Int) + + private fun readAi(s: String, pos: Int): AiRead? { + if (pos >= s.length || !s[pos].isDigit()) return null + // Prefer longer AIs first (240 before 24, 01 before 0…). + for (len in intArrayOf(4, 3, 2)) { + if (pos + len > s.length) continue + val code = s.substring(pos, pos + len) + val fixed = FIXED_AI[code] + if (fixed != null || VARIABLE_AI.contains(code)) { + return AiRead(code, fixed, pos + len) + } + } + return null + } + + private fun readValue(s: String, pos: Int, fixedLen: Int?): ValueRead { + if (fixedLen != null) { + val end = (pos + fixedLen).coerceAtMost(s.length) + return ValueRead(s.substring(pos, end), end) + } + var end = pos + while (end < s.length && s[end] != GS) end++ + return ValueRead(s.substring(pos, end), if (end < s.length && s[end] == GS) end + 1 else end) + } + + private val FIXED_AI = mapOf( + "01" to 14, + "11" to 6, + "17" to 6, + ) + + private val VARIABLE_AI = setOf("10", "21", "240", "250") +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorIdentity.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorIdentity.kt new file mode 100644 index 000000000000..e490a8b5f4d9 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorIdentity.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.dexcomoneplus.identity + +/** + * Dexcom ONE+ / G7 applicator identity (Juggluco GS1 Data Matrix fields). + * + * [pin] is the 4-digit KEKS password. [serial] comes from GS1 AI 21 when available + * and is used to sticky-match BLE ADV names across reconnects. + */ +data class OnePlusSensorIdentity( + val pin: String, + val serial: String? = null, + val gtin: String? = null, + /** Raw GS1 / Data Matrix payload when parsed from applicator QR. */ + val rawGs1: String? = null, +) + +data class OnePlusStoredSession( + val identity: OnePlusSensorIdentity, + val lastMac: String? = null, + /** Last ADV local name that successfully authenticated (Juggluco DexDeviceName). */ + val lastDeviceName: String? = null, + /** 16-byte KEKS shared key for reconnect short-auth (libkeks persistence channel 2). */ + val sharedKey: ByteArray? = null, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is OnePlusStoredSession) return false + return identity == other.identity && + lastMac == other.lastMac && + lastDeviceName == other.lastDeviceName && + sharedKey.contentEquals(other.sharedKey) + } + + override fun hashCode(): Int { + var result = identity.hashCode() + result = 31 * result + (lastMac?.hashCode() ?: 0) + result = 31 * result + (lastDeviceName?.hashCode() ?: 0) + result = 31 * result + (sharedKey?.contentHashCode() ?: 0) + return result + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefs.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefs.kt new file mode 100644 index 000000000000..77721ec4829c --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorPrefs.kt @@ -0,0 +1,50 @@ +package app.aaps.plugins.dexcomoneplus.identity + +/** + * The small private key-value file one sensor slot keeps for itself. + * + * It is deliberately not the application's own settings: the pairing code and the KEKS key stay + * local and never leave in an exported preference file. On Android it is a private + * `SharedPreferences` file, which is what this shape is drawn from; another platform may store it + * however it likes as long as a value written is the same value read back. + * + * Writing a null string removes the key, exactly as `SharedPreferences` does, and + * [OnePlusSensorStore] relies on that when a sensor has no serial. + */ +interface OnePlusSensorPrefs { + + fun getString(key: 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 + + /** + * Applies every change made in [block] together. + * + * One call, one write: several keys that belong to the same decision must not be able to land + * half way, which has already cost a sensor its correct age once. + */ + fun edit(block: Editor.() -> Unit) + + /** Collects the changes of one [edit] call. */ + interface Editor { + + /** A null [value] removes the key. */ + fun putString(key: String, value: String?) + + fun putLong(key: String, value: Long) + + fun putInt(key: String, value: Int) + + fun putBoolean(key: String, value: Boolean) + + fun remove(key: String) + + fun clear() + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt new file mode 100644 index 000000000000..a845f130728a --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt @@ -0,0 +1,300 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * Persist ONE+ identity + last good MAC + KEKS shared key for Juggluco-style reconnect. + * + * Uses the slot's own private key-value file ([OnePlusSensorPrefs]), never the exportable AAPS + * preferences — PIN / key stay local. + */ +@OptIn(ExperimentalEncodingApi::class) +class OnePlusSensorStore(private val prefs: OnePlusSensorPrefs) { + + fun load(): OnePlusStoredSession? { + val pin = prefs.getString(KEY_PIN)?.takeIf { it.length == 4 } ?: return null + val serial = prefs.getString(KEY_SERIAL)?.takeIf { it.isNotBlank() } + val gtin = prefs.getString(KEY_GTIN)?.takeIf { it.isNotBlank() } + val raw = prefs.getString(KEY_RAW_GS1)?.takeIf { it.isNotBlank() } + val mac = prefs.getString(KEY_MAC)?.takeIf { it.isNotBlank() } + val deviceName = prefs.getString(KEY_DEVICE_NAME)?.takeIf { it.isNotBlank() } + val keyB64 = prefs.getString(KEY_SHARED) + val shared = keyB64?.let { + try { + Base64.decode(it) + } catch (_: Throwable) { + null + } + }?.takeIf { it.size == 16 } + return OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = pin, serial = serial, gtin = gtin, rawGs1 = raw), + lastMac = mac, + lastDeviceName = deviceName, + sharedKey = shared, + ) + } + + fun saveIdentity(identity: OnePlusSensorIdentity) { + // A new sensor restarts its EGV sequence counter from a low value, so the persisted ingest + // high-water mark (last sequence/timestamp) MUST be reset — otherwise the new sensor's early + // readings would be wrongly rejected as "already seen". Reset only on an actual serial change. + val serialChanged = identity.serial != null && identity.serial != prefs.getString(KEY_SERIAL) + prefs.edit { + putString(KEY_PIN, identity.pin) + putString(KEY_SERIAL, identity.serial) + putString(KEY_GTIN, identity.gtin) + putString(KEY_RAW_GS1, identity.rawGs1) + } + // The session start is NOT cleared here. It is owned solely by [startSessionForSensor], which + // decides from the MAC whether this is the same sensor. Clearing it here made the write order + // matter: the staging start recorded the session start first, then saveIdentity wiped it + // milliseconds later, so the soak clock restarted from the first reading instead of from the + // moment the sensor was applied. + if (serialChanged) clearLastIngest() + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: sensor identity saved serial=${maskSerial(identity.serial)} serialChanged=$serialChanged", + ) + } + + /** + * Persist the ingest high-water mark so a process restart / app update cannot re-insert already + * stored readings (which the loop rejects as duplicates). [sequence] is the monotonic per-sensor + * EGV counter; [timestampMs] backs the near-duplicate time window. + */ + fun saveLastIngest(sequence: Long?, timestampMs: Long) { + prefs.edit { + if (sequence != null) putLong(KEY_LAST_SEQ, sequence) + putLong(KEY_LAST_TS, timestampMs) + } + } + + /** Last ingested EGV sequence, or -1 when none recorded (accept everything). */ + fun loadLastIngestSequence(): Long = prefs.getLong(KEY_LAST_SEQ, -1L) + + /** Last ingested reading timestamp (ms), or 0 when none recorded. */ + fun loadLastIngestTimestamp(): Long = prefs.getLong(KEY_LAST_TS, 0L) + + private fun clearLastIngest() { + prefs.edit { + remove(KEY_LAST_SEQ) + remove(KEY_LAST_TS) + } + } + + /** + * Persist the slot's collect-only progress so it survives a process restart. Used by the STAGING + * slot: without it, `stagingPresent` / `stagingValidEgvCount` are in-memory only, so any restart + * reset a warming pre-soak sensor to ABSENT — it could then neither resume, leave warm-up, nor be + * promoted, even though this store still held its identity, MAC and KEKS key. + */ + fun saveSlotProgress(present: Boolean, validEgvCount: Int) { + prefs.edit { + putBoolean(KEY_SLOT_PRESENT, present) + putInt(KEY_SLOT_EGV_COUNT, validEgvCount.coerceAtLeast(0)) + } + } + + /** A sensor was started in this slot and not cancelled/promoted. */ + fun loadSlotPresent(): Boolean = prefs.getBoolean(KEY_SLOT_PRESENT, false) + + /** Valid EGVs collected in this slot so far (promotion gate). */ + fun loadSlotValidEgvCount(): Int = prefs.getInt(KEY_SLOT_EGV_COUNT, 0) + + /** + * Latch: this slot's sensor has finished warm-up at least once. + * + * Warm-up completion is an event, not a state that can be read back from the live connection + * phase — a healthy sensor keeps re-connecting every radio cycle for its whole life. Persisted so + * a restart does not send a settled sensor back to "warming up". + */ + fun saveSlotWarmupDone(done: Boolean) { + prefs.edit { putBoolean(KEY_SLOT_WARMUP_DONE, done) } + } + + /** True once this slot's sensor has left warm-up (see [saveSlotWarmupDone]). */ + fun loadSlotWarmupDone(): Boolean = prefs.getBoolean(KEY_SLOT_WARMUP_DONE, false) + + /** Record the sensor session start (epoch ms) once — used to derive early/end-of-life age. */ + fun saveSessionStartIfAbsent(epochMs: Long) { + if (!prefs.contains(KEY_SESSION_START)) prefs.edit { putLong(KEY_SESSION_START, epochMs) } + } + + /** + * Anchor the session start on the explicit sensor start the user just ran, so the sensor age can + * be known from that moment instead of only from the first reading (~30 min later, after warm-up). + * + * Re-connecting the **same** sensor keeps the stored start — re-pairing a running sensor must not + * rejuvenate its age. Another sensor restarts the clock. The owning MAC is kept in its own key, + * so this does not depend on the order in which [saveLastMac] / [saveIdentity] are called + * around it; see [startsNewSession] for the decision itself. + * + * @param previousMac MAC stored for the running session **before** this start. Only used for + * sessions anchored by [saveSessionStartIfAbsent] before the owner key existed. + * @return true when a new session start was written (the caller may then log a sensor change). + */ + fun startSessionForSensor(deviceAddress: String, epochMs: Long, previousMac: String?): Boolean { + if (deviceAddress.isBlank() || epochMs <= 0L) return false + val address = deviceAddress.uppercase() + val isNewSession = startsNewSession( + storedStartMs = prefs.getLong(KEY_SESSION_START, 0L), + storedOwnerMac = prefs.getString(KEY_SESSION_START_MAC), + previousMac = previousMac, + deviceAddress = address, + ) + if (!isNewSession) { + // Same sensor: keep its age, and adopt the owner key so a session anchored before that + // key existed is recognised directly next time. + prefs.edit { putString(KEY_SESSION_START_MAC, address) } + return false + } + prefs.edit { + putLong(KEY_SESSION_START, epochMs) + putString(KEY_SESSION_START_MAC, address) + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: sensor session start recorded startMs=$epochMs", + ) + return true + } + + /** Sensor session start (epoch ms), or 0 when unknown. */ + fun loadSessionStart(): Long = prefs.getLong(KEY_SESSION_START, 0L) + + /** + * Move the session start of the sensor already stored here — the user correcting the real + * insertion time by hand. + * + * The other writers set this clock once and never touch it again on purpose ([saveSessionStartIfAbsent], + * [startSessionForSensor]), so nothing else in the app could change a sensor age that was stamped + * at pairing time instead of at insertion time. This is the one deliberate exception, and the + * owner MAC is left as it is: the sensor has not changed, only the moment it went in. + */ + fun overwriteSessionStart(epochMs: Long) { + if (epochMs <= 0L) return + prefs.edit { putLong(KEY_SESSION_START, epochMs) } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: sensor session start corrected by user startMs=$epochMs", + ) + } + + fun saveLastMac(address: String) { + if (address.isBlank()) return + prefs.edit { putString(KEY_MAC, address.uppercase()) } + } + + fun saveLastDeviceName(name: String?) { + if (name.isNullOrBlank()) return + prefs.edit { putString(KEY_DEVICE_NAME, name) } + } + + fun saveSharedKey(key: ByteArray) { + if (key.size != 16) return + prefs.edit { putString(KEY_SHARED, Base64.encode(key)) } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS shared key persisted (16b)", + ) + } + + fun clearSharedKey() { + prefs.edit { remove(KEY_SHARED) } + } + + fun clearAll() { + prefs.edit { clear() } + } + + /** + * Adopt another sensor's stored session into this store — used on staging→production promotion so + * the production driver durably resumes the promoted sensor after a restart. Copies identity / MAC + * / device name / KEKS key + its [sessionStartMs], and clears the ingest high-water mark (the + * promoted sensor has a fresh EGV sequence space, so no old floor must survive). + */ + fun adopt(session: OnePlusStoredSession, sessionStartMs: Long) { + prefs.edit { + putString(KEY_PIN, session.identity.pin) + putString(KEY_SERIAL, session.identity.serial) + putString(KEY_GTIN, session.identity.gtin) + putString(KEY_RAW_GS1, session.identity.rawGs1) + remove(KEY_LAST_SEQ) + remove(KEY_LAST_TS) + session.lastMac?.let { putString(KEY_MAC, it) } + session.lastDeviceName?.let { putString(KEY_DEVICE_NAME, it) } + session.sharedKey?.let { putString(KEY_SHARED, Base64.encode(it)) } + if (sessionStartMs > 0L) { + putLong(KEY_SESSION_START, sessionStartMs) + // Keep the start owned by the promoted sensor's MAC, so re-connecting it later is + // seen as the same sensor and does not restart the age clock (startSessionForSensor). + session.lastMac?.let { putString(KEY_SESSION_START_MAC, it.uppercase()) } + } + } + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: adopted promoted sensor serial=${maskSerial(session.identity.serial)}") + } + + companion object { + + /** + * The sensor serial for a log line: only its last three characters, enough to tell two + * sensors apart in a log without writing the whole serial into it. + */ + fun maskSerial(serial: String?): String = + when { + serial.isNullOrBlank() -> "-" + serial.length <= 3 -> "***" + else -> "***" + serial.takeLast(3) + } + + /** + * Pure decision behind [startSessionForSensor]: does an explicit start of [deviceAddress] + * begin a NEW sensor session? + * + * @param storedStartMs stored session start, 0 when none + * @param storedOwnerMac MAC owning the stored start; null for a session anchored on the first + * reading before that key existed, which then falls back to [previousMac] instead of being + * read as another sensor (that would reset the age of a sensor that never changed) + * @param previousMac last stored MAC of the running session, taken before this start + */ + fun startsNewSession( + storedStartMs: Long, + storedOwnerMac: String?, + previousMac: String?, + deviceAddress: String, + ): Boolean { + if (storedStartMs <= 0L) return true + val owner = storedOwnerMac?.takeIf { it.isNotBlank() } + ?: previousMac?.takeIf { it.isNotBlank() } + ?: return true + return !owner.equals(deviceAddress, ignoreCase = true) + } + + /** + * Name of the slot's own file. + * + * Per-slot isolation: the STAGING sensor must not share identity / MAC / KEKS key / ingest + * markers with PRODUCTION. A null or blank [namespace] gives the original single-sensor + * file, so an install that predates the staging slot keeps its stored sensor. + */ + fun prefsFileName(namespace: String?): String = + if (namespace.isNullOrBlank()) PREFS_NAME else "${PREFS_NAME}_$namespace" + + private const val PREFS_NAME = "dexcom_oneplus_sensor" + private const val KEY_PIN = "pin" + private const val KEY_SERIAL = "serial" + private const val KEY_GTIN = "gtin" + private const val KEY_RAW_GS1 = "raw_gs1" + private const val KEY_MAC = "last_mac" + private const val KEY_DEVICE_NAME = "last_device_name" + private const val KEY_SHARED = "shared_key_b64" + private const val KEY_LAST_SEQ = "last_ingest_seq" + private const val KEY_LAST_TS = "last_ingest_ts" + private const val KEY_SESSION_START = "session_start_ms" + + /** MAC that owns [KEY_SESSION_START] — tells "same sensor re-connected" from "new sensor". */ + private const val KEY_SESSION_START_MAC = "session_start_mac" + private const val KEY_SLOT_PRESENT = "slot_present" + private const val KEY_SLOT_EGV_COUNT = "slot_valid_egv_count" + private const val KEY_SLOT_WARMUP_DONE = "slot_warmup_done" + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistry.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistry.kt new file mode 100644 index 000000000000..3bdb3c99847f --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/DeviceProfileRegistry.kt @@ -0,0 +1,162 @@ +package app.aaps.plugins.dexcomoneplus.oem + +import app.aaps.plugins.dexcomoneplus.OnePlusLog + +/** + * Resolves OEM BLE defaults from [onePlusDeviceManufacturer] / [onePlusDeviceModel]. + */ +object DeviceProfileRegistry { + + const val LOG_MARKER = "DEXCOM_ONEPLUS_OEM_PROFILE" + + /** Pixel 6/7/8 family — Juggluco never requestMtu before discover on Dex path. */ + val PixelDefault: OemDeviceProfile = OemDeviceProfile( + id = OemProfileId.PIXEL, + connectTimeoutMs = 30_000L, + connectRetryCount = 3, + connectRetryDelayMs = 2_000L, + preferredMtu = 517, + useForegroundService = true, + aggressiveReconnect = false, + postCloseSettleMs = 2_000L, + scanHandoffMs = 500L, + preConnectScanMs = 2_000L, + requestMtuOnConnect = false, + useGattRefresh = true, + autoConnectFromAttempt = 2, + postDiscoverDelayMs = 0L, + ) + + /** + * Samsung S22–S25 — patient connect / reconnect (status 147 / 133 common). + * Field logs: blind autoConnect=false without fresh ADV → 147; success needed ADV + autoConnect. + */ + val SamsungDefault: OemDeviceProfile = OemDeviceProfile( + id = OemProfileId.SAMSUNG, + connectTimeoutMs = 45_000L, + connectRetryCount = 5, + connectRetryDelayMs = 10_000L, + preferredMtu = 517, + useForegroundService = true, + aggressiveReconnect = true, + postCloseSettleMs = 6_000L, + scanHandoffMs = 500L, + preConnectScanMs = 8_000L, + requestMtuOnConnect = false, + useGattRefresh = true, + autoConnectFromAttempt = 0, + postDiscoverDelayMs = 1_000L, + requireAdvBeforeConnect = true, + ) + + /** + * Motorola — same failure as Samsung, and it used to land on [GenericFallback]. + * + * The fallback connects on attempt 0 even when the pre-connect scan hears nothing + * (`requireAdvBeforeConnect` defaults to false) and only reaches for `autoConnect` from the third + * attempt. That is the exact combination the Samsung profile exists to avoid: a blind hard + * connect without a fresh advertisement fails, and the retry ladder then costs minutes. So this + * profile takes the two settings that fixed Samsung — wait for the ADV, and let the platform + * hold the connection with `autoConnect` from the first attempt — with a scan window long enough + * to actually hear a sensor that advertises on its own duty cycle. + * + * MTU stays at the safe 185: there is no field measurement on this stack yet, and + * [OemDeviceProfile.requestMtuOnConnect] is false anyway. + */ + val MotorolaDefault: OemDeviceProfile = OemDeviceProfile( + id = OemProfileId.MOTOROLA, + connectTimeoutMs = 45_000L, + connectRetryCount = 5, + connectRetryDelayMs = 8_000L, + preferredMtu = 185, + useForegroundService = true, + aggressiveReconnect = true, + postCloseSettleMs = 4_000L, + scanHandoffMs = 500L, + preConnectScanMs = 8_000L, + requestMtuOnConnect = false, + useGattRefresh = true, + autoConnectFromAttempt = 0, + postDiscoverDelayMs = 1_000L, + requireAdvBeforeConnect = true, + ) + + /** + * Unknown OEM — conservative everywhere, including the advertisement gate. + * + * It used to be conservative on timeouts only: `requireAdvBeforeConnect` was left at its false + * default and `autoConnectFromAttempt` at 2, so an unknown phone connected blind on the first two + * attempts after a 3 s scan. That is the combination the Samsung profile exists to avoid, and two + * independent field logs landed on it — a Motorola and a CUBOT KING KONG MINI 3 — because this is + * where every phone that is not a Pixel or a Samsung ends up. Being the default, it has to be the + * safest of the three, not the boldest. + */ + val GenericFallback: OemDeviceProfile = OemDeviceProfile( + id = OemProfileId.GENERIC_FALLBACK, + connectTimeoutMs = 60_000L, + connectRetryCount = 5, + connectRetryDelayMs = 8_000L, + preferredMtu = 185, + useForegroundService = true, + aggressiveReconnect = true, + postCloseSettleMs = 4_000L, + scanHandoffMs = 500L, + preConnectScanMs = 8_000L, + requestMtuOnConnect = false, + useGattRefresh = true, + autoConnectFromAttempt = 0, + postDiscoverDelayMs = 1_000L, + requireAdvBeforeConnect = true, + ) + + fun byId(id: OemProfileId): OemDeviceProfile = when (id) { + OemProfileId.PIXEL -> PixelDefault + OemProfileId.SAMSUNG -> SamsungDefault + OemProfileId.MOTOROLA -> MotorolaDefault + OemProfileId.GENERIC_FALLBACK -> GenericFallback + } + + /** + * Picks a profile for the running device (or [override]). + * Always logs [LOG_MARKER] for logcat / QA grepping. + */ + fun resolve( + manufacturer: String = onePlusDeviceManufacturer(), + model: String = onePlusDeviceModel(), + override: OemProfileId? = null, + ): OemDeviceProfile { + val profile = when { + override != null -> byId(override) + isPixel(manufacturer) -> PixelDefault + isSamsung(manufacturer) -> SamsungDefault + isMotorola(manufacturer) -> MotorolaDefault + else -> GenericFallback + } + OnePlusLog.i( + "$LOG_MARKER id=${profile.id} manufacturer=$manufacturer model=$model " + + "override=$override connectTimeoutMs=${profile.connectTimeoutMs} " + + "retry=${profile.connectRetryCount} mtu=${profile.preferredMtu} " + + "fgsFlag=${profile.useForegroundService} aggressiveReconnect=${profile.aggressiveReconnect} " + + "settleMs=${profile.postCloseSettleMs} preScanMs=${profile.preConnectScanMs} " + + "mtuOnConnect=${profile.requestMtuOnConnect} autoConnectFrom=${profile.autoConnectFromAttempt} " + + "requireAdv=${profile.requireAdvBeforeConnect}", + ) + return profile + } + + private fun isPixel(manufacturer: String): Boolean { + val m = manufacturer.lowercase() + return m.contains("google") + } + + private fun isSamsung(manufacturer: String): Boolean { + val m = manufacturer.lowercase() + return m.contains("samsung") + } + + /** The reported manufacturer stays "motorola" on these phones, whoever owns the brand. */ + private fun isMotorola(manufacturer: String): Boolean { + val m = manufacturer.lowercase() + return m.contains("motorola") + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OemDeviceProfile.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OemDeviceProfile.kt new file mode 100644 index 000000000000..7e6aec8e05f8 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OemDeviceProfile.kt @@ -0,0 +1,73 @@ +package app.aaps.plugins.dexcomoneplus.oem + +/** + * BLE/runtime knobs for a phone OEM family (Q9 v1). + * Per-OEM BLE defaults; do not hardcode GATT here. + */ +data class OemDeviceProfile( + val id: OemProfileId, + /** GATT connect attempt timeout. Values above ~30 s only bind when autoConnect=true; + * Android's hard connect (autoConnect=false) gives up around 30 s. */ + val connectTimeoutMs: Long, + /** Max connect attempts before surfacing failure. */ + val connectRetryCount: Int, + /** Delay between connect retries. */ + val connectRetryDelayMs: Long, + /** Preferred ATT MTU request (OS may negotiate lower). */ + val preferredMtu: Int, + /** When true, `DexcomOnePlusSessionService` runs as a connectedDevice foreground service. */ + val useForegroundService: Boolean, + /** Faster / denser reconnect backoff when true. */ + val aggressiveReconnect: Boolean, + /** + * Sleep after GATT [android.bluetooth.BluetoothGatt.close] before next connectGatt. + * Ob1/Samsung: avoids status 133/147 races on immediate reconnect. + */ + val postCloseSettleMs: Long = 2_000L, + /** Pause after stopScan / ADV sighting before connectGatt (Ob1 CONNECT_NOW ≈ 500 ms). */ + val scanHandoffMs: Long = 500L, + /** + * On reconnect attempts, LE-scan until the target MAC advertises (or timeout). + * 0 = skip (MAC-only connectGatt). + */ + val preConnectScanMs: Long = 0L, + /** + * When true, request MTU on CONNECTED before discover. + * When false, discover (+ CCCD) first — Ob1 never requests MTU; safer on Samsung. + */ + val requestMtuOnConnect: Boolean = true, + /** Call hidden BluetoothGatt.refresh() before close / reconnect. */ + val useGattRefresh: Boolean = false, + /** + * Use connectGatt(autoConnect=true) when attempt index >= this. + * -1 = never (hard connect only). + */ + val autoConnectFromAttempt: Int = -1, + /** Optional pause after services discovered before CCCD (Ob1 Samsung pairing workaround). */ + val postDiscoverDelayMs: Long = 0L, + /** + * When true and [preConnectScanMs] > 0, abort connect on ADV miss for **attempt 0 only** + * (see driver). Later attempts connect by known MAC after a best-effort scan. + */ + val requireAdvBeforeConnect: Boolean = false, + /** + * Force `BluetoothGatt.CONNECTION_PRIORITY_HIGH` (7.5 ms interval) on connect. Juggluco's + * Dex / ONE+ path does **not** — an aggressive interval correlated with the transmitter + * terminating the link (peer status 19) right after the post-auth `0x4E`. Default off: let + * the OS negotiate the interval, as Juggluco does. + */ + val forceHighConnectionPriority: Boolean = false, + /** + * Request a larger ATT MTU. Juggluco's Dex / ONE+ path **never** requests MTU (stays at 23, + * which fits an EGV frame); requesting 517→23 mid-connection is an extra exchange the ONE+ + * dislikes. Default off. [requestMtuOnConnect] only chooses *when* to request, if this is on. + */ + val requestMtu: Boolean = false, +) + +enum class OemProfileId { + PIXEL, + SAMSUNG, + MOTOROLA, + GENERIC_FALLBACK, +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfo.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfo.kt new file mode 100644 index 000000000000..b854ee7fddac --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/oem/OnePlusDeviceInfo.kt @@ -0,0 +1,15 @@ +package app.aaps.plugins.dexcomoneplus.oem + +/** + * Who made the phone this is running on, as the platform reports it. + * + * Only [DeviceProfileRegistry] needs it, to pick the BLE timings a given OEM's stack needs. The + * names are matched case insensitively, so a platform may return them in any case. + */ +internal expect fun onePlusDeviceManufacturer(): String + +/** + * The phone's model name, as the platform reports it. Logged with the chosen profile so a field + * report says which phone it came from; nothing is decided on it today. + */ +internal expect fun onePlusDeviceModel(): String diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillControlRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillControlRx.kt new file mode 100644 index 000000000000..032dd68b837b --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillControlRx.kt @@ -0,0 +1,15 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control ACK for BackFillTxMessage2 (opcode 0x59). + * + * Provenance: xDrip `BackFillControlRxMessage` / G7 `BackfillControlRx` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +object OnePlusBackFillControlRx { + + const val OPCODE: Byte = 0x59 + + fun isAck(packet: ByteArray): Boolean = + packet.isNotEmpty() && packet[0] == OPCODE +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillStream.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillStream.kt new file mode 100644 index 000000000000..02cf9fa1d4de --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillStream.kt @@ -0,0 +1,95 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import kotlin.time.Clock + +/** + * Assembles ProbablyBackfill notifications and decodes G7/ONE+ records. + * + * Short-TxId path (`streamType > 0` in xDrip): concatenate payload bytes; each + * record is 9 bytes: dexTime | glucose12 | type | flags | trend. A record whose flags carry + * [OnePlusGlucoseParser.DISPLAY_ONLY_FLAG] repeats a fingerstick and is skipped. + * + * Provenance: xDrip `BackFillStream` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +class OnePlusBackFillStream { + + private val buffer = ByteArray(MAX_BUFFER) + + /** How much of [buffer] holds bytes, the same thing `ByteBuffer.position()` told us. */ + private var filled = 0 + + fun hasData(): Boolean = filled > 0 + + fun byteCount(): Int = filled + + fun reset() { + filled = 0 + } + + /** Append a G7/ONE+ backfill notification (full packet). */ + fun pushG7(packet: ByteArray) { + if (packet.isEmpty()) return + val remaining = MAX_BUFFER - filled + if (remaining <= 0) return + val n = minOf(packet.size, remaining) + packet.copyInto(buffer, destinationOffset = filled, startIndex = 0, endIndex = n) + filled += n + } + + /** + * Decode buffered G7 records into glucose samples. + * + * @param currentDexTimeSeconds transmitter clock now (from TransmitterTime) + * @param nowMs wall clock corresponding to [currentDexTimeSeconds] + */ + fun decode( + currentDexTimeSeconds: Int, + nowMs: Long = Clock.System.now().toEpochMilliseconds(), + maxAgeMs: Long = MAX_AGE_MS, + ): List { + val extent = filled + if (extent < G7_RECORD_SIZE) return emptyList() + // A reader over the filled part only, which is what flipping the old buffer gave. + val view = OnePlusByteReader(buffer.copyOf(extent)) + val out = ArrayList() + try { + while (view.remaining >= G7_RECORD_SIZE) { + val dexTime = view.int() + val glucose = view.short().toInt() and 0x0fff + val type = view.u8() + val flags = view.u8() + val trend = view.byte().toInt() + val state = OnePlusCalibrationState.parse(type) + if (!state.usableGlucose()) continue + if (flags and OnePlusGlucoseParser.DISPLAY_ONLY_FLAG != 0) continue + if (dexTime == 0) continue + val ts = fromDexTime(dexTime, currentDexTimeSeconds, nowMs) + val age = nowMs - ts + if (age < 0L || age > maxAgeMs) continue + val sample = OnePlusGlucoseParser.toSample( + mgdl = glucose.toDouble(), + timestampMs = ts, + trendSlopeMgdlPerMin = trendToSlope(trend), + ) ?: continue + out.add(sample) + } + } catch (_: Exception) { + // mismatched trailing bytes — return what we parsed + } + return out + } + + companion object { + const val G7_RECORD_SIZE: Int = 9 + const val MAX_BUFFER: Int = 2800 + /** Align with Ob1 short-TxId window (~24 h) with slack. */ + const val MAX_AGE_MS: Long = 25L * 60L * 60L * 1000L + + fun fromDexTime(dexTime: Int, currentDexTimeSeconds: Int, nowMs: Long): Long = + nowMs - (currentDexTimeSeconds.toLong() - dexTime.toLong()) * 1000L + + private fun trendToSlope(trend: Int): Double? = OnePlusGlucoseParser.trendToSlope(trend) + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillTx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillTx.kt new file mode 100644 index 000000000000..69fb2869c8a4 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBackFillTx.kt @@ -0,0 +1,23 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control BackFill request for short-TxId / G7 / ONE+ (opcode 0x59). + * + * Layout (9 bytes, no CRC): opcode | startDex(u32 LE) | endDex(u32 LE) + * + * Provenance: xDrip `BackFillTxMessage2` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +object OnePlusBackFillTx { + + const val OPCODE: Byte = 0x59 + const val PACKET_LENGTH: Int = 9 + + fun build(startDexTimeSeconds: Int, endDexTimeSeconds: Int): ByteArray { + val buf = OnePlusByteWriter(PACKET_LENGTH) + buf.put(OPCODE) + buf.putInt(startDexTimeSeconds) + buf.putInt(endDexTimeSeconds) + return buf.array() + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytes.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytes.kt new file mode 100644 index 000000000000..6c596f57807c --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytes.kt @@ -0,0 +1,114 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * The little bit of `java.nio.ByteBuffer` this driver used, written so the packet code can stay in + * shared code. + * + * The Dex family puts every multi byte field on the wire little endian, so these two classes are + * little endian only. They read and write exactly the bytes `ByteBuffer.order(LITTLE_ENDIAN)` did, + * and the packet tests in `androidHostTest` are what hold them to that. + */ + +/** + * Reads a packet front to back, like a `ByteBuffer` with its position. + * + * Reading past the end throws, the way `ByteBuffer` threw `BufferUnderflowException`, so a caller + * that wrapped a decode in `try` keeps behaving the same way. + */ +internal class OnePlusByteReader(private val bytes: ByteArray, private var position: Int = 0) { + + /** How many bytes are still unread. */ + val remaining: Int get() = bytes.size - position + + /** The next byte, signed, as `ByteBuffer.get()` returned it. */ + fun byte(): Byte { + require(remaining >= 1) { "OnePlusByteReader underflow at $position" } + return bytes[position++] + } + + /** The next byte as an unsigned 0..255 value. */ + fun u8(): Int = byte().toInt() and 0xff + + /** The next two bytes, little endian, signed, as `ByteBuffer.getShort()` returned them. */ + fun short(): Short { + require(remaining >= 2) { "OnePlusByteReader underflow at $position" } + val low = bytes[position].toInt() and 0xff + val high = bytes[position + 1].toInt() and 0xff + position += 2 + return ((high shl 8) or low).toShort() + } + + /** The next four bytes, little endian, signed, as `ByteBuffer.getInt()` returned them. */ + fun int(): Int { + require(remaining >= 4) { "OnePlusByteReader underflow at $position" } + val value = intAt(position) + position += 4 + return value + } + + /** Four bytes at an absolute offset, little endian, as `ByteBuffer.getInt(index)` did. */ + fun intAt(offset: Int): Int { + require(offset >= 0 && offset + 4 <= bytes.size) { "OnePlusByteReader offset $offset out of range" } + return (bytes[offset].toInt() and 0xff) or + ((bytes[offset + 1].toInt() and 0xff) shl 8) or + ((bytes[offset + 2].toInt() and 0xff) shl 16) or + ((bytes[offset + 3].toInt() and 0xff) shl 24) + } + + /** Steps over [count] bytes without reading them. */ + fun skip(count: Int) { + require(remaining >= count) { "OnePlusByteReader underflow at $position" } + position += count + } +} + +/** + * Builds a fixed length packet front to back, like `ByteBuffer.allocate(size)`. + * + * The bytes that are never written stay zero, which is what `ByteBuffer.allocate` gave as well, + * and the two CRC bytes at the end of most requests rely on it. + */ +internal class OnePlusByteWriter(size: Int) { + + private val bytes = ByteArray(size) + private var position = 0 + + fun put(value: Byte) { + bytes[position++] = value + } + + /** Two bytes, little endian, as `ByteBuffer.putShort()` wrote them. */ + fun putShort(value: Short) { + val v = value.toInt() + bytes[position++] = (v and 0xff).toByte() + bytes[position++] = ((v shr 8) and 0xff).toByte() + } + + /** Four bytes, little endian, as `ByteBuffer.putInt()` wrote them. */ + fun putInt(value: Int) { + bytes[position++] = (value and 0xff).toByte() + bytes[position++] = ((value shr 8) and 0xff).toByte() + bytes[position++] = ((value shr 16) and 0xff).toByte() + bytes[position++] = ((value shr 24) and 0xff).toByte() + } + + /** The whole buffer, including the bytes that were never written. */ + fun array(): ByteArray = bytes +} + +/** + * Lower case hex of every byte, the same text `"%02x".format(b)` produced per byte. + * + * `String.format` is JVM only, which is the only reason this exists. + */ +internal fun ByteArray.onePlusToHex(): String { + val out = StringBuilder(size * 2) + for (b in this) { + val v = b.toInt() and 0xff + out.append(HEX_DIGITS[v shr 4]) + out.append(HEX_DIGITS[v and 0x0f]) + } + return out.toString() +} + +private const val HEX_DIGITS = "0123456789abcdef" diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationState.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationState.kt new file mode 100644 index 000000000000..6325a4d9e525 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationState.kt @@ -0,0 +1,77 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.warmup.OnePlusWarmupClock +import kotlin.time.Clock + +/** + * Calibration / sensor state byte from EGV packets. + * + * Provenance: xDrip `CalibrationState` at pin `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +enum class OnePlusCalibrationState(val value: Int) { + Unknown(0x00), + Stopped(0x01), + WarmingUp(0x02), + ExcessNoise(0x03), + NeedsFirstCalibration(0x04), + NeedsSecondCalibration(0x05), + Ok(0x06), + NeedsCalibration(0x07), + SensorFailed(0x0b), + Ended(0x0f), + SensorExpired(0x18), + SensorStarted(0xC1), + SensorStopped(0xC2), + CalibrationSent(0xC3), + Other(-1), + ; + + fun usableGlucose(): Boolean = this == Ok || this == NeedsCalibration + + fun warmingUp(): Boolean = this == WarmingUp + + fun failed(): Boolean = this == SensorFailed || this == Ended || this == SensorExpired || this == SensorStopped + + companion object { + fun parse(raw: Int): OnePlusCalibrationState { + val v = raw and 0xff + return entries.firstOrNull { it.value == v } ?: Other + } + } +} + +object OnePlusCalibrationMapper { + + /** + * Maps calibration byte + optional session age (seconds from EGV2) into [OnePlusWarmupState]. + * When warming up without exact remaining, uses [OnePlusWarmupClock] 30 min fallback from [nowMs]. + */ + fun toWarmupState( + state: OnePlusCalibrationState, + nowMs: Long = Clock.System.now().toEpochMilliseconds(), + sessionAgeSeconds: Int? = null, + ): OnePlusWarmupState { + return when { + state.warmingUp() || state == OnePlusCalibrationState.SensorStarted -> { + if (sessionAgeSeconds != null && sessionAgeSeconds in 0 until OnePlusWarmupClock.DEFAULT_WARMUP_MS.toInt() / 1000) { + val remaining = (OnePlusWarmupClock.DEFAULT_WARMUP_MS - sessionAgeSeconds * 1000L).coerceAtLeast(0L) + OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + remainingMs = remaining, + endsAtEpochMs = nowMs + remaining, + message = state.name, + ) + } else { + OnePlusWarmupClock.warmingFromStart(startEpochMs = nowMs, nowMs = nowMs, message = state.name) + } + } + state.usableGlucose() || state == OnePlusCalibrationState.Ok -> + OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY, remainingMs = 0L, message = state.name) + state.failed() -> + OnePlusWarmupState(phase = OnePlusWarmupState.Phase.FAILED, message = state.name) + else -> + OnePlusWarmupState(phase = OnePlusWarmupState.Phase.WARMING, message = state.name) + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusEGlucoseTx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusEGlucoseTx.kt new file mode 100644 index 000000000000..87bc7f7254a2 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusEGlucoseTx.kt @@ -0,0 +1,24 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control-channel EGV request (opcode 0x4e). + * + * Provenance: xDrip `EGlucoseTxMessage` / `BaseMessage.init` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +object OnePlusEGlucoseTx { + + const val OPCODE: Byte = 0x4e + + /** Short TxId / G7-ONE+ style request (length 1, no CRC). */ + fun requestShort(): ByteArray = byteArrayOf(OPCODE) + + /** Longer request with CRC (length 3). */ + fun requestWithCrc(): ByteArray { + val body = byteArrayOf(OPCODE, 0, 0) + val crc = OnePlusFastCrc16.calculate(body, 1) + body[1] = crc[0] + body[2] = crc[1] + return body + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusFastCrc16.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusFastCrc16.kt new file mode 100644 index 000000000000..8755b883d34d --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusFastCrc16.kt @@ -0,0 +1,43 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Dex G5/G7 message CRC16. + * + * Provenance: NightscoutFoundation/xDrip `FastCRC16.java` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0, jamorham). + */ +object OnePlusFastCrc16 { + + private val table = intArrayOf( + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, + ) + + fun calculate(bytes: ByteArray, end: Int = bytes.size): ByteArray { + var crc = 0 + for (i in 0 until end) { + crc = (crc shl 8) xor table[(crc ushr 8 xor (bytes[i].toInt() and 0xff)) and 0xff] + } + return byteArrayOf((crc and 0xff).toByte(), ((crc shr 8) and 0xff).toByte()) + } + + fun check(packet: ByteArray): Boolean { + if (packet.size < 3) return false + val crc = calculate(packet, packet.size - 2) + return crc[0] == packet[packet.size - 2] && crc[1] == packet[packet.size - 1] + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParser.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParser.kt new file mode 100644 index 000000000000..c6d80c421afe --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusGlucoseParser.kt @@ -0,0 +1,218 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import kotlin.time.Clock + +/** + * Pure glucose parse / bounds helpers + Control EGV packet decode. + * + * Kotlin rewrite of field layouts from NightscoutFoundation/xDrip (GPL-3.0): + * - `g5model/EGlucoseRxMessage.java` (opcode 0x4f + FastCRC16) + * - `g5model/EGlucoseRxMessage2.java` / `cgm/dex/g7/EGlucoseRxMessage.java` (opcode 0x4e) + * - trend scaling from `BaseGlucoseRxMessage.getTrend()` (raw ≠ 127 → mg/dL/min = raw/10) + * + * Pin: `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f`. See `plugins/dexcom_oneplus/NOTICE`. + */ +object OnePlusGlucoseParser { + + const val MIN_MGDL: Double = 20.0 + const val MAX_MGDL: Double = 600.0 + + /** xDrip `EGlucoseRxMessage.opcode` (CRC-checked). */ + const val OPCODE_EGV1: Int = 0x4f + + /** xDrip `EGlucoseRxMessage2` / G7 `EGlucoseRxMessage.opcode` (no CRC in Ob1 path). */ + const val OPCODE_EGV2: Int = 0x4e + + /** Upstream invalid trend marker (`BaseGlucoseRxMessage` / G7 `getTrend`). */ + const val TREND_INVALID: Int = 127 + + /** Bit of the flags byte (0x4E byte 18, backfill record byte 7) that marks a display-only value. */ + const val DISPLAY_ONLY_FLAG: Int = 0x10 + + fun inRange(mgdl: Double): Boolean = mgdl in MIN_MGDL..MAX_MGDL + + /** + * Accepts a numeric mg/dL value; returns null if outside [MIN_MGDL]..[MAX_MGDL]. + * Bounds gate (reject, do not coerce). + */ + fun sanitizeMgdl(mgdl: Double): Double? = if (inRange(mgdl)) mgdl else null + + /** + * Builds a sample when value is in range; null otherwise (caller logs ERROR / drops). + */ + fun toSample( + mgdl: Double, + timestampMs: Long, + trendSlopeMgdlPerMin: Double? = null, + sequence: Long? = null, + ): OnePlusGlucoseSample? { + val safe = sanitizeMgdl(mgdl) ?: return null + return OnePlusGlucoseSample( + mgdl = safe, + timestampMs = timestampMs, + trendSlopeMgdlPerMin = trendSlopeMgdlPerMin, + sequence = sequence, + ) + } + + /** + * Decode Control EGV notify bytes → [OnePlusGlucoseSample], or null when opcode/layout/bounds fail. + */ + fun parse(packet: ByteArray, nowMs: Long = Clock.System.now().toEpochMilliseconds()): OnePlusGlucoseSample? = + parseControlPacket(packet, nowMs)?.sample + + data class ParsedEgv( + val sample: OnePlusGlucoseSample?, + val calibration: OnePlusCalibrationState, + val usable: Boolean, + val ageSeconds: Int?, + val sessionAgeSeconds: Int?, + val opcode: Int, + /** + * The sensor marks the value as for display only: it repeats a fingerstick right after a + * calibration, it is not a measurement. It never becomes a [sample]. + */ + val glucoseIsDisplayOnly: Boolean = false, + val predictedGlucose: Int? = null, + /** Byte 18 of a 0x4E packet, raw, for the log. Null for 0x4F. */ + val flags: Int? = null, + ) + + /** + * Parse a Control characteristic notification with calibration metadata. + * Returns null if not an EGV opcode / too short / CRC fail (EGV1). + */ + fun parseControlPacket(packet: ByteArray, nowMs: Long = Clock.System.now().toEpochMilliseconds()): ParsedEgv? { + if (packet.isEmpty()) return null + val opcode = packet[0].toInt() and 0xff + return when (opcode) { + OPCODE_EGV1 -> parseEgv1(packet, nowMs) + OPCODE_EGV2 -> parseEgv2(packet, nowMs) + else -> null + } + } + + /** + * Opcode 0x4f — `g5model/EGlucoseRxMessage` (min 14 bytes, FastCRC16 on trailing 2). + * Wall timestamp uses [nowMs] (upstream `getRealTimestamp` default = receive time). + */ + private fun parseEgv1(packet: ByteArray, nowMs: Long): ParsedEgv? { + if (packet.size < 14) return null + if (!OnePlusFastCrc16.check(packet)) return null + val data = OnePlusByteReader(packet) + data.skip(1) // opcode + data.skip(1) // status / battery raw + val sequence = data.int().toLong() and 0xffffffffL + val txTimestamp = data.int() // dex relative seconds + val glucoseBytes = data.short().toInt() and 0xffff + val glucoseIsDisplayOnly = (glucoseBytes and 0xf000) != 0 + val glucose = glucoseBytes and 0x0fff + val state = data.u8() + val trend = data.byte().toInt() // signed byte promoted + val predicted = if (data.remaining >= 2) data.short().toInt() and 0x03ff else null + val cal = OnePlusCalibrationState.parse(state) + val sample = if (cal.usableGlucose() && glucose > 13) { + toSample( + mgdl = glucose.toDouble(), + timestampMs = nowMs, + trendSlopeMgdlPerMin = trendToSlope(trend), + sequence = sequence, + ) + } else { + null + } + return ParsedEgv( + sample = sample, + calibration = cal, + usable = cal.usableGlucose() && sample != null, + ageSeconds = null, + sessionAgeSeconds = if (txTimestamp > 0) txTimestamp else null, + opcode = OPCODE_EGV1, + glucoseIsDisplayOnly = glucoseIsDisplayOnly, + predictedGlucose = predicted, + ) + } + + /** + * Opcode 0x4e — G7 / ONE+ `EGlucoseRxMessage2` / `cgm/dex/g7/EGlucoseRxMessage` (min 19 bytes). + * Timestamp = [nowMs] − ageSeconds × 1000 (upstream `getRealTimestamp`). + */ + private fun parseEgv2(packet: ByteArray, nowMs: Long): ParsedEgv? { + if (packet.size < 19) return null + // Ob1 path matches opcode only (no CRC). + val data = OnePlusByteReader(packet) + data.skip(1) // opcode 0x4e + data.skip(1) // status_raw + val sessionAge = readUnsignedInt(data).toInt() + val sequence = readUnsignedShort(data).toLong() + readUnsignedShort(data) // unused / "bogus" upstream + val age = readUnsignedShort(data) + val glucoseBytes = data.short().toInt() and 0xffff + val glucose = glucoseBytes and 0x0fff + val state = data.u8() + val trend = data.byte().toInt() // signed byte promoted + var predicted: Int? = data.short().toInt() and 0x03ff + if (predicted == 0x3ff) predicted = null // Message2 invalid marker + // Display only is bit 0x10 of byte 18, as in Loop's G7SensorKit (`G7GlucoseMessage`) and in + // the Dexcom G7 driver of AAPS PR 5397. xDrip reads it from the top bits of the glucose + // field, which is the G6 layout: on a G7 those bits are always 0, so a value echoed after a + // calibration was never recognised and went to the loop. + val flags = data.u8() + val glucoseIsDisplayOnly = glucoseBytes != 0xffff && (flags and DISPLAY_ONLY_FLAG) != 0 + val cal = OnePlusCalibrationState.parse(state) + val adjusted = if (cal == OnePlusCalibrationState.Stopped && sessionAge * 1000L < 30L * 60L * 1000L) { + OnePlusCalibrationState.WarmingUp + } else { + cal + } + val ts = nowMs - age * 1000L + // Sample when usable + in range; ageRecent (age < 305) is Ob1 sync-only, not an insert gate. + val sample = if (adjusted.usableGlucose() && glucose > 13 && !glucoseIsDisplayOnly) { + toSample( + mgdl = glucose.toDouble(), + timestampMs = ts, + trendSlopeMgdlPerMin = trendToSlope(trend), + sequence = sequence, + ) + } else { + null + } + return ParsedEgv( + sample = sample, + calibration = adjusted, + usable = adjusted.usableGlucose() && sample != null, + ageSeconds = age, + sessionAgeSeconds = sessionAge, + opcode = OPCODE_EGV2, + glucoseIsDisplayOnly = glucoseIsDisplayOnly, + predictedGlucose = predicted, + flags = flags, + ) + } + + /** + * Upstream: `trend != 127 ? trend / 10.0 : NaN`. The EGV trend byte is a signed rate scaled by + * ten, so dividing by ten gives mg/dL per minute — see [OnePlusGlucoseSample.trendSlopeMgdlPerMin]. + */ + internal fun trendToSlope(trend: Int): Double? { + if (trend == TREND_INVALID) return null + return trend / 10.0 + } + + /** Matches `cgm/dex/g7/BaseMessage.getUnsignedInt`. */ + private fun readUnsignedInt(data: OnePlusByteReader): Long { + val b0 = data.u8().toLong() + val b1 = data.u8().toLong() + val b2 = data.u8().toLong() + val b3 = data.u8().toLong() + return b0 + (b1 shl 8) + (b2 shl 16) + (b3 shl 24) + } + + /** Matches `cgm/dex/g7/BaseMessage.getUnsignedShort`. */ + private fun readUnsignedShort(data: OnePlusByteReader): Int { + val b0 = data.u8() + val b1 = data.u8() + return b0 + (b1 shl 8) + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartRx.kt new file mode 100644 index 000000000000..47e472e0ceb8 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartRx.kt @@ -0,0 +1,65 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control SessionStart response (opcode 0x27). + * + * Provenance: xDrip `SessionStartRxMessage` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +data class OnePlusSessionStartRx( + val status: Int, + val info: Int, + val requestedStartTime: Int, + val sessionStartTime: Int, + val transmitterTime: Int, + val valid: Boolean, +) { + + fun isOkay(): Boolean = + valid && + status == 0x00 && + (info == 0x01 || info == 0x05 || info == 0x06) && + sessionStartTime != INVALID_TIME + + /** Sensor already running — not a hard failure for reconnect / re-start UX. */ + fun isAlreadyStarted(): Boolean = valid && info == 0x02 + + fun isFubar(): Boolean = valid && info == 0x04 + + fun message(): String = when (info) { + 0x01 -> "OK" + 0x02 -> "Already started" + 0x03 -> "Invalid" + 0x04 -> "Clock not synchronized or other error" + 0x05 -> "OK G6" + 0x06 -> "OK G6 - unsure" + else -> "Unknown code: $info" + } + + companion object { + const val OPCODE: Byte = 0x27 + const val PACKET_LENGTH: Int = 17 + const val INVALID_TIME: Int = -1 // 0xFFFFFFFF as signed int + + fun parse(packet: ByteArray): OnePlusSessionStartRx? { + if (packet.size != PACKET_LENGTH) return null + if (packet[0] != OPCODE) return null + if (!OnePlusFastCrc16.check(packet)) return null + val data = OnePlusByteReader(packet) + data.skip(1) // opcode + val status = data.u8() + val info = data.u8() + val requested = data.int() + val sessionStart = data.int() + val txTime = data.int() + return OnePlusSessionStartRx( + status = status, + info = info, + requestedStartTime = requested, + sessionStartTime = sessionStart, + transmitterTime = txTime, + valid = true, + ) + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartTx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartTx.kt new file mode 100644 index 000000000000..6f2d26278e09 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStartTx.kt @@ -0,0 +1,31 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control SessionStart request (opcode 0x26) — ONE+ / short-TxId form (no G6 sensor code). + * + * Layout (11 bytes incl. CRC): opcode | dexTime(u32 LE) | startUnixSec(u32 LE) | crc16 + * + * Provenance: xDrip `SessionStartTxMessage` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +object OnePlusSessionStartTx { + + const val OPCODE: Byte = 0x26 + const val PACKET_LENGTH: Int = 11 + + /** + * @param dexTimeSeconds transmitter time (seconds); 0 if unknown before TransmitterTime sync + * @param startTimeEpochMs wall-clock session start (ms); encoded as seconds in the packet + */ + fun build(dexTimeSeconds: Int, startTimeEpochMs: Long): ByteArray { + val buf = OnePlusByteWriter(PACKET_LENGTH) + buf.put(OPCODE) + buf.putInt(dexTimeSeconds) + buf.putInt((startTimeEpochMs / 1000L).toInt()) + val packet = buf.array() + val crc = OnePlusFastCrc16.calculate(packet, PACKET_LENGTH - 2) + packet[PACKET_LENGTH - 2] = crc[0] + packet[PACKET_LENGTH - 1] = crc[1] + return packet + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopRx.kt new file mode 100644 index 000000000000..7737422a99f1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopRx.kt @@ -0,0 +1,45 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control SessionStop response (opcode 0x29). + * + * Provenance: xDrip `SessionStopRxMessage` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +data class OnePlusSessionStopRx( + val status: Int, + val received: Int, + val sessionStopTime: Int, + val sessionStartTime: Int, + val transmitterTime: Int, + val valid: Boolean, +) { + + fun isOkay(): Boolean = valid && status == 0x00 + + companion object { + const val OPCODE: Byte = 0x29 + const val PACKET_LENGTH: Int = 17 + + fun parse(packet: ByteArray): OnePlusSessionStopRx? { + if (packet.size != PACKET_LENGTH) return null + if (packet[0] != OPCODE) return null + if (!OnePlusFastCrc16.check(packet)) return null + val data = OnePlusByteReader(packet) + data.skip(1) // opcode + val status = data.u8() + val received = data.u8() + val stop = data.int() + val start = data.int() + val txTime = data.int() + return OnePlusSessionStopRx( + status = status, + received = received, + sessionStopTime = stop, + sessionStartTime = start, + transmitterTime = txTime, + valid = true, + ) + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopTx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopTx.kt new file mode 100644 index 000000000000..111f7753cf0d --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusSessionStopTx.kt @@ -0,0 +1,27 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control SessionStop request (opcode 0x28). + * + * Layout (7 bytes incl. CRC): opcode | stopDexTime(u32 LE) | crc16 + * + * Provenance: xDrip `SessionStopTxMessage` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +object OnePlusSessionStopTx { + + const val OPCODE: Byte = 0x28 + const val PACKET_LENGTH: Int = 7 + + /** @param stopTimeDexSeconds transmitter clock seconds at stop */ + fun build(stopTimeDexSeconds: Int): ByteArray { + val buf = OnePlusByteWriter(PACKET_LENGTH) + buf.put(OPCODE) + buf.putInt(stopTimeDexSeconds) + val packet = buf.array() + val crc = OnePlusFastCrc16.calculate(packet, PACKET_LENGTH - 2) + packet[PACKET_LENGTH - 2] = crc[0] + packet[PACKET_LENGTH - 1] = crc[1] + return packet + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeRx.kt new file mode 100644 index 000000000000..0c8e4aed95ef --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeRx.kt @@ -0,0 +1,57 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import kotlin.time.Clock + +/** + * Control TransmitterTime response (opcode 0x25). + * + * Provenance: xDrip `TransmitterTimeRxMessage` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +data class OnePlusTransmitterTimeRx( + val statusByte: Int, + val currentTimeSeconds: Int, + val sessionStartTimeSeconds: Int, +) { + + fun sessionInProgress(): Boolean = + sessionStartTimeSeconds != INVALID_TIME && + currentTimeSeconds != sessionStartTimeSeconds + + /** + * Wall-clock estimate of when the sensor session started, or null if not in progress. + */ + fun realSessionStartEpochMs(nowMs: Long = Clock.System.now().toEpochMilliseconds()): Long? { + if (!sessionInProgress()) return null + val ageSec = (currentTimeSeconds.toLong() - sessionStartTimeSeconds.toLong()) + return nowMs - ageSec * 1000L + } + + fun sessionAgeSeconds(): Long? { + if (!sessionInProgress()) return null + return (currentTimeSeconds.toLong() - sessionStartTimeSeconds.toLong()).coerceAtLeast(0L) + } + + companion object { + const val OPCODE: Byte = 0x25 + /** op + status + current(4) + sessionStart(4) + crc(2). */ + const val MIN_LENGTH: Int = 12 + const val INVALID_TIME: Int = -1 // 0xFFFFFFFF + + fun parse(packet: ByteArray): OnePlusTransmitterTimeRx? { + if (packet.size < MIN_LENGTH) return null + if (packet[0] != OPCODE) return null + if (!OnePlusFastCrc16.check(packet)) return null + // Fields sit in the first 10 bytes; CRC is the final 2 (xDrip reads via absolute offsets). + val status = packet[1].toInt() and 0xff + val data = OnePlusByteReader(packet) + val current = data.intAt(2) + val sessionStart = data.intAt(6) + return OnePlusTransmitterTimeRx( + statusByte = status, + currentTimeSeconds = current, + sessionStartTimeSeconds = sessionStart, + ) + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeTx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeTx.kt new file mode 100644 index 000000000000..cbacfaa7cadc --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusTransmitterTimeTx.kt @@ -0,0 +1,23 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control TransmitterTime request (opcode 0x24). + * + * Layout (3 bytes): opcode | crc16 — same pattern as [OnePlusEGlucoseTx.requestWithCrc]. + * + * Provenance: xDrip `TransmitterTimeTxMessage` at pin + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +object OnePlusTransmitterTimeTx { + + const val OPCODE: Byte = 0x24 + const val PACKET_LENGTH: Int = 3 + + fun request(): ByteArray { + val body = byteArrayOf(OPCODE, 0, 0) + val crc = OnePlusFastCrc16.calculate(body, 1) + body[1] = crc[0] + body[2] = crc[1] + return body + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OnePlusReconnectPolicy.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OnePlusReconnectPolicy.kt new file mode 100644 index 000000000000..0f20fe90261a --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/reconnect/OnePlusReconnectPolicy.kt @@ -0,0 +1,38 @@ +package app.aaps.plugins.dexcomoneplus.reconnect + +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile + +/** + * Reconnect / backoff policy. Uses [OemDeviceProfile] knobs only — no GATT. + */ +interface OnePlusReconnectPolicy { + fun shouldRetry(attempt: Int, profile: OemDeviceProfile): Boolean + fun nextDelayMs(attempt: Int, profile: OemDeviceProfile): Long +} + +class OemAwareReconnectPolicy : OnePlusReconnectPolicy { + + override fun shouldRetry(attempt: Int, profile: OemDeviceProfile): Boolean { + if (attempt < 0) return false + return attempt < profile.connectRetryCount + } + + override fun nextDelayMs(attempt: Int, profile: OemDeviceProfile): Long { + val base = profile.connectRetryDelayMs.coerceAtLeast(0L) + if (!profile.aggressiveReconnect) return base + // First reconnect is quick — the sensor advertises in short windows, so a fast retry + // catches the next one instead of parking for the full base delay (field: Samsung sat + // 20 s idle after an auth=2 wipe before the full J-PAKE could run). Then grow linearly, + // but cap so late attempts don't stretch to minute-scale gaps. + val delay = if (attempt <= 1) FIRST_RETRY_MS else base * (attempt - 1) + return delay.coerceAtMost(MAX_RECONNECT_DELAY_MS) + } + + companion object { + /** Delay before the first reconnect attempt (catch the next ADV window fast). */ + const val FIRST_RETRY_MS = 3_000L + + /** Upper bound on any reconnect backoff. */ + const val MAX_RECONNECT_DELAY_MS = 30_000L + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScanner.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScanner.kt new file mode 100644 index 000000000000..d5264af62be8 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScanner.kt @@ -0,0 +1,75 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import kotlin.concurrent.Volatile + +/** + * BLE scan façade for ONE+ / G7-family ADV. + * + * ⚠️ ASYNC IMPACT: Android `ScanCallback` runs on the binder thread; + * [OnePlusScanListener.onDevice] may be invoked off the main thread — hop to main for UI. + */ +fun interface OnePlusScanListener { + fun onDevice(result: OnePlusScanResult) +} + +/** + * Outcome of a bounded pre-connect ADV wait. + * + * @param target the awaited MAC, or null when it stayed silent for the whole window. + * @param foreign other ONE+ / G7-family transmitters heard during the same window. A non-empty + * [foreign] with a null [target] is the signature of a **stale stored MAC** (sensor replaced, or + * started into the other slot): a ONE+ is right there, it is simply not the one we wait for. + */ +data class OnePlusAdvWaitResult( + val target: OnePlusScanResult? = null, + val foreign: List = emptyList(), +) { + + /** Strongest foreign transmitter heard, for the "wrong MAC?" diagnostic. */ + fun strongestForeign(): OnePlusScanResult? = foreign.maxByOrNull { it.rssi } +} + +interface OnePlusBleScanner { + fun startScan(listener: OnePlusScanListener) + fun stopScan() + fun isScanning(): Boolean + + /** + * Tell the scanner what the slot's store now knows about its sensor, so later advertisements + * are ranked and sticky-matched against it. + * + * Called after a successful authentication and after the identity is saved. The default does + * nothing, which is right for a scanner that does not rank anything. + */ + fun updateSessionHint(session: OnePlusStoredSession?) = Unit + + /** + * Block until [address] is seen in ADV (or timeout), also reporting any other ONE+ family + * transmitter heard in the same window. + * + * A [stopScan] from the screen must not cut this wait short. Android gets that from a private + * `ScanCallback`. Each platform owes the guarantee, not the mechanism. + * + * ⚠️ ASYNC IMPACT: blocks the calling thread; the platform delivers results on its own thread. + */ + fun awaitTarget(address: String, timeoutMs: Long): OnePlusAdvWaitResult = OnePlusAdvWaitResult() +} + +/** + * No-op scanner for unit tests / Stub driver path. + */ +class OnePlusBleScannerStub : OnePlusBleScanner { + @Volatile + private var scanning = false + + override fun startScan(listener: OnePlusScanListener) { + scanning = true + } + + override fun stopScan() { + scanning = false + } + + override fun isScanning(): Boolean = scanning +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudget.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudget.kt new file mode 100644 index 000000000000..f8bdc6464703 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanBudget.kt @@ -0,0 +1,120 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock + +/** + * Process-wide LE scan start budget shared by **all** ONE+ slots (production + staging) and the UI + * discovery scan. + * + * Android silently stops delivering results when an app starts more than + * [MAX_STARTS_PER_WINDOW_PLATFORM] LE scans within [WINDOW_MS] (`ScanManager` + * "app is scanning too frequently"): no `onScanFailed`, no error — the callback simply never fires. + * + * The quota counts scan **registrations**, not scan time, so one long window is far cheaper than + * several short ones. The persistent ADV wait therefore uses + * `OnePlusBleSessionCyclePolicy.PERSISTENT_ADV_SCAN_MS` (20 s) rather than the per-OEM + * `OemDeviceProfile.preConnectScanMs`: about 3 starts/min per slot, so even two slots plus the UI + * discovery scan stay inside the platform's 10/min. + * + * ⚠️ This used to read "roughly every 8.25 s (~7.3 starts/min), which is under the quota". That + * only ever held for the Samsung profile (`preConnectScanMs` 8 s). Generic used 3 s and Pixel 2 s, + * giving 3.25 s / 2.25 s cycles — 18 and 27 starts/min, i.e. a *single* slot structurally over the + * quota. The CUBOT field log of 2026-08-20 measured 18.3 starts/min, 13 platform throttle events, + * and the budget deferring its own scans for 54 % of the wait. Keep any future window/delay change + * consistent with the arithmetic above. + * + * This budget keeps one slot free for the UI discovery scan, so opening the Start screen can never + * be starved by the background waits either. + * + * ⚠️ ASYNC IMPACT: [waitMsFor] / [record] take [lock] and are non-blocking; the *caller* decides + * whether it may sleep (background BLE executor: yes — UI thread: never, it only [record]s). + */ +object OnePlusScanBudget { + + /** Platform accounting window for the "scanning too frequently" throttle. */ + const val WINDOW_MS = 30_000L + + /** What the platform actually allows per [WINDOW_MS]. */ + const val MAX_STARTS_PER_WINDOW_PLATFORM = 5 + + /** What we allow ourselves — one slot kept in reserve for the UI discovery scan. */ + const val MAX_STARTS_PER_WINDOW = MAX_STARTS_PER_WINDOW_PLATFORM - 1 + + /** Longest single sleep a waiting caller does before re-checking (keeps `stop` responsive). */ + const val MAX_SLEEP_SLICE_MS = 500L + + /** + * Guards everything below. An [AapsLock] rather than `@Synchronized`, which is JVM only, so + * this budget stays in shared code. It is reentrant, like the object monitor it + * replaces, which [reserve] relies on when it calls [waitMsFor]. + */ + private val lock = AapsLock() + + private val starts = ArrayDeque() + + /** Elapsed-time until which no start is granted at all — see [blockFor]. */ + private var blockedUntilMs = 0L + + /** + * Hold every scan start back for [durationMs], on top of the normal quota. + * + * Used when a caller has good reason to believe the OS is silently refusing our scans: the model + * of the platform quota is then known to be too optimistic on this device, and the only safe + * reaction is to scan less until the platform window has certainly rolled over. + */ + fun blockFor(nowMs: Long, durationMs: Long) = lock.withLock { + val until = nowMs + durationMs.coerceAtLeast(0L) + if (until > blockedUntilMs) blockedUntilMs = until + } + + /** + * Milliseconds to wait before another `startScan` may be issued (0 = free slot available now). + * Pure function of the recorded history — safe to call from any thread. + */ + fun waitMsFor(nowMs: Long): Long = lock.withLock { + prune(nowMs) + val blocked = (blockedUntilMs - nowMs).coerceAtLeast(0L) + if (blocked > 0L) return@withLock blocked + if (starts.size < MAX_STARTS_PER_WINDOW) return@withLock 0L + val oldest = starts.first() + (WINDOW_MS - (nowMs - oldest)).coerceAtLeast(0L) + } + + /** Book a scan start at [nowMs]. Callers must invoke this for **every** `startScan`. */ + fun record(nowMs: Long) = lock.withLock { + prune(nowMs) + starts.addLast(nowMs) + } + + /** + * Atomically take a start slot: returns 0 with the start booked, or the milliseconds to wait + * before retrying. Checking [waitMsFor] and then [record] separately would let two slots racing + * on their own BLE executors both pass the same free slot. + */ + fun reserve(nowMs: Long): Long = lock.withLock { + val wait = waitMsFor(nowMs) + if (wait > 0L) return@withLock wait + starts.addLast(nowMs) + 0L + } + + /** Recorded starts still inside the platform window (diagnostics / tests). */ + fun startsInWindow(nowMs: Long): Int = lock.withLock { + prune(nowMs) + starts.size + } + + /** Test seam — drops the recorded history. */ + fun reset() = lock.withLock { + starts.clear() + blockedUntilMs = 0L + } + + private fun prune(nowMs: Long) { + // Also drops entries from a backwards clock jump so a bad timestamp cannot wedge the budget. + while (starts.isNotEmpty() && (nowMs - starts.first() >= WINDOW_MS || nowMs < starts.first())) { + starts.removeFirst() + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt new file mode 100644 index 000000000000..6a55062f4264 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt @@ -0,0 +1,21 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import kotlin.concurrent.Volatile + +/** + * LE advertisement hit for ONE+ / G7-family transmitters. + */ +data class OnePlusScanResult( + val address: String, + val name: String?, + val rssi: Int, +) { + /** + * The platform's monotonic clock in milliseconds when this ADV was last seen, for UI→driver + * handoff freshness. On Android that is `SystemClock.elapsedRealtime()`. + * Intentionally **not** a constructor property: excluded from `equals`/`hashCode`/`copy` so it + * never affects list keys or the scanner's field-diff dedup. + */ + @Volatile + var seenElapsedMs: Long = 0L +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanSelection.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanSelection.kt new file mode 100644 index 000000000000..05cba1831d1a --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanSelection.kt @@ -0,0 +1,45 @@ +package app.aaps.plugins.dexcomoneplus.scan + +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession + +/** + * Which sensor a setup screen may select on its own, out of what the scan heard. + * + * This is a rule, not a platform job, so it lives in shared code and is the same on every + * platform. + */ +object OnePlusScanSelection { + + /** + * The sensor a screen may select on its own, out of what the scan heard. + * + * Exactly one hit, and only then. The 4-digit code is the KEKS password and is not in the + * advertisement, so with two ONE+ in range no score can tell which one the user just applied: + * the strongest signal may be the neighbour's, and the best ranked one may be the sensor being + * replaced. Picking either would send the user into a five minute connect with the wrong + * transmitter. Two or more is a question, and the user answers it by tapping a row. + * + * Nothing heard means nothing to connect to, so that answer is null as well. + */ + fun autoSelectSingle(devices: List): OnePlusScanResult? = devices.singleOrNull() + + /** + * The transmitter the start screen may select on its own, given what the scan heard so far. + * + * Two cases, and the code on screen is what tells them apart: + * - The code belongs to the stored sensor, so this is a reconnect or a repair of the session + * already running. That sensor is the answer, even among several: the user is not choosing + * anything new. A live sighting of it is preferred over the stored one, because it carries + * the fresh ADV the driver connects in-window with. + * - The code belongs to another sensor. Nothing sticky may apply then, and only a single hit + * may be selected — see [autoSelectSingle]. + * + * Feed it the session from `OnePlusAdvCandidate.scanHintFor`, which is what drops the stored + * MAC as soon as the code on screen is another sensor. + */ + fun autoSelect(devices: List, hint: OnePlusStoredSession?): OnePlusScanResult? { + val storedMac = hint?.lastMac?.takeIf { it.isNotBlank() } ?: return autoSelectSingle(devices) + return devices.firstOrNull { it.address.equals(storedMac, ignoreCase = true) } + ?: OnePlusScanResult(address = storedMac, name = hint.lastDeviceName, rssi = 0) + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRx.kt new file mode 100644 index 000000000000..f841e0a24234 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthStatusRx.kt @@ -0,0 +1,34 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * AuthStatus (opcode 0x05) fields from Dexcom G7/ONE+ Authentication characteristic. + * + * Semantics aligned with Juggluco [DexGattCallback.authenticate] ChallengeReply and + * xDrip libkeks [AuthStatusRxMessage]: only [authenticated] == 1 is crypto success. + */ +internal data class OnePlusAuthStatusRx( + val authenticated: Int, + val bonded: Int, +) { + val isAuthenticated: Boolean get() = authenticated == AUTHENTICATED_OK + val sensorReportsBonded: Boolean get() = bonded == SENSOR_BONDED + val needsKeyRefresh: Boolean get() = bonded == SENSOR_NEEDS_REFRESH + + companion object { + const val OPCODE: Int = 0x05 + const val AUTHENTICATED_OK: Int = 1 + const val SENSOR_BONDED: Int = 1 + /** Juggluco accepts OS-bonded + this after full cert exchange. */ + const val SENSOR_BOND_ALT: Int = 2 + const val SENSOR_NEEDS_REFRESH: Int = 3 + + fun parse(payload: ByteArray): OnePlusAuthStatusRx? { + if (payload.size < 3) return null + if ((payload[0].toInt() and 0xff) != OPCODE) return null + return OnePlusAuthStatusRx( + authenticated = payload[1].toInt() and 0xff, + bonded = payload[2].toInt() and 0xff, + ) + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfill.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfill.kt new file mode 100644 index 000000000000..e52fcb5cd572 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfill.kt @@ -0,0 +1,17 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample + +/** + * Short history pull after session up. + * + * Production path: [OnePlusBackfillSession] invoked from [OnePlusEgvSession] after + * TransmitterTime / SessionStart. This interface remains for tests / stubs. + */ +interface OnePlusBackfill { + fun requestRecent(): List +} + +class OnePlusBackfillStub : OnePlusBackfill { + override fun requestRecent(): List = emptyList() +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt new file mode 100644 index 000000000000..f7a432a12dd7 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt @@ -0,0 +1,137 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.onePlusSleep +import app.aaps.plugins.dexcomoneplus.parse.OnePlusBackFillControlRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusBackFillStream +import app.aaps.plugins.dexcomoneplus.parse.OnePlusBackFillTx +import kotlin.time.Clock + +/** + * Short history pull after session up — G7/ONE+ BackFillTxMessage2 path. + * + * Sequence: enable ProbablyBackfill notify → write Control 0x59 window → + * collect stream → decode → [onGlucose]. + * + * ⚠️ ASYNC IMPACT: Blocks bleExecutor (Control + backfill awaits). [shouldContinue] + * false / GATT disconnect must unblock both queues. + * + * Provenance: Ob1G5StateMachine.backFillIfNeeded / monitorBackFill / BackFillStream + * at pin `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +class OnePlusBackfillSession( + private val gatt: OnePlusGattClient, + private val onGlucose: (OnePlusGlucoseSample) -> Unit = {}, + private val onError: (String, Boolean) -> Unit = { _, _ -> }, +) { + + /** + * @param currentDexTimeSeconds from TransmitterTime (required > 0) + * @return number of samples delivered + */ + fun runOnce( + currentDexTimeSeconds: Int, + shouldContinue: () -> Boolean, + lookbackMs: Long = DEFAULT_LOOKBACK_MS, + ): Int { + if (!gatt.isConnected() || !shouldContinue()) return 0 + if (currentDexTimeSeconds < 1) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: backfill skipped — no dexTime", + ) + return 0 + } + + val lookbackSec = (lookbackMs / 1000L).toInt().coerceAtLeast(1) + val endDex = currentDexTimeSeconds + val startDex = (currentDexTimeSeconds - lookbackSec).coerceAtLeast(1) + if (startDex >= endDex) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: backfill skipped — empty window", + ) + return 0 + } + + try { + gatt.enableBackfillNotifications() + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_BACKFILL_CCCD_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: $msg", t) + onError(msg, false) + return 0 + } + if (!onePlusSleep(CCCD_SETTLE_MS)) return 0 + + val tx = OnePlusBackFillTx.build(startDex, endDex) + try { + gatt.writeControl(tx) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: wrote BackFillTx2 opcode=0x59 " + + "start=$startDex end=$endDex", + ) + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_BACKFILL_WRITE_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: $msg", t) + onError(msg, false) + return 0 + } + + // Optional Control ACK (same opcode 0x59). + val ack = gatt.awaitControlNotify(ACK_TIMEOUT_MS) + if (ack != null && OnePlusBackFillControlRx.isAck(ack)) { + OnePlusLog.d("${OnePlusLogMarkers.SESSION}: BackFillControlRx ACK") + } else if (ack != null) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: backfill Control notify non-ACK op=0x" + + (ack[0].toInt() and 0xff).toString(16), + ) + } + + val stream = OnePlusBackFillStream() + val deadline = Clock.System.now().toEpochMilliseconds() + COLLECT_TIMEOUT_MS + var lastPacketMs = 0L + while (shouldContinue() && gatt.isConnected() && Clock.System.now().toEpochMilliseconds() < deadline) { + val wait = if (stream.hasData()) QUIET_TIMEOUT_MS else 1_000L + val packet = gatt.awaitBackfillNotify(wait) + if (!shouldContinue()) break + if (packet == null) { + if (stream.hasData() && lastPacketMs > 0L && + Clock.System.now().toEpochMilliseconds() - lastPacketMs >= QUIET_TIMEOUT_MS + ) { + break + } + continue + } + stream.pushG7(packet) + lastPacketMs = Clock.System.now().toEpochMilliseconds() + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: backfill chunk ${packet.size}b total=${stream.byteCount()}", + ) + } + + val nowMs = Clock.System.now().toEpochMilliseconds() + val samples = stream.decode(currentDexTimeSeconds, nowMs) + for (sample in samples) { + OnePlusLog.d( + "${OnePlusLogMarkers.BG}: backfill mgdl=${sample.mgdl} ts=${sample.timestampMs}", + ) + onGlucose(sample) + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: backfill done samples=${samples.size} bytes=${stream.byteCount()}", + ) + return samples.size + } + + companion object { + const val CCCD_SETTLE_MS: Long = 200L + const val ACK_TIMEOUT_MS: Long = 5_000L + const val COLLECT_TIMEOUT_MS: Long = 15_000L + const val QUIET_TIMEOUT_MS: Long = 3_000L + /** Short window (Ob1 G5 default 3 h; G7 allows 24 h). */ + const val DEFAULT_LOOKBACK_MS: Long = 3L * 60L * 60L * 1000L + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt new file mode 100644 index 000000000000..e942ca42c6a9 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt @@ -0,0 +1,1035 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.onePlusSleep +import app.aaps.plugins.dexcomoneplus.reconnect.OemAwareReconnectPolicy +import app.aaps.plugins.dexcomoneplus.reconnect.OnePlusReconnectPolicy +import app.aaps.plugins.dexcomoneplus.warmup.OnePlusWarmupClock +import kotlin.concurrent.Volatile +import kotlin.time.Clock + +/** + * ONE+ BLE session lifecycle (scan already done → connect → auth → Control EGV → warm-up/glucose). + * + * ⚠️ ASYNC IMPACT: Real fills run on bleExecutor; [startWithPairingCode] blocks that thread + * through KEKS + [OnePlusEgvSession] loop + reconnect sleeps. [stop] must be callable without + * waiting for the executor queue (sets [running] false + GATT disconnect to unblock awaits). + */ +interface OnePlusBleSession { + fun startWithPairingCode(deviceAddress: String, pairingCode: String) + fun stop(reason: String?) + fun isUp(): Boolean + fun warmupState(): OnePlusWarmupState +} + +/** + * Outcome of the pre-connect step (`beforeConnect`). + * + * @param advFresh a recent ADV sighting for the target MAC is in hand (UI handoff or in-window + * rescan hit) → prefer a fast direct connect (`autoConnect=false`) over the OEM autoConnect park. + * @param blindFallback the persistent ADV wait gave up waiting and authorises **one** connect + * without a sighting. Without this escape a restored session can never leave the wait, because + * [OnePlusBleSessionCyclePolicy.allowConnection] refuses every ADV-less connect (field log + * 2026-08-03: 18 min of `target ADV absent — remain waiting`, no glucose, no error, no retry). + * @param foreignAdv redacted label of the strongest *other* ONE+ heard while the target stayed + * silent — the stale-stored-MAC signature. + */ +data class OnePlusConnectPrep( + val advFresh: Boolean = false, + val blindFallback: Boolean = false, + val foreignAdv: String? = null, +) + +/** Next persistent-ADV retry: raised strategy index plus the connect prep to use. */ +private data class PersistentRetry( + val attempt: Int, + val prep: OnePlusConnectPrep?, +) + +/** + * Pure decisions for the post-Control-loop transition, kept separate from Android BLE calls so the + * normal duty-cycle behavior can be unit tested. + * + * **Link robustness.** Early builds lost the sensor after a while in a car with its Bluetooth on, + * with a Bluetooth headset playing audio, and in crowded places such as a metro. Audio uses the + * same radio as BLE and goes first, so connects fail (133, 147) and links drop (8) far more often + * there. These rules are what keeps the sensor connected in those places. Nothing in their names + * says so, so check this list before you simplify any of them: + * - a session that has sent Control traffic never ends in a terminal failure. It goes to the + * persistent ADV wait ([recoverExhaustedBudgetWithPersistentWait], [applyFailureBudget]); + * - the wait listens in long windows that stay inside the platform scan quota + * ([PERSISTENT_ADV_SCAN_MS]), so the platform does not block our scans; + * - it ignores the end of the burst of the cycle that just closed ([POST_CYCLE_ADV_GUARD_MS]); + * - after a failed `autoConnect` it does not retry at once ([skipAdvWaitAfterFailedConnect]), and + * it connects without an ADV at most once per silence window ([authorizeBlindConnect]). Both + * stop a burst of connects on a busy radio; + * - the link never asks for `CONNECTION_PRIORITY_HIGH` (`OemDeviceProfile.forceHighConnectionPriority`). + * + * `OnePlusBleSessionCyclePolicyTest` holds these rules for every OEM profile. On Android the GATT + * client logs the Bluetooth audio state on every link loss, so a field log shows whether a car + * or a headset was in use. + */ +internal object OnePlusBleSessionCyclePolicy { + const val POST_COLLECTION_RECONNECT_ATTEMPT = 1 + + /** + * Continuous ADV silence after which the persistent wait authorises one blind connect. Long + * enough that a normal G7 duty cycle (~5 min) never triggers it, short enough that a sensor the + * phone simply stopped hearing is retried rather than waited on forever. + */ + const val BLIND_CONNECT_AFTER_ADV_SILENCE_MS = 4L * 60_000L + + /** Continuous ADV silence after which a stale stored MAC is reported. */ + const val STALE_MAC_SUSPICION_AFTER_MS = 6L * 60_000L + + /** + * Quiet period after a **successful** EGV cycle before the next ADV wait may start. + * + * The transmitter keeps radiating the tail of its current advertising burst for a few hundred + * milliseconds after it closes the link. Re-arming the wait immediately latches that residual + * burst, reports "next-cycle target ADV acquired" and connects into a sensor that is already + * going to sleep. CUBOT field log 2026-08-20: cycle down 17:10:14.012 → ADV at 17:10:14.139 + * (+127 ms) → `connectGatt` → status 133 after 30 s → autoConnect retry → 60 s timeout. That is + * 97 s of a 300 s cycle spent on a connect that could not succeed, and the silence clock only + * starts once it ends, so the blind-connect escape is late for the real next window too. + * + * The next genuine burst is a whole duty cycle away (~5 min), so a guard of this size cannot + * hide it. Applies to the healthy-cycle path only: after a *failed* connect the sensor may + * legitimately still be advertising and that sighting is worth catching. + */ + const val POST_CYCLE_ADV_GUARD_MS = 10_000L + + /** + * Length of one filtered ADV window during the persistent wait. + * + * Android's throttle counts scan **registrations** (5 per 30 s), not scan time, so a few long + * windows are far cheaper than many short ones *and* hear the advertisement the moment it + * arrives instead of at the next poll. The per-OEM [OemDeviceProfile.preConnectScanMs] stays + * what it is for the normal pre-connect rescan; only this open-ended wait uses the long window. + * + * Sized so that two slots (production + staging) polling together stay under the platform quota + * with room to spare for the UI discovery scan: 20 s + [ADV_WAIT_RESTART_DELAY_MS] ≈ 3 starts + * per minute per slot, against the 10 per minute the platform allows. It is also the worst-case + * lag between `stop` and the wait loop noticing it, which is why it is not longer still. + */ + const val PERSISTENT_ADV_SCAN_MS = 20_000L + + /** + * Pause between two ADV windows of the persistent wait. Only long enough to keep `stop` + * responsive between windows — the scan-start rate is governed by [PERSISTENT_ADV_SCAN_MS]. + */ + const val ADV_WAIT_RESTART_DELAY_MS = 250L + + /** + * A cycle that proved the link works ends in the persistent ADV wait instead of the bounded + * failure budget. + * + * Gating this on a *usable glucose value* made warm-up impossible to survive: a warming sensor + * only sends `WarmingUp` packets, so every normal duty-cycle disconnect burned one retry, and the + * budget was exhausted (FAILED, session dead) minutes into the ~30 min warm-up. Any parsed + * Control packet proves the same thing a glucose value does — the sensor is ours, authenticated + * and talking. + */ + fun waitForAdvertisementAfterExit(sessionProvedHealthy: Boolean): Boolean = + sessionProvedHealthy + + /** + * Control traffic that proves the session is alive. [OnePlusWarmupState.Phase.FAILED] is + * excluded on purpose: a stopped / expired / failed sensor must keep the bounded budget so it + * ends in a real failure instead of waiting for an advertisement that means nothing. + */ + fun controlTrafficProvesSession(phase: OnePlusWarmupState.Phase): Boolean = + phase == OnePlusWarmupState.Phase.WARMING || phase == OnePlusWarmupState.Phase.READY + + /** + * Retry budget exhausted: recover into the persistent ADV wait instead of the terminal FAILED, + * but ONLY when the Control channel has already delivered at least once. Such a sensor is + * asleep between radio windows, not lost, so waiting is right. + * + * The proof must be real Control traffic, never a successful authentication. A sensor that has + * no session started completes the whole handshake and then hangs up on the first glucose + * request, so "authenticated" is true on every cycle while the slot receives nothing at all. + * Recovering on that signal removed the terminal FAILED, and with it the only way back to a + * fresh sensor start (SessionStart is issued on attempt 0 only) — the slot then retried for + * ever and could never come back. + */ + fun recoverExhaustedBudgetWithPersistentWait(sessionEverProvedControlChannel: Boolean): Boolean = + sessionEverProvedControlChannel + + /** + * Warm-up deadline to remember once [state] has been emitted, so the countdown survives the + * CONNECTING / RECONNECTING states of a duty cycle (those carry no clock of their own and used + * to blank the UI countdown until the next EGV packet). + */ + fun warmupDeadlineAfter(previousEndsAtMs: Long?, state: OnePlusWarmupState): Long? = + when (state.phase) { + OnePlusWarmupState.Phase.WARMING -> state.endsAtEpochMs ?: previousEndsAtMs + OnePlusWarmupState.Phase.READY, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.FAILED -> null + OnePlusWarmupState.Phase.PAIRING, + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING -> previousEndsAtMs + } + + fun applyFailureBudget(preparedPostCollectionAdvertisement: Boolean): Boolean = + !preparedPostCollectionAdvertisement + + fun requireFreshAdvertisementBeforeReconnect(persistentAdvertisementMode: Boolean): Boolean = + persistentAdvertisementMode + + fun allowConnection( + restoredSessionMode: Boolean, + advertisementFresh: Boolean, + blindFallbackAuthorized: Boolean = false, + ): Boolean = !restoredSessionMode || advertisementFresh || blindFallbackAuthorized + + /** + * Long enough silence on the stored MAC to suspect it is stale. + * + * A foreign ONE+ sighting **strengthens** the log line; it must not **gate** the diagnosis. + * Under the pre-connect MAC+FEBC filter, a house with one sensor never sees a foreign ADV, so + * requiring one made this check unreachable (CUBOT field log 2026-08-16). + */ + fun suspectStaleMac(continuousAdvSilenceMs: Long, foreignSightings: Int): Boolean { + // [foreignSightings] is logged at the call site; it must not gate the diagnosis. + return continuousAdvSilenceMs >= STALE_MAC_SUSPICION_AFTER_MS + } + + /** + * Strategy index after a persistent-ADV retryable failure. This must **rise**, not reset to + * [POST_COLLECTION_RECONNECT_ATTEMPT]: Generic/Pixel only enable `autoConnect` from attempt 2, + * and pinning at 1 made that park unreachable. The failure **budget** stays separate + * ([applyFailureBudget] is still false while a post-collection wait is prepared). + */ + fun nextPersistentAttempt(currentAttempt: Int): Int = + currentAttempt + 1 + + /** + * Fresh ADV → hard connect (fail-fast). Otherwise the OEM `autoConnectFromAttempt` park. + * Samsung uses `autoConnectFromAttempt = 0`, so a quiet sensor still parks a background connect + * on attempt 1. That path must stay as-is. + */ + fun useAutoConnect( + advFresh: Boolean, + attempt: Int, + autoConnectFromAttempt: Int, + ): Boolean = when { + advFresh -> false + autoConnectFromAttempt < 0 -> false + else -> attempt >= autoConnectFromAttempt + } + + /** + * After a failed connect in persistent-ADV mode, skip the next ADV wait only when the failed + * attempt was a **hard** connect and the next one would use `autoConnect`. + * + * Generic CUBOT log: attempt 1 `autoConnect=false` → 133 in 30 s. The next attempt (2) is the + * first park and should run now, not after another 4 min of filtered scanning. + * + * Samsung: attempt 1 already used `autoConnect=true`. Immediate retry would GATT-storm after + * 133. Return false so Samsung keeps the ADV wait and the 4 min blind cooldown. + */ + fun skipAdvWaitAfterFailedConnect( + lastConnectUsedAutoConnect: Boolean, + nextAttempt: Int, + autoConnectFromAttempt: Int, + ): Boolean { + if (lastConnectUsedAutoConnect) return false + return useAutoConnect( + advFresh = false, + attempt = nextAttempt, + autoConnectFromAttempt = autoConnectFromAttempt, + ) + } + + /** + * One blind connect after [BLIND_CONNECT_AFTER_ADV_SILENCE_MS] of silence, then not again until + * another full silence window has passed **since that blind**. The silence clock itself must + * keep running (stale-MAC at 6 min); only the escape is rate-limited. + * + * [msSinceLastBlindConnect] null means no blind has been issued in this silence episode. + */ + fun authorizeBlindConnect( + continuousAdvSilenceMs: Long, + msSinceLastBlindConnect: Long? = null, + ): Boolean { + if (continuousAdvSilenceMs < BLIND_CONNECT_AFTER_ADV_SILENCE_MS) return false + val sinceBlind = msSinceLastBlindConnect ?: Long.MAX_VALUE + return sinceBlind >= BLIND_CONNECT_AFTER_ADV_SILENCE_MS + } + + /** Whole minutes of silence — the granularity at which the wait re-emits a warm-up state. */ + fun advSilenceMinutes(continuousAdvSilenceMs: Long): Long = + continuousAdvSilenceMs.coerceAtLeast(0L) / 60_000L +} + +/** + * Session: pairing validation → GATT connect → KEKS auth → Control/EGV loop, with OEM + * reconnect retries after GATT drop / connect-auth failure. After a successful EGV cycle, the + * transmitter's disconnect is treated as normal duty cycling: wait persistently for its next ADV + * instead of consuming the finite failure budget while the radio is asleep. + */ +class OnePlusBleSessionSkeleton( + private val gatt: OnePlusGattClient, + private val auth: OnePlusSessionAuth, + private val reconnectPolicy: OnePlusReconnectPolicy = OemAwareReconnectPolicy(), + private val profile: OemDeviceProfile = DeviceProfileRegistry.resolve(), + private val onWarmup: (OnePlusWarmupState) -> Unit = {}, + private val onGlucose: (OnePlusGlucoseSample) -> Unit = {}, + private val onSession: (Boolean, String?) -> Unit = { _, _ -> }, + private val onError: (String, Boolean) -> Unit = { _, _ -> }, + /** + * When true on the **first** successful connect only: SessionStart **if** the + * transmitter has no session yet. Never auto SessionStop (Dexcom recovery). + * Reconnect attempts always pass false. + */ + private val requestNewSensorStart: Boolean = true, + /** + * Ob1-style pre-connect: LE rescan / handoff before [OnePlusGattClient.connect]. + * Runs on bleExecutor; must not touch UI. Returns [OnePlusConnectPrep] (ADV freshness). + * + * `scanMs` overrides [OemDeviceProfile.preConnectScanMs] for this call; null keeps the profile + * value. The persistent ADV wait passes + * [OnePlusBleSessionCyclePolicy.PERSISTENT_ADV_SCAN_MS] so an open-ended wait costs few scan + * registrations instead of one every few seconds. + * + * Default no-op (tests / stub). + */ + private val beforeConnect: (deviceAddress: String, attempt: Int, scanMs: Long?) -> OnePlusConnectPrep = + { _, _, _ -> OnePlusConnectPrep() }, + /** Juggluco-style reconnect: preload 16-byte KEKS shared key when available. */ + private val savedSharedKeyProvider: () -> ByteArray? = { null }, + /** Persist MAC + shared key after successful auth. */ + private val onAuthSuccess: (deviceAddress: String, sharedKey: ByteArray) -> Unit = { _, _ -> }, + /** Clear persisted shared key when short-auth / bond path is invalidated. */ + private val onAuthInvalidate: () -> Unit = {}, + /** Keeps the processor awake during connect / auth (Juggluco does the same). */ + private val cpuLease: OnePlusCpuLease? = null, + /** Sensor slot owning this session (`prod` / `staging`) — logged on every marker. */ + private val slot: String = OnePlusLogMarkers.SLOT_PRODUCTION, +) : OnePlusBleSession { + + @Volatile + private var up = false + + @Volatile + private var running = false + + @Volatile + private var cancelled = false + + private val lifecycleLock = AapsLock() + + @Volatile + private var warmup = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + + /** + * Last known end of warm-up, kept across connection phases so the UI countdown does not blank + * out on every duty cycle. Maintained by [OnePlusBleSessionCyclePolicy.warmupDeadlineAfter]. + */ + @Volatile + private var warmupEndsAtEpochMs: Long? = null + + /** + * At least one cycle received real Control traffic (warm-up state or glucose) — the sensor is + * ours AND its data channel works. + * + * This must NOT be "auth succeeded": a sensor with no active session completes the whole KEKS + * handshake and then drops the link as soon as it is asked for glucose (peer status 19). Using + * auth as the proof kept such a sensor in the persistent wait for ever, so the retry budget + * never ran out, the session never reached FAILED, and the only path that re-issues + * SessionStart (a fresh start on attempt 0) could never be reached again. + */ + @Volatile + private var everProvedControlChannel = false + + /** + * Start of the current ADV-silence episode. 0 = not in an episode. + * Reset only on a real target sighting (or a proven healthy cycle), never on a failed connect. + */ + private var advSilenceStartedMs = 0L + + /** Wall-clock of the last blind-connect escape in this silence episode. 0 = none yet. */ + private var lastBlindConnectAtMs = 0L + + /** Stale-MAC [onError] already posted for this silence episode. */ + private var staleMacReportedThisSilence = false + + /** + * Whether the connect that just failed used `autoConnect=true`. + * Used so Generic can skip the ADV wait to reach the autoConnect park, while Samsung + * (which already parked) does not GATT-storm after status 133. + */ + private var lastConnectUsedAutoConnect = false + + override fun startWithPairingCode(deviceAddress: String, pairingCode: String) { + val codeError = OnePlusSessionStart.validationError(pairingCode) + if (codeError != null) { + fail(codeError, fatal = false) + return + } + val normalized = OnePlusSessionStart.normalizePairingCode(pairingCode) + if (deviceAddress.isBlank()) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] start pairing (addr blank) profile=${profile.id}", + ) + } else { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] start pairing addr=${redactAddress(deviceAddress)} profile=${profile.id}", + ) + } + + val startAllowed = lifecycleLock.withLock { + if (cancelled) { + false + } else { + running = true + true + } + } + if (!startAllowed) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] start ignored — session already stopped", + ) + return + } + setWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.PAIRING, message = "pairing")) + + resetAdvSilenceTracking() + lastConnectUsedAutoConnect = false + var attempt = 0 + var preparedConnect: OnePlusConnectPrep? = null + // A restored session must never fall back to a blind connect while the transmitter sleeps. + // Explicit new-sensor setup may use its existing bounded initial-connect policy. + var persistentAdvertisementMode = !requestNewSensorStart + while (running) { + if (attempt > 0) { + val applyFailureBudget = OnePlusBleSessionCyclePolicy.applyFailureBudget( + preparedPostCollectionAdvertisement = preparedConnect != null, + ) + if (applyFailureBudget && !reconnectPolicy.shouldRetry(attempt, profile)) { + if (!OnePlusBleSessionCyclePolicy.recoverExhaustedBudgetWithPersistentWait(everProvedControlChannel)) { + fail("ONEPLUS_RECONNECT_EXHAUSTED: attempts=$attempt", fatal = false) + return + } + // A sensor that has already sent us Control traffic is asleep, not lost: keep + // waiting for its next radio window instead of ending in a terminal FAILED only + // a manual restart could leave. + OnePlusLog.w( + "${OnePlusLogMarkers.RECONNECT}: [$slot] retry budget exhausted after proven Control " + + "traffic (attempts=$attempt) — switch to persistent ADV wait", + ) + persistentAdvertisementMode = true + preparedConnect = preparePostCollectionReconnect( + deviceAddress = deviceAddress, + reason = "retry_budget_exhausted_waiting_for_adv", + ) + if (!running || preparedConnect == null) return + attempt = OnePlusBleSessionCyclePolicy.POST_COLLECTION_RECONNECT_ATTEMPT + // The prepared fresh ADV bypasses the backoff delay and the pre-connect rescan. + continue + } + if (applyFailureBudget) { + val delayMs = reconnectPolicy.nextDelayMs(attempt, profile) + OnePlusLog.i( + "${OnePlusLogMarkers.RECONNECT}: [$slot] attempt=$attempt delayMs=$delayMs " + + "profile=${profile.id} aggressive=${profile.aggressiveReconnect}", + ) + if (!sleepWhileRunning(delayMs)) { + stop("cancelled") + return + } + } else { + val bypassReason = when { + preparedConnect?.advFresh == true -> "fresh_adv" + preparedConnect?.blindFallback == true -> "blind_escape" + else -> "prepared_connect" + } + OnePlusLog.i( + "${OnePlusLogMarkers.RECONNECT}: [$slot] bypass retry delay " + + "reason=$bypassReason attempt=$attempt profile=${profile.id}", + ) + } + } else { + OnePlusLog.i( + "${OnePlusLogMarkers.RECONNECT}: [$slot] attempt=0 " + + "maxRetries=${profile.connectRetryCount} timeoutMs=${profile.connectTimeoutMs}", + ) + } + + val wantSessionStart = OnePlusSessionStartPolicy.wantSessionStartOnAttempt( + requestNewSensorStart = requestNewSensorStart, + attempt = attempt, + ) + val outcome = runConnectionCycle( + deviceAddress = deviceAddress, + pairingCode = normalized, + requestNewSensorStart = wantSessionStart, + attempt = attempt, + preparedConnect = preparedConnect, + ) + preparedConnect = null + if (!running) return + + when (outcome) { + CycleOutcome.Stopped -> return + CycleOutcome.HealthyCycleThenExited -> { + persistentAdvertisementMode = true + resetAdvSilenceTracking() + preparedConnect = preparePostCollectionReconnect( + deviceAddress = deviceAddress, + reason = "egv_cycle_complete_waiting_for_adv", + postCycleQuietMs = OnePlusBleSessionCyclePolicy.POST_CYCLE_ADV_GUARD_MS, + ) + if (!running || preparedConnect == null) return + // Attempt 1 suppresses SessionStart and reports a reconnect, while the prepared + // fresh ADV bypasses both the backoff delay and a second pre-connect scan. + attempt = OnePlusBleSessionCyclePolicy.POST_COLLECTION_RECONNECT_ATTEMPT + } + CycleOutcome.EgvExited -> { + if (OnePlusBleSessionCyclePolicy.requireFreshAdvertisementBeforeReconnect( + persistentAdvertisementMode, + ) + ) { + val retry = persistentRetryAfterFailure( + deviceAddress = deviceAddress, + currentAttempt = attempt, + reason = "egv_loop_exit_waiting_for_adv", + ) + if (!running || retry.prep == null) return + attempt = retry.attempt + preparedConnect = retry.prep + } else { + // Drop before the first usable EGV: retain bounded failure retries. + up = false + try { + gatt.disconnect() + } catch (_: Throwable) { + } + onSession(false, "egv_loop_exit") + enterReconnecting("egv_loop_exit") + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] down reason=egv_loop_exit → reconnect", + ) + attempt++ + } + } + CycleOutcome.RetryableFailure -> { + if (OnePlusBleSessionCyclePolicy.requireFreshAdvertisementBeforeReconnect( + persistentAdvertisementMode, + ) + ) { + val retry = persistentRetryAfterFailure( + deviceAddress = deviceAddress, + currentAttempt = attempt, + reason = "cycle_failure_waiting_for_adv", + ) + if (!running || retry.prep == null) return + attempt = retry.attempt + preparedConnect = retry.prep + } else { + up = false + try { + gatt.disconnect() + } catch (_: Throwable) { + } + attempt++ + } + } + CycleOutcome.Fatal -> return + } + } + } + + /** + * Safe to call from any thread. Clears [running] and disconnects GATT so Control awaits unblock. + * + * ⚠️ ASYNC IMPACT: Must not be queued behind [startWithPairingCode] on the same single-thread + * executor alone — callers should invoke [stop] directly (see `OnePlusCgmDriverReal.disconnect`). + */ + override fun stop(reason: String?) { + lifecycleLock.withLock { + cancelled = true + running = false + up = false + warmup = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE, message = reason) + warmupEndsAtEpochMs = null + } + gatt.disconnect() + emitWarmup() + onSession(false, reason) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] down reason=$reason") + } + + override fun isUp(): Boolean = up + + override fun warmupState(): OnePlusWarmupState = warmup + + private fun runConnectionCycle( + deviceAddress: String, + pairingCode: String, + requestNewSensorStart: Boolean, + attempt: Int, + preparedConnect: OnePlusConnectPrep?, + ): CycleOutcome { + // CONNECTING (first attempt) / RECONNECTING (retry) — never PAIRING here, so the UI can tell + // "establishing link" from the terminal FAILED it used to flash between retries. + val connectingPhase = + if (attempt == 0) OnePlusWarmupState.Phase.CONNECTING else OnePlusWarmupState.Phase.RECONNECTING + setWarmup(OnePlusWarmupState(phase = connectingPhase, message = "connect_attempt_$attempt")) + + val prep = preparedConnect ?: try { + beforeConnect(deviceAddress, attempt, null) + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_BEFORE_CONNECT_FAILED" + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: [$slot] beforeConnect failed: $msg attempt=$attempt", + ) + onError(msg, false) + enterReconnecting(msg) + return if (running) CycleOutcome.RetryableFailure else CycleOutcome.Stopped + } + if (!running) return CycleOutcome.Stopped + if (!OnePlusBleSessionCyclePolicy.allowConnection( + restoredSessionMode = !this.requestNewSensorStart, + advertisementFresh = prep.advFresh, + blindFallbackAuthorized = prep.blindFallback, + ) + ) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] restored session requires fresh ADV — remain waiting", + ) + enterReconnecting("waiting_for_next_adv") + return CycleOutcome.RetryableFailure + } + if (prep.blindFallback) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] blind connect — no ADV sighting, " + + "persistent wait escape (attempt=$attempt)", + ) + } + + // Fresh ADV in hand → fast direct connect (fail-fast status 133 → quick retry). Otherwise fall + // back to the OEM autoConnect policy (Samsung parks a background connect when the sensor is + // quiet — that park cost ~48 s in the field log; the handoff avoids it when a sighting exists). + val useAutoConnect = OnePlusBleSessionCyclePolicy.useAutoConnect( + advFresh = prep.advFresh, + attempt = attempt, + autoConnectFromAttempt = profile.autoConnectFromAttempt, + ) + lastConnectUsedAutoConnect = useAutoConnect + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] connect decision advFresh=${prep.advFresh} " + + "autoConnect=$useAutoConnect attempt=$attempt profile=${profile.id}", + ) + // Hold the CPU awake through settle, scan→connect handoff, connectGatt and discovery. + // The wait clock freezes under suspend (Android sleeps on CLOCK_MONOTONIC): field log 26/08/2026 + // showed a 500 ms handoff taking 27.7 s with the screen off, so the in-window connect + // missed the ADV the wait had just caught. The lock used to start only after connect + // returned, which was too late. + val wakeLock = cpuLease?.hold(AUTH_WAKE_LOCK_MS) + try { + try { + gatt.connect(deviceAddress, autoConnect = useAutoConnect) + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_GATT_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: [$slot] $msg attempt=$attempt", t) + onError(msg, false) + enterReconnecting(msg) + return if (running) CycleOutcome.RetryableFailure else CycleOutcome.Stopped + } + + if (!running) return CycleOutcome.Stopped + + val authResult = auth.authenticate(pairingCode, savedSharedKeyProvider()) + if (!running) return CycleOutcome.Stopped + if (!authResult.ok) { + val msg = authResult.message ?: "ONEPLUS_AUTH_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: [$slot] $msg attempt=$attempt") + if (authResult.invalidateSharedKey || + msg.contains("bond failure", ignoreCase = true) || + msg.contains("key refresh", ignoreCase = true) || + msg.contains("Missing QR", ignoreCase = true) || + msg.contains("short-auth rejected", ignoreCase = true) + ) { + // Stale shared key / cert path — force full KEKS next attempt (Juggluco resetCerts). + try { + onAuthInvalidate() + } catch (_: Throwable) { + } + } + onError(msg, false) + // Retryable: the loop will re-attempt (short-auth reject wipes the key → full J-PAKE + // next). Show RECONNECTING, NOT FAILED — the old FAILED flash made the user abandon + // during the reconnect delay (field log 23:18:40). + enterReconnecting(msg) + return if (running) CycleOutcome.RetryableFailure else CycleOutcome.Stopped + } + + authResult.sharedKey?.let { key -> + try { + onAuthSuccess(deviceAddress, key) + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] onAuthSuccess persist failed: ${t.message}", + ) + } + } + + // Do NOT invent a 30 min WARMING clock here — that blocked ingest even when the + // transmitter was already producing Ok EGVs. Protocol (TransmitterTime / EGV) sets phase. + up = true + setWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.PAIRING, message = "auth_ok")) + onSession(true, if (attempt == 0) "session_up" else "session_reconnected") + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] up attempt=$attempt newStart=$requestNewSensorStart — Control/EGV", + ) + + // Any Control traffic proves the link — a warming sensor never sends usable glucose, so + // gating the persistent ADV wait on glucose alone made warm-up burn the retry budget. + var sessionProvedHealthy = false + val egv = OnePlusEgvSession( + gatt = gatt, + onWarmup = { state -> + if (OnePlusBleSessionCyclePolicy.controlTrafficProvesSession(state.phase)) { + sessionProvedHealthy = true + everProvedControlChannel = true + } + setWarmup(state) + }, + onGlucose = { sample -> + sessionProvedHealthy = true + everProvedControlChannel = true + onGlucose(sample) + }, + onError = onError, + requestNewSensorStart = requestNewSensorStart, + ) + try { + egv.run(shouldContinue = { running && gatt.isConnected() }) + } catch (t: Throwable) { + if (!running) return CycleOutcome.Stopped + val msg = t.message ?: "ONEPLUS_CONTROL_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: [$slot] $msg", t) + onError(msg, false) + enterReconnecting(msg) + return CycleOutcome.RetryableFailure + } + + return when { + !running -> CycleOutcome.Stopped + OnePlusBleSessionCyclePolicy.waitForAdvertisementAfterExit(sessionProvedHealthy) -> + CycleOutcome.HealthyCycleThenExited + else -> CycleOutcome.EgvExited + } + } finally { + // Held from before connect through the first EGV cycle; Juggluco holds it unbounded. + wakeLock?.release() + } + } + + /** + * Transient / retryable transition. UI shows RECONNECTING (never terminal FAILED) so the user + * keeps waiting through the reconnect delay. Terminal failure stays in [fail]. + */ + private fun enterReconnecting( + message: String?, + advSilenceMinutes: Long? = null, + staleMacSuspected: Boolean = false, + ) { + if (!running) return + setWarmup( + OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.RECONNECTING, + message = message, + advSilenceMinutes = advSilenceMinutes, + staleMacSuspected = staleMacSuspected, + ), + ) + } + + /** + * Persistent-ADV failure: raise the strategy index (so Generic/Pixel can reach autoConnect) + * without touching the failure budget. Samsung already parked on attempt 1, so it keeps the + * ADV wait instead of a tight GATT retry after status 133. + */ + private fun persistentRetryAfterFailure( + deviceAddress: String, + currentAttempt: Int, + reason: String, + ): PersistentRetry { + val nextAttempt = OnePlusBleSessionCyclePolicy.nextPersistentAttempt(currentAttempt) + if (OnePlusBleSessionCyclePolicy.skipAdvWaitAfterFailedConnect( + lastConnectUsedAutoConnect = lastConnectUsedAutoConnect, + nextAttempt = nextAttempt, + autoConnectFromAttempt = profile.autoConnectFromAttempt, + ) + ) { + OnePlusLog.i( + "${OnePlusLogMarkers.RECONNECT}: [$slot] skip ADV wait — previous was hard connect, " + + "retry autoConnect attempt=$nextAttempt profile=${profile.id}", + ) + lastBlindConnectAtMs = Clock.System.now().toEpochMilliseconds() + return PersistentRetry( + attempt = nextAttempt, + prep = OnePlusConnectPrep(advFresh = false, blindFallback = true), + ) + } + return PersistentRetry( + attempt = nextAttempt, + prep = preparePostCollectionReconnect(deviceAddress, reason), + ) + } + + private fun resetAdvSilenceTracking() { + advSilenceStartedMs = 0L + lastBlindConnectAtMs = 0L + staleMacReportedThisSilence = false + } + + /** + * Ends the current successful duty cycle and waits for the next transmitter radio window. + * Watcher exceptions are isolated so they cannot terminate the persistent BLE loop. + */ + private fun preparePostCollectionReconnect( + deviceAddress: String, + reason: String, + /** + * Quiet period before the first ADV window, so the transmitter's residual advertising burst + * is not mistaken for the next cycle — see + * [OnePlusBleSessionCyclePolicy.POST_CYCLE_ADV_GUARD_MS]. Only the healthy-cycle path passes + * a value; after a failure the sensor may still be advertising for real. + */ + postCycleQuietMs: Long = 0L, + ): OnePlusConnectPrep? { + if (!running) return null + up = false + try { + gatt.disconnect() + } catch (_: Throwable) { + } + if (!running) return null + try { + onSession(false, reason) + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] down callback failed: ${t.message}", + ) + } + if (!running) return null + try { + enterReconnecting("waiting_for_next_adv") + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.WARMUP}: [$slot] waiting callback failed: ${t.message}", + ) + } + if (!running) return null + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] cycle down reason=$reason — wait persistently for next ADV", + ) + if (postCycleQuietMs > 0L) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] post-cycle ADV guard ${postCycleQuietMs}ms — " + + "ignoring the residual advertising burst of the cycle that just closed", + ) + if (!sleepWhileRunning(postCycleQuietMs)) return null + } + return awaitFreshAdvertisement(deviceAddress) + } + + /** + * A successful EGV cycle resets failure semantics. Dexcom advertises only in short windows, so + * repeatedly scan until the target MAC is actually visible and hand that fresh sighting directly + * to the next connection cycle — no finite retry exhaustion while the radio is merely asleep. + * + * The wait is **not** unbounded any more: + * - every whole minute of silence re-emits a RECONNECTING state, so the UI / ongoing + * notification shows progress instead of a frozen warm-up; + * - after [OnePlusBleSessionCyclePolicy.BLIND_CONNECT_AFTER_ADV_SILENCE_MS] it returns a + * `blindFallback` prep so the cycle may connect without a sighting (a sensor whose ADV the + * phone can no longer hear is otherwise never retried); + * - if the stored MAC stays silent long enough, the stale-MAC suspicion is surfaced through + * [onError] once per silence episode (a foreign ONE+ sighting only enriches the message). + * + * ⚠️ ASYNC IMPACT: blocks bleExecutor in bounded scan calls; [stop] clears [running], so this + * loop exits as soon as the current bounded pre-connect scan returns. + */ + private fun awaitFreshAdvertisement(deviceAddress: String): OnePlusConnectPrep? { + if (advSilenceStartedMs == 0L) { + advSilenceStartedMs = Clock.System.now().toEpochMilliseconds() + } + val silenceStartedMs = advSilenceStartedMs + var lastEmittedMinute = -1L + var lastEmittedStale = false + var foreignEverSeen: String? = null + while (running) { + val prep = try { + beforeConnect( + deviceAddress, + OnePlusBleSessionCyclePolicy.POST_COLLECTION_RECONNECT_ATTEMPT, + OnePlusBleSessionCyclePolicy.PERSISTENT_ADV_SCAN_MS, + ) + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: [$slot] waiting for next ADV failed: ${t.message}", + ) + OnePlusConnectPrep(advFresh = false) + } + if (!running) return null + if (prep.advFresh) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] next-cycle target ADV acquired", + ) + resetAdvSilenceTracking() + return prep + } + + val nowMs = Clock.System.now().toEpochMilliseconds() + val silenceMs = nowMs - silenceStartedMs + val silenceMinutes = OnePlusBleSessionCyclePolicy.advSilenceMinutes(silenceMs) + // A transmitter only advertises in short windows, so a foreign sighting is sporadic: + // remember it for the whole wait instead of requiring it in the same 8 s scan as the + // suspicion threshold. + prep.foreignAdv?.let { foreignEverSeen = it } + val foreignCount = if (foreignEverSeen != null) 1 else 0 + + if (!staleMacReportedThisSilence && + OnePlusBleSessionCyclePolicy.suspectStaleMac(silenceMs, foreignCount) + ) { + staleMacReportedThisSilence = true + val message = if (foreignEverSeen != null) { + "ONEPLUS_ADV_STALE_MAC: target ${redactAddress(deviceAddress)} silent " + + "${silenceMinutes}min while another ONE+ advertises ($foreignEverSeen) — " + + "sensor replaced or started in the other slot?" + } else { + "ONEPLUS_ADV_STALE_MAC: target ${redactAddress(deviceAddress)} silent " + + "${silenceMinutes}min with no advertisement — stored MAC may be stale" + } + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: [$slot] $message") + try { + onError(message, false) + } catch (_: Throwable) { + } + } + + val msSinceLastBlind = + if (lastBlindConnectAtMs == 0L) null else nowMs - lastBlindConnectAtMs + if (OnePlusBleSessionCyclePolicy.authorizeBlindConnect(silenceMs, msSinceLastBlind)) { + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: [$slot] ADV silent ${silenceMinutes}min — " + + "authorising one blind connect (escape from persistent wait)", + ) + lastBlindConnectAtMs = nowMs + return prep.copy(blindFallback = true) + } + + // One state per whole minute (and immediately when the stale-MAC suspicion appears): + // enough for the UI / ongoing notification to show progress, rare enough not to churn + // the notification or the warm-up basal guard every 8 s. + if (silenceMinutes != lastEmittedMinute || staleMacReportedThisSilence != lastEmittedStale) { + lastEmittedMinute = silenceMinutes + lastEmittedStale = staleMacReportedThisSilence + enterReconnecting( + message = "waiting_for_adv", + advSilenceMinutes = silenceMinutes, + staleMacSuspected = staleMacReportedThisSilence, + ) + if (!running) return null + } + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] target ADV absent — remain waiting " + + "silentMs=$silenceMs foreign=${foreignEverSeen ?: "-"}", + ) + if (!sleepWhileRunning(OnePlusBleSessionCyclePolicy.ADV_WAIT_RESTART_DELAY_MS)) return null + } + return null + } + + private fun fail(message: String, fatal: Boolean) { + running = false + up = false + try { + gatt.disconnect() + } catch (_: Throwable) { + } + setWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.FAILED, message = message)) + onError(message, fatal) + onSession(false, message) + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: [$slot] $message fatal=$fatal") + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] down reason=fail") + } + + /** + * Publishes [state] and keeps the warm-up deadline sticky: connection phases carry no clock of + * their own, so without this the UI countdown (and the ongoing notification) went blank on every + * duty cycle and only came back with the next EGV packet. + */ + private fun setWarmup(state: OnePlusWarmupState) { + val published = lifecycleLock.withLock { + // A stopped / superseded session must not be resurrected by a late callback still queued + // on the BLE executor: it would republish a stale phase and, worse, bring the sticky + // deadline back for every later state. [stop] owns the final IDLE state. + if (cancelled && state.phase != OnePlusWarmupState.Phase.IDLE) return + val endsAt = OnePlusBleSessionCyclePolicy.warmupDeadlineAfter(warmupEndsAtEpochMs, state) + warmupEndsAtEpochMs = endsAt + warmup = if (state.endsAtEpochMs == null) state.copy(endsAtEpochMs = endsAt) else state + warmup + } + emitWarmup(published) + } + + /** Logs and publishes [state] to the watcher — outside [lifecycleLock], callbacks are foreign code. */ + private fun emitWarmup(state: OnePlusWarmupState = warmup) { + val remaining = OnePlusWarmupClock.resolveRemainingMs(state, Clock.System.now().toEpochMilliseconds()) + OnePlusLog.i( + "${OnePlusLogMarkers.WARMUP}: [$slot] phase=${state.phase} remainingMs=$remaining " + + "msg=${state.message} advSilenceMin=${state.advSilenceMinutes ?: "-"} " + + "staleMac=${state.staleMacSuspected}", + ) + onWarmup(state) + } + + /** Interruptible sleep that exits early when [stop] clears [running]. */ + private fun sleepWhileRunning(delayMs: Long): Boolean { + if (delayMs <= 0L) return running + val end = Clock.System.now().toEpochMilliseconds() + delayMs + while (running && Clock.System.now().toEpochMilliseconds() < end) { + val slice = (end - Clock.System.now().toEpochMilliseconds()).coerceAtMost(200L).coerceAtLeast(1L) + if (!onePlusSleep(slice)) return false + } + return running + } + + private fun redactAddress(address: String): String { + if (address.length <= 5) return "***" + return "***" + address.takeLast(5) + } + + private enum class CycleOutcome { + /** The cycle proved the session works (glucose or warm-up Control traffic) before exiting. */ + HealthyCycleThenExited, + EgvExited, + RetryableFailure, + Stopped, + Fatal, + } + + companion object { + /** + * Cover settle, scan→connect handoff, connectGatt + discovery, KEKS, bond, first EGV. + * Must be held before those waits: the clock they use freezes under CPU suspend. + * Juggluco uses an unbounded wake lock for the whole connection; we bound it. + */ + private const val AUTH_WAKE_LOCK_MS = 600_000L + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCpuLease.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCpuLease.kt new file mode 100644 index 000000000000..fa2489f407f8 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCpuLease.kt @@ -0,0 +1,30 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * Keeps the phone's processor running while the driver does something that must not be paused. + * + * The session connects, authenticates and reads its first value on one thread, with short waits in + * between. Those waits are measured on a clock that stops while the phone sleeps, so with the + * screen off a 500 ms handoff was once measured taking 27.7 s (field log 26/08/2026) and the + * connection missed the advertisement it had just heard. + * + * The lease says what is wanted - "do not let the phone go to sleep for a while" - and leaves each + * platform to say how. On Android that is a partial wake lock. + */ +interface OnePlusCpuLease { + + /** + * Takes the lease, for at most [maxMillis] in case the holder never gives it back. + * + * @return the lease being held, or null when the platform could not take one. Null is not an + * error the caller has to handle: the work goes ahead, it is only less protected. + */ + fun hold(maxMillis: Long): Hold? + + /** A lease that is being held. */ + interface Hold { + + /** Gives the lease back. Safe to call when it has already ended on its own. */ + fun release() + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt new file mode 100644 index 000000000000..a703e0643d21 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt @@ -0,0 +1,409 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.onePlusSleep +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationMapper +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationState +import app.aaps.plugins.dexcomoneplus.parse.OnePlusEGlucoseTx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusGlucoseParser +import app.aaps.plugins.dexcomoneplus.parse.OnePlusSessionStartRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusSessionStartTx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusSessionStopRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusTransmitterTimeRx +import app.aaps.plugins.dexcomoneplus.warmup.OnePlusWarmupClock +import kotlin.concurrent.Volatile +import kotlin.time.Clock + +/** + * Post-KEKS Control / EGV path aligned with Juggluco `getdatacmd` + xDrip Ob1 `doGetData` (G7). + * + * Sequence: enable Control **INDICATE** (NOTIFY fallback) → [OnePlusEGlucoseTx] (`0x4e`) → + * continuous EGV loop → optional BackFill (`0x59`) once dex time is known from EGV. + * SessionStart (`0x26`) only reactively if EGV reports Stopped (never auto SessionStop). + * + * Do **not** write TransmitterTime (`0x24`) before/with the first `0x4e`: Juggluco never + * sends `0x24` on ONE+/G7; Ob1 queues TimeTx *after* glucose. Dual/early `0x24` correlated + * with peer GATT status=19 on Samsung. + * + * ⚠️ ASYNC IMPACT: Blocks the calling thread (intended: single bleExecutor). + * [shouldContinue] must flip false and [OnePlusGattClient.disconnect] must run + * (typically from [OnePlusBleSession.stop]) so [OnePlusGattClient.awaitControlNotify] + * unblocks. Do not call dosing / UI work from this loop; only invoke callbacks. + * + * Provenance: Juggluco DexGattCallback.getdatacmd + Ob1G5StateMachine.doGetData + * `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). + */ +class OnePlusEgvSession( + private val gatt: OnePlusGattClient, + private val onWarmup: (OnePlusWarmupState) -> Unit = {}, + private val onGlucose: (OnePlusGlucoseSample) -> Unit = {}, + private val onError: (String, Boolean) -> Unit = { _, _ -> }, + /** + * When true, allow SessionStartTx (0x26) if EGV reports Stopped / SensorStopped. + * Never auto SessionStop. Dex time for Start comes from EGV session age when available. + */ + private val requestNewSensorStart: Boolean = false, +) { + + @Volatile + private var sessionStartAttempted = false + + /** Last transmitter time (seconds). Filled from EGV session age / TimeRx / SessionStartRx. */ + @Volatile + private var lastDexTimeSeconds: Int = 0 + + @Volatile + private var backfillAttempted = false + + /** + * Continuous Control/EGV loop until [shouldContinue] is false or GATT drops. + * + * @param notifyTimeoutMs per-wait for Control indication (Ob1 uses ~10s) + * @param rewriteIntervalMs re-issue EGlucoseTx after idle + */ + fun run( + shouldContinue: () -> Boolean, + notifyTimeoutMs: Long = DEFAULT_NOTIFY_TIMEOUT_MS, + rewriteIntervalMs: Long = DEFAULT_REWRITE_INTERVAL_MS, + ) { + if (!gatt.isConnected()) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: EGV GATT not connected") + onError("ONEPLUS_EGV_NOT_CONNECTED", false) + return + } + + // Control is INDICATE on ONE+/G7. xDrip (same libkeks stack) does setupIndication(Control) + // then writes 0x4E; we previously enabled NOTIFY → transmitter accepted the request but + // could not deliver the EGV indication and terminated the link (peer status 19). Juggluco + // uses NOTIFY, but that is its native stack — libkeks/xDrip is our reference here. + gatt.enableControlIndications() + // Ob1 speakSlowly() — give CCCD write time before Control write. + if (!onePlusSleep(CCCD_SETTLE_MS)) return + + // Juggluco getdatacmd / Ob1 doGetData (G7): Control CCCD → 0x4E only. + var lastWriteMs = 0L + writeEgvRequest(preferShort = true) + lastWriteMs = Clock.System.now().toEpochMilliseconds() + + var preferShort = true + var consecutiveTimeouts = 0 + var triedIndicateFallback = false + + while (shouldContinue() && gatt.isConnected()) { + val now = Clock.System.now().toEpochMilliseconds() + if (now - lastWriteMs >= rewriteIntervalMs) { + writeEgvRequest(preferShort = preferShort) + lastWriteMs = now + } + val packet = gatt.awaitControlNotify(notifyTimeoutMs) + if (!shouldContinue()) break + if (packet == null) { + consecutiveTimeouts++ + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: Control notify timeout ${notifyTimeoutMs}ms " + + "n=$consecutiveTimeouts — re-request EGV", + ) + // After a few short-form misses, try CRC form once (Ob1 length 3). + if (consecutiveTimeouts >= 2) preferShort = false + // Silent NOTIFY accept but no traffic → Ob1 INDICATE. + if (consecutiveTimeouts >= 2 && !triedIndicateFallback) { + triedIndicateFallback = true + try { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: Control quiet after INDICATE — try NOTIFY", + ) + gatt.enableControlNotifications() + onePlusSleep(CCCD_SETTLE_MS) + } catch (t: Throwable) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: Control INDICATE fallback failed: ${t.message}", + ) + } + } + // After prolonged silence with new-sensor request: try SessionStart once (no 0x24). + if (consecutiveTimeouts >= 3 && + requestNewSensorStart && + !sessionStartAttempted && + gatt.isConnected() + ) { + performSessionStart(reason = "egv_timeout_new_start", shouldContinue = shouldContinue) + writeEgvRequest(preferShort = preferShort) + lastWriteMs = Clock.System.now().toEpochMilliseconds() + continue + } + writeEgvRequest(preferShort = preferShort) + lastWriteMs = Clock.System.now().toEpochMilliseconds() + continue + } + consecutiveTimeouts = 0 + preferShort = true + handleControlPacket(packet, shouldContinue) + } + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: Control/EGV loop exit") + } + + /** + * Finite initial poll (useful for tests / one-shot). Prefer [run] after auth in production path. + * + * @return true if at least one Control EGV packet was seen or warm-up reported healthy. + */ + fun runInitialPoll(maxRounds: Int = 6, stepTimeoutMs: Long = 20_000L): Boolean { + if (!gatt.isConnected()) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: EGV GATT not connected") + return false + } + // Control is INDICATE on ONE+/G7 (xDrip libkeks reference); NOTIFY made the peer drop. + gatt.enableControlIndications() + if (!onePlusSleep(CCCD_SETTLE_MS)) return false + // Juggluco/xDrip GET_DATA: 0x4E first (same as [run]). + writeEgvRequest(preferShort = true) + var gotPacket = false + var deliveredGlucose = false + for (round in 0 until maxRounds) { + val preferShort = round % 2 == 0 + if (round > 0) writeEgvRequest(preferShort = preferShort) + val packet = gatt.awaitControlNotify(stepTimeoutMs) ?: continue + gotPacket = true + if (OnePlusSessionStartRx.parse(packet) != null) continue + if (OnePlusSessionStopRx.parse(packet) != null) continue + if (OnePlusTransmitterTimeRx.parse(packet) != null) continue + val parsed = OnePlusGlucoseParser.parseControlPacket(packet) ?: continue + val warmup = OnePlusCalibrationMapper.toWarmupState( + state = parsed.calibration, + sessionAgeSeconds = parsed.sessionAgeSeconds, + ) + onWarmup(warmup) + val sample = parsed.sample + if (parsed.usable && sample != null) { + onGlucose(sample) + deliveredGlucose = true + break + } + if (warmup.phase == OnePlusWarmupState.Phase.WARMING) return true + if (warmup.phase == OnePlusWarmupState.Phase.FAILED) return false + } + return deliveredGlucose || gotPacket + } + + private fun applyTransmitterTime(rx: OnePlusTransmitterTimeRx) { + lastDexTimeSeconds = rx.currentTimeSeconds + val age = rx.sessionAgeSeconds() + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: TransmitterTimeRx current=${rx.currentTimeSeconds} " + + "sessionStart=${rx.sessionStartTimeSeconds} inProgress=${rx.sessionInProgress()} " + + "ageSec=$age status=0x${rx.statusByte.toString(16)}", + ) + if (rx.sessionInProgress()) { + val startMs = rx.realSessionStartEpochMs() + if (startMs != null) { + val warmup = OnePlusWarmupClock.warmingFromStart( + startEpochMs = startMs, + nowMs = Clock.System.now().toEpochMilliseconds(), + message = "tx_time_session", + ) + onWarmup(warmup) + } + } + } + + private fun performSessionStart(reason: String, shouldContinue: () -> Boolean) { + if (sessionStartAttempted) return + sessionStartAttempted = true + if (!gatt.isConnected() || !shouldContinue()) return + + val payload = OnePlusSessionStartTx.build( + dexTimeSeconds = lastDexTimeSeconds, + startTimeEpochMs = Clock.System.now().toEpochMilliseconds(), + ) + try { + gatt.writeControl(payload) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: wrote SessionStartTx opcode=0x26 " + + "dexTime=$lastDexTimeSeconds reason=$reason", + ) + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_SESSION_START_WRITE_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: $msg", t) + onError(msg, false) + return + } + + val packet = gatt.awaitControlNotify(SESSION_START_TIMEOUT_MS) + if (packet == null) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: SessionStartRx timeout — continuing EGV", + ) + return + } + + val rx = OnePlusSessionStartRx.parse(packet) + if (rx == null) { + // Could be an EGV that arrived first — process it and continue. + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: SessionStart await got non-0x27; handling as Control", + ) + handleControlPacket(packet, shouldContinue) + return + } + + if (rx.transmitterTime != 0 && rx.transmitterTime != OnePlusSessionStartRx.INVALID_TIME) { + lastDexTimeSeconds = rx.transmitterTime + } + + when { + rx.isOkay() -> OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: SessionStartRx OK info=${rx.info} msg=${rx.message()} " + + "sessionStart=${rx.sessionStartTime} txTime=${rx.transmitterTime}", + ) + rx.isAlreadyStarted() -> OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: SessionStartRx already started — continuing EGV", + ) + rx.isFubar() -> { + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: SessionStartRx fubar ${rx.message()}", + ) + onError("ONEPLUS_SESSION_START_FUBAR: ${rx.message()}", false) + } + else -> OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: SessionStartRx status=${rx.status} info=${rx.info} " + + "msg=${rx.message()} — continuing EGV", + ) + } + } + + private fun performBackfill(shouldContinue: () -> Boolean) { + if (!shouldContinue() || !gatt.isConnected()) return + try { + OnePlusBackfillSession( + gatt = gatt, + onGlucose = onGlucose, + onError = onError, + ).runOnce( + currentDexTimeSeconds = lastDexTimeSeconds, + shouldContinue = shouldContinue, + ) + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_BACKFILL_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: $msg", t) + onError(msg, false) + } + } + + private fun writeEgvRequest(preferShort: Boolean) { + val payload = if (preferShort) { + OnePlusEGlucoseTx.requestShort() + } else { + OnePlusEGlucoseTx.requestWithCrc() + } + try { + gatt.writeControl(payload) + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: wrote EGlucoseTx short=$preferShort " + + "opcode=0x${(OnePlusEGlucoseTx.OPCODE.toInt() and 0xff).toString(16)}", + ) + } catch (t: Throwable) { + val msg = t.message ?: "ONEPLUS_CONTROL_WRITE_FAILED" + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: $msg", t) + onError(msg, false) + } + } + + private fun handleControlPacket(packet: ByteArray, shouldContinue: () -> Boolean) { + OnePlusTransmitterTimeRx.parse(packet)?.let { rx -> + applyTransmitterTime(rx) + return + } + + OnePlusSessionStopRx.parse(packet)?.let { rx -> + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: late SessionStopRx status=${rx.status} ok=${rx.isOkay()}", + ) + if (rx.transmitterTime != 0) { + lastDexTimeSeconds = rx.transmitterTime + } + return + } + + OnePlusSessionStartRx.parse(packet)?.let { rx -> + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: late SessionStartRx info=${rx.info} msg=${rx.message()}", + ) + if (rx.transmitterTime != 0 && rx.transmitterTime != OnePlusSessionStartRx.INVALID_TIME) { + lastDexTimeSeconds = rx.transmitterTime + } + return + } + + val parsed = OnePlusGlucoseParser.parseControlPacket(packet) + if (parsed == null) { + val op = if (packet.isNotEmpty()) packet[0].toInt() and 0xff else -1 + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: Control packet ignored opcode=0x${op.toString(16)} len=${packet.size}", + ) + return + } + + if (parsed.calibration == OnePlusCalibrationState.Stopped || + parsed.calibration == OnePlusCalibrationState.SensorStopped + ) { + if (requestNewSensorStart && !sessionStartAttempted && shouldContinue()) { + performSessionStart( + reason = "calibration=${parsed.calibration.name}", + shouldContinue = shouldContinue, + ) + } + } + + parsed.sessionAgeSeconds?.takeIf { it > 0 }?.let { age -> + lastDexTimeSeconds = age + } + + val warmup = OnePlusCalibrationMapper.toWarmupState( + state = parsed.calibration, + nowMs = Clock.System.now().toEpochMilliseconds(), + sessionAgeSeconds = parsed.sessionAgeSeconds, + ) + onWarmup(warmup) + + val sample = parsed.sample + if (parsed.usable && sample != null) { + OnePlusLog.d( + "${OnePlusLogMarkers.BG}: mgdl=${sample.mgdl} ts=${sample.timestampMs} " + + "cal=${parsed.calibration.name} op=0x${parsed.opcode.toString(16)} flags=${flagsHex(parsed)}", + ) + onGlucose(sample) + maybeBackfillAfterEgv(shouldContinue) + } else { + OnePlusLog.d( + "${OnePlusLogMarkers.WARMUP}: egv cal=${parsed.calibration.name} usable=false " + + "displayOnly=${parsed.glucoseIsDisplayOnly} flags=${flagsHex(parsed)} " + + "age=${parsed.ageSeconds} sessionAge=${parsed.sessionAgeSeconds}", + ) + } + } + + private fun flagsHex(parsed: OnePlusGlucoseParser.ParsedEgv): String = + parsed.flags?.let { "0x" + it.toString(16).padStart(2, '0') } ?: "-" + + /** Juggluco askbackfill after first glucose when dex time is known. */ + private fun maybeBackfillAfterEgv(shouldContinue: () -> Boolean) { + if (backfillAttempted) return + if (lastDexTimeSeconds < 1) return + backfillAttempted = true + performBackfill(shouldContinue) + } + + companion object { + const val CCCD_SETTLE_MS: Long = 200L + const val DEFAULT_NOTIFY_TIMEOUT_MS: Long = 10_000L + const val DEFAULT_REWRITE_INTERVAL_MS: Long = 5 * 60_000L + const val SESSION_START_TIMEOUT_MS: Long = 15_000L + const val SESSION_STOP_TIMEOUT_MS: Long = 15_000L + /** xDrip `SessionStopTxMessage.postExecuteGuardTime`. */ + const val SESSION_STOP_GUARD_MS: Long = 1_000L + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusInvalidShortPairingCodes.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusInvalidShortPairingCodes.kt new file mode 100644 index 000000000000..6acd16c92f0c --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusInvalidShortPairingCodes.kt @@ -0,0 +1,44 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * G7 / ONE+ short pairing codes rejected by xDrip Direct validation. + * + * Provenance: NightscoutFoundation/xDrip `TxIdHelper.INVALID_SHORT_PAIRING_CODES` + * at pin `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0, JamOrHam). + * See `plugins/dexcom_oneplus/NOTICE`. + */ +internal object OnePlusInvalidShortPairingCodes { + + val codes: Set = setOf( + "0006", "0008", "0009", "0060", "0066", "0068", "0069", "0080", + "0086", "0088", "0089", "0090", "0096", "0098", "0099", "0600", + "0606", "0608", "0609", "0660", "0666", "0668", "0669", "0680", + "0686", "0688", "0689", "0696", "0698", "0699", "0800", "0806", + "0808", "0809", "0860", "0866", "0868", "0869", "0886", "0888", + "0889", "0890", "0896", "0898", "0899", "0900", "0906", "0908", + "0909", "0966", "0968", "0969", "0980", "0986", "0988", "0989", + "0990", "0996", "0998", "0999", "6000", "6006", "6008", "6060", + "6066", "6068", "6069", "6080", "6086", "6088", "6089", "6090", + "6096", "6098", "6099", "6600", "6606", "6608", "6609", "6660", + "6666", "6668", "6669", "6680", "6686", "6688", "6689", "6690", + "6696", "6698", "6800", "6806", "6808", "6809", "6860", "6866", + "6868", "6869", "6880", "6886", "6888", "6890", "6896", "6898", + "6899", "6900", "6906", "6908", "6909", "6960", "6966", "6968", + "6980", "6986", "6988", "6989", "6990", "6996", "6998", "6999", + "8000", "8006", "8009", "8060", "8066", "8068", "8069", "8080", + "8086", "8088", "8089", "8090", "8096", "8098", "8099", "8600", + "8606", "8608", "8609", "8660", "8666", "8668", "8669", "8680", + "8686", "8688", "8689", "8690", "8696", "8699", "8800", "8806", + "8808", "8809", "8860", "8866", "8868", "8869", "8880", "8886", + "8889", "8890", "8896", "8898", "8899", "8900", "8906", "8908", + "8909", "8960", "8966", "8969", "8980", "8986", "8988", "8989", + "8990", "8996", "8998", "8999", "9000", "9008", "9009", "9060", + "9066", "9068", "9069", "9080", "9086", "9088", "9089", "9090", + "9096", "9098", "9099", "9600", "9606", "9608", "9609", "9660", + "9666", "9668", "9669", "9680", "9686", "9688", "9689", "9690", + "9698", "9699", "9800", "9806", "9808", "9809", "9860", "9866", + "9868", "9869", "9880", "9888", "9889", "9890", "9896", "9898", + "9899", "9900", "9906", "9908", "9909", "9960", "9968", "9969", + "9980", "9986", "9988", "9989", "9990", "9996", "9998", "9999", + ) +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCerts.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCerts.kt new file mode 100644 index 000000000000..4b720048509e --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCerts.kt @@ -0,0 +1,82 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import jamorham.keks.Plugin +import kotlin.io.encoding.Base64 +import kotlin.io.encoding.ExperimentalEncodingApi + +/** + * KEKS certificate package from the public xDrip G7/One+/Stelo Auto Configure QR + * (`G7_keks_QR.png` on navid200.github.io/xDrip docs — not the sensor applicator QR). + * + * Ob1 loads Pref `keks_p1`/`keks_p2`/`keks_p3` into [Plugin.setPersistence] channels + * 8/9/10 (PartA/B/C) before the AuthStatus certificate path. Without them, unbonded + * 4-digit pairing throws "Missing QR code". + * + * Provenance: NightscoutFoundation/xDrip guide Auto Configure material. + */ +object OnePlusKeksGuideCerts { + + private val partA: ByteArray by lazy { decode(PART_A_B64) } + private val partB: ByteArray by lazy { decode(PART_B_B64) } + private val partC: ByteArray by lazy { decode(PART_C_B64) } + + /** + * Install guide certs into [plugin]. Safe to call every connect. + * Mirrors Ob1: `setPersistence(7 + i, keks_p{i})` for i in 1..3. + */ + fun install(plugin: Plugin) { + plugin.setPersistence(8, partA.copyOf()) + plugin.setPersistence(9, partB.copyOf()) + plugin.setPersistence(10, partC.copyOf()) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS guide certs installed " + + "p1=${partA.size}b p2=${partB.size}b p3=${partC.size}b", + ) + } + + /** + * The same bytes `android.util.Base64.decode(b64, Base64.DEFAULT)` gave. + * + * The three values below are split across source lines for reading, but they are joined at + * compile time and hold no line separator at all, so the one way the two decoders differ - + * Android's DEFAULT skips line breaks, the Kotlin one refuses them - cannot be reached by + * anything here. Padding is not a difference either: part A ends in + * a single `=` and the other two are a whole number of three byte groups, so both decoders + * read all three the same way. A certificate that decoded to the wrong length would still + * look like a certificate, and the sensor would be the only thing to say otherwise, after a + * failed pairing - so `OnePlusKeksGuideCertsTest` holds [install] against the three sizes + * 494, 465 and 138 instead. + */ + @OptIn(ExperimentalEncodingApi::class) + private fun decode(b64: String): ByteArray = Base64.Default.decode(b64) + + private val PART_A_B64: String = + "MIIB6jCCAY+gAwIBAgIULzxStusIcBBG1F14zoF4TJ3+UkAwCgYIKoZIzj0EAwIwEzERMA8GA1UE" + + "AwwIREVYMDBQRzEwHhcNMjAxMDMwMTU1OTA0WhcNMzUxMDI3MTU1OTA0WjATMREwDwYDVQQDDAhE" + + "RVgwM1BHMTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPsayiHYruyaTrUfhTBJU9l3oa1Wl5kl" + + "D/hjmH9Co82fpP9XHrVovGw5YnfD3LUd7a7oVRPIClxENVOKGfWpY0ijgcAwgb0wDwYDVR0TAQH/" + + "BAUwAwEB/zAfBgNVHSMEGDAWgBSeDx428/J2pwH+jog6biamNb1q/DBaBgNVHR8EUzBRME+gNKAy" + + "hjBodHRwOi8vY3JsLmRwLnNhYXMucHJpbWVrZXkuY29tL2NybC9ERVgwMFBHMS5jcmyiF6QVMBMx" + + "ETAPBgNVBAMMCERFWDAwUEcxMB0GA1UdDgQWBBSI9h6BvEsX8FxrG+KZHWAIfM7deTAOBgNVHQ8B" + + "Af8EBAMCAYYwCgYIKoZIzj0EAwIDSQAwRgIhAKppzYl+xmOvX54VgYffaFH/B1bwDEAWJFZPgaGf" + + "WgeFAiEA2uu5/bFjtzHrBmHxwKGTKHGlDjma0cb1Geq9TJ57oBM=" + + private val PART_B_B64: String = + "MIIBzTCCAXSgAwIBAgIUGQUvzBdTC/pW5J3K/NrPhTzlunMwCgYIKoZIzj0EAwIwEzERMA8GA1UE" + + "AwwIREVYMDNQRzEwHhcNMjMwNDE0MTAyODE0WhcNMjUwNDEzMTAyODEzWjA6MTgwNgYDVQQDDC8w" + + "MSwwMDAwLDAzMDBMUUVDQ3pBQkF3QUEsY2lvaWUzVmJRMmhsWk1qZFVtNXJnQTBZMBMGByqGSM49" + + "AgEGCCqGSM49AwEHA0IABFEYw16eQefgZU/ugBxSqcXfxRDvCVl9XMqEYeSvnGZnFINPK8kD8W+r" + + "/EV1WwGD8aCXRc3/y04veZ5QvtmmtYyjfzB9MAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAUiPYe" + + "gbxLF/BcaxvimR1gCHzO3XkwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMB0GA1UdDgQW" + + "BBTTCedcByVBLXp5IuOqz7J/fr1r4DAOBgNVHQ8BAf8EBAMCBaAwCgYIKoZIzj0EAwIDRwAwRAIg" + + "SNSGjPOT2QRBAbbwf9aNfwZCgF+F2nTi/p3o3TUH8CcCIBzRv3xsft1ZQ14ySSX88OuzyuIRDXlA" + + "fHeqO5O3vATL" + + private val PART_C_B64: String = + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgAHz71Zb250R3uMDp9vehdCdeEB72" + + "v30YyvARgdEntXmhRANCAARRGMNenkHn4GVP7oAcUqnF38UQ7wlZfVzKhGHkr5xmZxSDTyvJA/Fv" + + "q/xFdVsBg/Ggl0XN/8tOL3meUL7ZprWM" + +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiter.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiter.kt new file mode 100644 index 000000000000..69404f4f3643 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusMacArbiter.kt @@ -0,0 +1,88 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers + +/** + * Gives the physical sensor an owner. + * + * The dual-slot design separates everything that can be separated — store namespace, executor, + * driver instance — and the one thing it cannot separate is the transmitter itself. Two slots on one + * MAC means two `BluetoothGatt` clients over a single ACL link, both subscribed to the same Auth and + * ExtraData characteristics, so each receives the other's notifications and the sensor sees one + * interleaved stream of two KEKS handshakes. The field log of 2026-08-25 shows both sides dying + * inside libkeks 1.6 s after the second connect, on a handshake that had just reported + * `authenticated=1`. It is not a race that sometimes bites; it is certain. + * + * Why a process-wide claim and not only a check at the two UI entry points: the entry points are not + * the only way in. `resumeStoredSession` runs for both slots on every plugin start, and for an + * install whose two stores already hold the same MAC — the state a phone is left in by the very bug + * above — that reproduced the collision on every launch with no UI involved. A claim taken where the + * connection is actually made covers those paths, and the ones not written yet. + * + * An owner may re-claim what it already holds: reconnects and repairs inside one slot are normal, and + * claiming a different MAC releases the owner's previous claim. + * + * ⚠️ The owner token must **not** be the driver's slot name ("prod" / "staging"). `OnePlusCgmDriverReal` + * keeps its slot name for the whole life of the instance, on purpose, so a bug report stays readable + * across a promotion — a promoted instance is production but still calls itself "staging" in the log. + * Keying the map on that name would let the next pre-soak's `claim` remove the promoted instance's own + * claim (see the "moving to another releases the old one" rule below), silently dropping the arbiter's + * protection on the sensor that is still feeding the loop. Each driver instance passes a token of its + * own instead — see `OnePlusCgmDriverReal.arbiterOwner`. + */ +object OnePlusMacArbiter { + + private val lock = AapsLock() + + /** Normalised MAC → the token of the driver instance that owns it. At most one owner per transmitter. */ + private val owners = mutableMapOf() + + private fun normalize(mac: String): String = mac.trim().uppercase() + + /** + * Take ownership of [mac] for [owner]. + * + * @param owner a token that belongs to one driver instance and never changes — see the note on + * promotion above. + * @return true when that driver may connect. false means another driver instance holds this + * transmitter and the caller must not open a session on it. + */ + fun claim(mac: String, owner: String): Boolean { + val key = normalize(mac).takeIf { it.isNotEmpty() } ?: return false + lock.withLock { + val current = owners[key] + if (current != null && current != owner) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$owner] MAC claim refused — ***${key.takeLast(5)} " + + "is held by [$current]; two sessions on one sensor corrupt the KEKS handshake", + ) + return false + } + // One driver instance holds one transmitter at a time: moving to another releases the old one. + owners.entries.removeAll { it.value == owner && it.key != key } + owners[key] = owner + return true + } + } + + /** Give up whatever [owner] holds. Safe when it holds nothing. */ + fun release(owner: String) { + lock.withLock { + owners.entries.removeAll { it.value == owner } + } + } + + /** Which owner holds [mac], or null when nobody does. */ + fun ownerOf(mac: String): String? { + val key = normalize(mac).takeIf { it.isNotEmpty() } ?: return null + return lock.withLock { owners[key] } + } + + /** Test hook: forget every claim. */ + fun reset() { + lock.withLock { owners.clear() } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt new file mode 100644 index 000000000000..74b1765424df --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt @@ -0,0 +1,47 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * Session authentication / J-PAKE key exchange. + * + * Production path: [OnePlusSessionAuthKeks] via `:plugins:libkeks` (GPL-3 xDrip pin). Both are + * shared code; only OS bonding is platform specific, behind [app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient]. + * **No proprietary Dexcom secrets or hard-coded session keys belong in this module.** + */ +interface OnePlusSessionAuth { + /** + * Runs auth after GATT connect. Returns success/failure without throwing for expected auth fails. + * + * @param savedSharedKey optional 16-byte key from a prior session (libkeks channel 2 / + * Juggluco reconnect short path). When present and Android-bonded, Round1–3 are skipped. + */ + fun authenticate(pairingCode: String, savedSharedKey: ByteArray? = null): AuthResult +} + +data class AuthResult( + val ok: Boolean, + val message: String? = null, + /** 16-byte KEKS shared key when [ok] — persist for reconnect short-auth. */ + val sharedKey: ByteArray? = null, + /** + * Juggluco-style: wipe persisted shared key before the next attempt + * (short-auth rejected / bond failure / missing certs). + */ + val invalidateSharedKey: Boolean = false, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is AuthResult) return false + return ok == other.ok && + message == other.message && + sharedKey.contentEquals(other.sharedKey) && + invalidateSharedKey == other.invalidateSharedKey + } + + override fun hashCode(): Int { + var result = ok.hashCode() + result = 31 * result + (message?.hashCode() ?: 0) + result = 31 * result + (sharedKey?.contentHashCode() ?: 0) + result = 31 * result + invalidateSharedKey.hashCode() + return result + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt new file mode 100644 index 000000000000..021ee780baca --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt @@ -0,0 +1,381 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusLog +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusKeksNotifySource +import jamorham.keks.Plugin +import jamorham.keks.crypto.KeksArrayIndexOutOfBoundsException +import jamorham.keks.crypto.KeksInvalidParameterException +import jamorham.keks.crypto.KeksSecurityException + +/** + * KEKS (libkeks) handshake driver over [OnePlusGattClient]. + * + * Provenance: NightscoutFoundation/xDrip libkeks at the pin in plugins/libkeks/NOTICE (GPL-3.0) via `:plugins:libkeks`. + * Pump loop mirrors Ob1 `Ob1G5StateMachine.doNext` + Juggluco reconnect short-auth: + * - Install guide certs + optional saved shared key (persistence channel 2) + * - When bonded + saved key, libkeks skips Round1–3 (`aNext` → RequestAuth) + * - Bond via [OnePlusGattClient.awaitBondComplete] (CCCD teardown while BONDING) + * - Success only when Ob1 would enter GET_DATA (`aNext` length==1) + * + * Juggluco recovery (ChallengeReply): if AuthStatus `authenticated != 1`, wipe persisted key + * ([AuthResult.invalidateSharedKey]) and clear the in-memory [jamorham.keks.Context.savedKey] and + * the singleton, so the next attempt runs full J-PAKE. Soft recovery: do **not** [OnePlusGattClient.removeBond] on the + * first short-auth reject (preload path) — forced unbond correlated with ADV blackout on Samsung. + * Unbond only after a full J-PAKE AuthStatus reject while still OS-bonded, or on bond=3. + * + * ## Shared code + * + * This class is in commonMain, like `:plugins:libkeks`. The three exception types it catches come + * from `jamorham.keks.crypto` for that reason: on Android they are still `java.lang.SecurityException`, + * `java.security.InvalidParameterException` and `java.lang.ArrayIndexOutOfBoundsException`, so + * nothing changed there. + * + * The sensor asks for a bond in the middle of an **unbonded** four-digit pairing, and + * `requestAndroidBond` answers it through [OnePlusGattClient.createBond] and + * [OnePlusGattClient.awaitBondComplete]. On platforms without a pairing API the GATT client may + * return true there and let the OS pair on the next encrypted operation. A reconnect with a saved + * shared key does not pass through `requestAndroidBond` at all. + * + * ⚠️ ASYNC IMPACT: blocks caller (bleExecutor) on [OnePlusGattClient.awaitKeksNotify] and + * [OnePlusGattClient.awaitBondComplete]. Do not call from main. + */ +class OnePlusSessionAuthKeks( + private val gatt: OnePlusGattClient, + private val stepTimeoutMs: Long = 15_000L, + /** Many 20-byte ExtraData chunks per 160-byte round (×3) plus Auth challenge / AuthStatus. */ + private val maxSteps: Int = 96, + private val bondWaitMs: Long = 45_000L, +) : OnePlusSessionAuth { + + override fun authenticate(pairingCode: String, savedSharedKey: ByteArray?): AuthResult { + if (!gatt.isConnected()) { + return AuthResult(ok = false, message = "ONEPLUS_AUTH: GATT not connected") + } + // Drop singleton KEKS state left by a prior ChallengeReply / getPersistence — + // otherwise RoundStart still sees context.savedKey and short-auths (auth=2) even when + // AAPS preload=false (seen on Samsung after reconnect). + forceFreshKeksInstance(pairingCode) + val plugin = Plugin.getInstance(pairingCode) + plugin.context.reset() + // Ob1: Pref keks_p1..p3 → setPersistence(8..10) before handshake (xDrip Auto Configure QR). + OnePlusKeksGuideCerts.install(plugin) + + val preload = savedSharedKey?.takeIf { it.size == 16 } + val usedShortAuthPreload = preload != null + if (preload != null) { + plugin.setPersistence(2, preload.copyOf()) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS saved shared key preloaded " + + "bonded=${gatt.isBonded()} (short-auth path if RoundStart)", + ) + } else { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS full J-PAKE path " + + "(no preload, in-memory key cleared) bonded=${gatt.isBonded()}", + ) + } + + plugin.amConnected() + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS amConnected bonded=${gatt.isBonded()} " + + "preload=${usedShortAuthPreload} savedKeyInCtx=${plugin.context.savedKey != null}", + ) + + // Ob1: first doNext after Auth CCCD setup (connect already enabled CCCDs). + emitANext(plugin)?.let { return finalizeAuthResult(it, plugin) } + + var sawSharedKey = false + repeat(maxSteps) { step -> + if (!gatt.isConnected()) { + return finalizeAuthResult( + AuthResult(ok = false, message = "ONEPLUS_AUTH: GATT disconnected"), + plugin, + ) + } + + val notify = gatt.awaitKeksNotify(stepTimeoutMs) + ?: return finalizeAuthResult( + AuthResult(ok = false, message = "ONEPLUS_AUTH: notify timeout step=$step"), + plugin, + ) + + if (plugin.bondNow(notify.payload)) { + val bondOk = requestAndroidBond() + if (!bondOk) { + return finalizeAuthResult( + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: Android bond required / timed out — accept pairing prompt", + ), + plugin, + ) + } + // TIME_EXTENDED is the bond trigger and leaves libkeks in GET_DATA. It is not a + // response consumed by receivedResponse(GET_DATA), so advance immediately instead + // of waiting for a notification the transmitter will never send. + emitANext(plugin)?.let { return finalizeAuthResult(it, plugin) } + return@repeat + } + + if (notify.source == OnePlusKeksNotifySource.AUTHENTICATION) { + evaluateAuthStatus(notify.payload, usedShortAuthPreload)?.let { + return finalizeAuthResult(it, plugin) + } + } + + val shouldEmit = try { + when (notify.source) { + OnePlusKeksNotifySource.AUTHENTICATION -> plugin.receivedResponse(notify.payload) + OnePlusKeksNotifySource.EXTRA_DATA -> plugin.receivedData(notify.payload) + } + } catch (se: KeksSecurityException) { + return finalizeAuthResult( + AuthResult(ok = false, message = "ONEPLUS_AUTH: ${se.message}"), + plugin, + ) + } catch (ipe: KeksInvalidParameterException) { + return finalizeAuthResult( + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: ${ipe.message}", + invalidateSharedKey = ipe.message?.contains("Missing QR", ignoreCase = true) == true, + ), + plugin, + ) + } catch (aioobe: KeksArrayIndexOutOfBoundsException) { + // libkeks `Calc.challenger` copies 16 bytes from offset 2 with no length check, so a + // short packet where a challenge was expected throws instead of failing auth. The + // field log of 2026-08-25 hit this with a 3-byte AuthStatus arriving mid-handshake. + // Upstream is vendored third party and stays untouched: the wrapper turns it into an + // auth failure so the session retry machinery takes over. + return finalizeAuthResult( + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS short packet ${aioobe.message} (out-of-step handshake)", + ), + plugin, + ) + } catch (ise: IllegalStateException) { + // "Invalid result" from validateZeroKnowledgeProof: the round-1 packet did not + // decode to a point on the curve. BouncyCastle raised this on Android and the + // shared `KeksP256.multiply` keeps the same check and the same message. Same root + // cause as above — bytes from another handshake — and same treatment. + return finalizeAuthResult( + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS proof rejected ${ise.message} (out-of-step handshake)", + ), + plugin, + ) + } catch (npe: NullPointerException) { + return finalizeAuthResult( + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS NPE ${npe.message} (incomplete round state)", + ), + plugin, + ) + } + + if (shouldEmit) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: KEKS emit after ${notify.source} " + + "${notify.payload.size}b step=$step", + ) + emitANext(plugin)?.let { return finalizeAuthResult(it, plugin) } + } + + // Only probe persistence after auth is progressing — getPersistence(1) can *create* + // context.savedKey via getShortSharedKey and poison the next RoundStart. + if (!sawSharedKey && plugin.context.savedKey != null) { + sawSharedKey = true + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS context.savedKey present " + + "(${plugin.context.savedKey!!.size}b) step=$step", + ) + } + } + + return finalizeAuthResult( + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS handshake incomplete after $maxSteps steps " + + "(sharedKey=$sawSharedKey; need AuthStatus→GET_DATA)", + ), + plugin, + ) + } + + /** + * libkeks [Plugin.setPersistence] channel 3/4 nulls the singleton so the next + * [Plugin.getInstance] allocates a clean Context (no leftover savedKey / Round3). + */ + private fun forceFreshKeksInstance(pairingCode: String) { + try { + val stale = Plugin.getInstance(pairingCode) + stale.context.reset() + stale.setPersistence(3, ByteArray(0)) + } catch (_: Throwable) { + // Best-effort — getInstance below still runs. + } + } + + /** On failure, wipe in-memory KEKS key so the next attempt cannot short-auth on garbage. */ + private fun finalizeAuthResult(result: AuthResult, plugin: Plugin): AuthResult { + if (!result.ok) { + try { + plugin.context.reset() + } catch (_: Throwable) { + } + } + return result + } + + /** + * Juggluco ChallengeReply: `auth != 1` → wipe key and force full J-PAKE next. + * Soft path (short-auth / preload): keep OS bond — removeBond after auth=2 caused ADV silence. + * Hard path (full J-PAKE still rejected while bonded, or bond=3): then removeBond. + */ + private fun evaluateAuthStatus( + payload: ByteArray, + usedShortAuthPreload: Boolean, + ): AuthResult? { + val status = OnePlusAuthStatusRx.parse(payload) ?: return null + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: AuthStatus authenticated=${status.authenticated} " + + "bonded=${status.bonded} localBonded=${gatt.isBonded()} preload=$usedShortAuthPreload", + ) + + if (status.needsKeyRefresh) { + dropOsBondIfPresent("bond=3 key refresh") + return AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS bond failure / key refresh required (bond=3)", + invalidateSharedKey = true, + ) + } + + if (!status.isAuthenticated) { + // Short-auth with stale/wrong key (typical Samsung: auth=2 bonded=1 after EGV drop). + // Soft recovery: wipe key only → next connect full J-PAKE while bond may remain. + // Hard recovery: full J-PAKE already failed with local bond → removeBond. + val viaShort = usedShortAuthPreload + if (viaShort) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: soft key refresh after short-auth " + + "auth=${status.authenticated} — keep OS bond, full J-PAKE next", + ) + } else { + dropOsBondIfPresent("full-pair auth=${status.authenticated}") + } + OnePlusLog.e( + "${OnePlusLogMarkers.ERROR}: AuthStatus rejected authenticated=${status.authenticated} " + + "(need ${OnePlusAuthStatusRx.AUTHENTICATED_OK}) " + + if (viaShort) "— soft short-auth key refresh (no removeBond)" + else "— full-pair auth failed", + ) + return AuthResult( + ok = false, + message = if (viaShort) { + "ONEPLUS_AUTH: KEKS short-auth rejected auth=${status.authenticated} — key refresh required" + } else { + "ONEPLUS_AUTH: KEKS AuthStatus rejected auth=${status.authenticated}" + }, + invalidateSharedKey = true, + ) + } + + // auth==1: do NOT createBond here. Ob1/Juggluco bond only on inbound TIME_EXTENDED + // (bondNow). Early createBond on bonded=2 caused GATT status=19 before Pairing write. + return null + } + + /** + * Ob1 `doNext` write side. Returns a terminal [AuthResult] when handshake ends; + * null means continue waiting for notifies. + */ + private fun emitANext(plugin: Plugin): AuthResult? { + val next = try { + plugin.aNext() + } catch (npe: NullPointerException) { + return AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS aNext NPE ${npe.message}", + ) + } + if (next == null) { + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: KEKS aNext null — wait for more notifies", + ) + return null + } + return when (next.size) { + 1 -> { + // Ob1: length==1 → auth complete (GET_DATA). Do not write GETDATA here — + // Control/EGV path owns post-auth traffic. + val key = plugin.getPersistence(1) + val keyBytes = if (key != null && key.isNotEmpty()) key.size else 0 + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: KEKS auth complete (aNext length=1, key=${keyBytes}b)", + ) + if (keyBytes == 0) { + AuthResult(ok = false, message = "ONEPLUS_AUTH: GET_DATA without shared key") + } else { + AuthResult(ok = true, message = "keks_ok", sharedKey = key!!.copyOf()) + } + } + 3 -> { + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: KEKS bond failure / key refresh required", + invalidateSharedKey = true, + ) + } + else -> { + // Ob1 doNext: ExtraData chunks first (NO_RESPONSE), then Auth (DEFAULT). + // Includes AuthChallenge (0x04) and TIME_EXTENDED after AuthStatus paths. + if (next.isNotEmpty()) { + gatt.writeExtraData(next.getOrNull(1)) + gatt.writeAuthentication(next.getOrNull(0)) + } + null + } + } + } + + private fun requestAndroidBond(): Boolean { + if (gatt.isBonded()) return true + return try { + if (!gatt.createBond()) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: createBond returned false") + return false + } + // Juggluco: BroadcastReceiver + CCCD teardown/restore (not a bare isBonded poll). + gatt.awaitBondComplete(bondWaitMs) + } catch (t: Throwable) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: createBond ${t.message}", t) + false + } + } + + /** + * Hard recovery only: drop OS bond after full-pair AuthStatus reject or bond=3. + * Not used on first short-auth reject (see [evaluateAuthStatus] soft path). + * + * ⚠️ ASYNC IMPACT: [OnePlusGattClient.removeBond] may disconnect GATT and silence ADV briefly. + */ + private fun dropOsBondIfPresent(reason: String) { + if (!gatt.isBonded()) return + val ok = try { + gatt.removeBond() + } catch (t: Throwable) { + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: removeBond $reason ${t.message}", t) + false + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: Juggluco-style removeBond after $reason ok=$ok", + ) + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStart.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStart.kt new file mode 100644 index 000000000000..4084aee601e2 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStart.kt @@ -0,0 +1,32 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * Native session start from pairing code. + * Pure validation helpers live here; BLE side effects stay in [OnePlusBleSession]. + * + * Short-code rules align with xDrip `TxIdHelper.isValidShortPairingCode` at the xDrip pin in NOTICE + * (GPL-3.0) — see [OnePlusInvalidShortPairingCodes]. + */ +object OnePlusSessionStart { + + /** Dexcom ONE+ / G7 applicator codes are 4 decimal digits in xDrip Direct UX. */ + const val EXPECTED_CODE_LENGTH: Int = 4 + + fun normalizePairingCode(raw: String): String = raw.trim() + + fun isValidPairingCode(raw: String): Boolean { + val code = normalizePairingCode(raw) + if (code.length != EXPECTED_CODE_LENGTH) return false + if (!code.all { it.isDigit() }) return false + return code !in OnePlusInvalidShortPairingCodes.codes + } + + fun validationError(raw: String): String? { + if (isValidPairingCode(raw)) return null + val code = normalizePairingCode(raw) + if (code.length != EXPECTED_CODE_LENGTH || !code.all { it.isDigit() }) { + return "ONEPLUS_PAIR_CODE_INVALID: expect $EXPECTED_CODE_LENGTH digits" + } + return "ONEPLUS_PAIR_CODE_INVALID: reserved / invalid short code" + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicy.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicy.kt new file mode 100644 index 000000000000..9ffbab4260c2 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionStartPolicy.kt @@ -0,0 +1,32 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * Pure policy for Control SessionStart after TransmitterTime (Dexcom-safe). + * + * Never auto SessionStop — stopping the transmitter session can prevent recovery + * in the official Dexcom app. + */ +object OnePlusSessionStartPolicy { + + enum class Action { + /** Transmitter already has a session — EGV/backfill only. */ + AttachOnly, + + /** No session yet — send SessionStartTx 0x26. */ + SessionStart, + + /** No session and start not requested — EGV only. */ + EgvOnly, + } + + fun decide(requestNewSensorStart: Boolean, sessionAlreadyInProgress: Boolean): Action = + when { + sessionAlreadyInProgress -> Action.AttachOnly + requestNewSensorStart -> Action.SessionStart + else -> Action.EgvOnly + } + + /** Reconnect attempts must never re-issue SessionStart. */ + fun wantSessionStartOnAttempt(requestNewSensorStart: Boolean, attempt: Int): Boolean = + requestNewSensorStart && attempt == 0 +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClock.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClock.kt new file mode 100644 index 000000000000..568bb191e0e6 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/warmup/OnePlusWarmupClock.kt @@ -0,0 +1,43 @@ +package app.aaps.plugins.dexcomoneplus.warmup + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState + +/** + * Pure warm-up helpers for protocol / UI (~30 min factory warm-up, Q12). + * Prefer protocol-reported [OnePlusWarmupState.remainingMs] when the stack provides it. + */ +object OnePlusWarmupClock { + + /** Factory default warm-up duration used when estimating locally. */ + const val DEFAULT_WARMUP_MS: Long = 30L * 60L * 1000L + + /** + * Remaining ms from explicit fields; does not invent a local 30 min clock. + * Order: [remainingMs] → [endsAtEpochMs] − now → null. + */ + fun resolveRemainingMs(state: OnePlusWarmupState, nowMs: Long): Long? { + state.remainingMs?.let { return it.coerceAtLeast(0L) } + val endsAt = state.endsAtEpochMs ?: return null + return (endsAt - nowMs).coerceAtLeast(0L) + } + + /** + * Builds a WARMING state from session start + duration (estimate until protocol clock exists). + */ + fun warmingFromStart( + startEpochMs: Long, + durationMs: Long = DEFAULT_WARMUP_MS, + nowMs: Long, + message: String? = null, + ): OnePlusWarmupState { + val endsAt = startEpochMs + durationMs + val remaining = (endsAt - nowMs).coerceAtLeast(0L) + val phase = if (remaining <= 0L) OnePlusWarmupState.Phase.READY else OnePlusWarmupState.Phase.WARMING + return OnePlusWarmupState( + phase = phase, + remainingMs = if (phase == OnePlusWarmupState.Phase.READY) 0L else remaining, + endsAtEpochMs = endsAt, + message = message, + ) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorTest.kt new file mode 100644 index 000000000000..1308fdd29485 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusBleExecutorTest.kt @@ -0,0 +1,115 @@ +package app.aaps.plugins.dexcomoneplus + +import kotlin.concurrent.Volatile +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * The driver's one thread. + * + * This is in `commonTest` on purpose, so every platform's executor runs it. An executor that + * queues work and never runs it would look exactly like a sensor that is simply never found. + */ +class OnePlusBleExecutorTest { + + @Test + fun `a queued block really runs on another thread`() { + val executor = onePlusBleExecutor() + val flag = Flag() + executor.execute { flag.set() } + assertTrue(flag.awaitUpTo(WAIT_MS), "the executor never ran the block") + executor.shutdownNow() + } + + @Test + fun `blocks run one after the other and in order`() { + val executor = onePlusBleExecutor() + val order = Order() + val done = Flag() + executor.execute { + // Hold the thread, so a second executor thread would be visible as a wrong order. + onePlusSleep(50L) + order.append("first") + } + executor.execute { order.append("second") } + executor.execute { + order.append("third") + done.set() + } + assertTrue(done.awaitUpTo(WAIT_MS), "the executor never reached the last block") + assertEquals("first,second,third", order.text()) + executor.shutdownNow() + } + + @Test + fun `a stopped executor refuses new work`() { + val executor = onePlusBleExecutor() + executor.shutdownNow() + try { + executor.execute { fail("a stopped executor ran a block") } + fail("a stopped executor accepted a block") + } catch (_: Throwable) { + // The JVM throws RejectedExecutionException; another platform may throw another type. + // The driver catches it either way; what matters is that it is not silent. + } + } + + @Test + fun `a block queued before the stop does not run after it`() { + val executor = onePlusBleExecutor() + val blocking = Flag() + val second = Flag() + executor.execute { + blocking.set() + onePlusSleep(200L) + } + executor.execute { second.set() } + assertTrue(blocking.awaitUpTo(WAIT_MS), "the executor never started the first block") + executor.shutdownNow() + onePlusSleep(400L) + assertFalse(second.hasRun(), "a block queued before the stop still ran after it") + } + + private class Flag { + + @Volatile + private var done = false + + fun set() { + done = true + } + + fun hasRun(): Boolean = done + + fun awaitUpTo(millis: Long): Boolean { + var left = millis + while (left > 0L && !done) { + onePlusSleep(POLL_MS) + left -= POLL_MS + } + return done + } + } + + /** Written only from the executor's own thread, read after it has finished. */ + private class Order { + + @Volatile + private var value = "" + + fun append(step: String) { + value = if (value.isEmpty()) step else "$value,$step" + } + + fun text(): String = value + } + + private companion object { + + const val WAIT_MS = 5_000L + const val POLL_MS = 10L + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt new file mode 100644 index 000000000000..fa99c9c84dca --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt @@ -0,0 +1,181 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub +import app.aaps.plugins.dexcomoneplus.session.OnePlusCpuLease +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The real driver's own state, run on every platform the module builds for. + * + * Nothing here needs a radio: it is the part of the driver that decides. + * The three things the move replaced - the lock, the counter and the clock - are all exercised. + * + * No test here connects. The fake platform's GATT client throws if it is ever asked for, so a test + * that started a session by accident would say so instead of hanging on a radio that is not there. + */ +class OnePlusCgmDriverRealSharedTest { + + @Test + fun `a fresh driver has no session and no store`() { + val driver = OnePlusCgmDriverReal() + assertNull(driver.sensorStore()) + assertFalse(driver.isSessionUp()) + assertEquals(OnePlusWarmupState.Phase.IDLE, driver.warmupState().phase) + driver.shutdown() + } + + @Test + fun `attach gives the slot its own store file`() { + val platform = FakePlatform() + val production = OnePlusCgmDriverReal() + val staging = OnePlusCgmDriverReal(storeNamespace = "staging") + production.attach(platform) + staging.attach(platform) + assertNotNull(production.sensorStore()) + assertNotNull(staging.sensorStore()) + assertEquals( + listOf( + OnePlusSensorStore.prefsFileName(null), + OnePlusSensorStore.prefsFileName("staging"), + ), + platform.prefsAsked, + ) + production.shutdown() + staging.shutdown() + } + + @Test + fun `a promotion points the instance at the production file under its own link`() { + val platform = FakePlatform() + val staging = OnePlusCgmDriverReal(storeNamespace = "staging") + staging.attach(platform) + staging.saveIdentity(OnePlusSensorIdentity(pin = "1234")) + staging.rebindStore(null) + assertEquals(OnePlusSensorStore.prefsFileName(null), platform.prefsAsked.last()) + // The production file is a different file, so the staging PIN is not in it. + assertNull(staging.sensorStore()?.load()?.identity?.pin) + staging.shutdown() + } + + @Test + fun `nothing is resumed when the store is empty`() { + val driver = OnePlusCgmDriverReal() + driver.attach(FakePlatform()) + assertFalse(driver.resumeStoredSession()) + driver.shutdown() + } + + @Test + fun `nothing is resumed when the stored session has no key`() { + val platform = FakePlatform() + val driver = OnePlusCgmDriverReal() + driver.attach(platform) + driver.saveIdentity(OnePlusSensorIdentity(pin = "1234")) + driver.sensorStore()?.saveLastMac("AA:BB:CC:DD:EE:FF") + assertFalse(driver.resumeStoredSession()) + driver.shutdown() + } + + @Test + fun `scan start and stop reach the scanner`() { + val platform = FakePlatform() + val driver = OnePlusCgmDriverReal() + driver.attach(platform) + driver.startScan { } + assertTrue(platform.scanner.isScanning()) + driver.stopScan() + assertFalse(platform.scanner.isScanning()) + driver.shutdown() + } + + @Test + fun `shutdown can be called twice`() { + val driver = OnePlusCgmDriverReal() + driver.attach(FakePlatform()) + driver.shutdown() + driver.shutdown() + assertFalse(driver.isSessionUp()) + } + + /** A host with a store and a scanner, and nothing that needs a radio. */ + private class FakePlatform : OnePlusPlatform { + + val prefsAsked = mutableListOf() + val scanner = OnePlusBleScannerStub() + private val files = mutableMapOf() + + override fun sensorPrefs(fileName: String): OnePlusSensorPrefs { + prefsAsked += fileName + return files.getOrPut(fileName) { FakePrefs() } + } + + override fun scanner(hint: OnePlusStoredSession?, slot: String): OnePlusBleScanner = scanner + + override fun gattClient(profile: OemDeviceProfile): OnePlusGattClient = + throw IllegalStateException("a test asked for a GATT client; no test here connects") + + override fun cpuLease(slot: String): OnePlusCpuLease = NoLease + + private object NoLease : OnePlusCpuLease { + + override fun hold(maxMillis: Long): OnePlusCpuLease.Hold? = null + } + } + + /** In memory [OnePlusSensorPrefs]. A null string removes the key, as the real ones do. */ + private class FakePrefs : OnePlusSensorPrefs { + + private val values = mutableMapOf() + + override fun getString(key: String): String? = values[key] as? String + + override fun getLong(key: String, defaultValue: Long): Long = values[key] as? Long ?: defaultValue + + override fun getInt(key: String, defaultValue: Int): Int = values[key] as? Int ?: defaultValue + + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = + values[key] as? Boolean ?: defaultValue + + override fun contains(key: String): Boolean = values.containsKey(key) + + override fun edit(block: OnePlusSensorPrefs.Editor.() -> Unit) { + object : OnePlusSensorPrefs.Editor { + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + + override fun putLong(key: String, value: Long) { + values[key] = value + } + + override fun putInt(key: String, value: Int) { + values[key] = value + } + + override fun putBoolean(key: String, value: Boolean) { + values[key] = value + } + + override fun remove(key: String) { + values.remove(key) + } + + override fun clear() { + values.clear() + } + }.block() + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt new file mode 100644 index 000000000000..ade1593972d6 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt @@ -0,0 +1,130 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * The shared replacement for `java.nio.ByteBuffer`, run on every target this module builds for. + * + * It lives in commonTest and not beside the other packet tests on purpose: these bytes go on the + * wire to a sensor, so they have to be proved on every target, and integer shifts are exactly the + * kind of thing that can differ between two compilers. + * + * Test names here carry no comma: Kotlin/Native rejects one inside a backtick quoted name. + */ +class OnePlusBytesTest { + + @Test + fun `the writer puts multi byte fields little endian`() { + val writer = OnePlusByteWriter(9) + writer.put(0x34) + writer.putShort(150) + writer.putInt(0x01020304) + + assertEquals("34" + "9600" + "04030201" + "0000", writer.array().onePlusToHex()) + } + + @Test + fun `bytes never written stay zero`() { + val writer = OnePlusByteWriter(4) + writer.put(0x01) + + assertEquals("01000000", writer.array().onePlusToHex()) + } + + @Test + fun `the reader reads back what the writer wrote`() { + val writer = OnePlusByteWriter(7) + writer.put(-1) + writer.putShort(-2) + writer.putInt(-3) + + val reader = OnePlusByteReader(writer.array()) + assertEquals((-1).toByte(), reader.byte()) + assertEquals((-2).toShort(), reader.short()) + assertEquals(-3, reader.int()) + assertEquals(0, reader.remaining) + } + + @Test + fun `an unsigned byte is read as zero to 255`() { + val reader = OnePlusByteReader(byteArrayOf(0x00, 0x7f, -1)) + assertEquals(0, reader.u8()) + assertEquals(127, reader.u8()) + assertEquals(255, reader.u8()) + } + + @Test + fun `an absolute read does not move the position`() { + val reader = OnePlusByteReader(byteArrayOf(0x25, 0x00, 0x04, 0x03, 0x02, 0x01)) + assertEquals(0x01020304, reader.intAt(2)) + assertEquals(0x25.toByte(), reader.byte()) + } + + @Test + fun `skipping moves past the bytes`() { + val reader = OnePlusByteReader(byteArrayOf(0x01, 0x02, 0x03)) + reader.skip(2) + assertEquals(0x03.toByte(), reader.byte()) + } + + @Test + fun `reading past the end fails instead of returning rubbish`() { + val reader = OnePlusByteReader(byteArrayOf(0x01)) + reader.byte() + assertFailsWith { reader.byte() } + } + + @Test + fun `hex is lower case and two characters per byte`() { + assertEquals("00017fff", byteArrayOf(0x00, 0x01, 0x7f, -1).onePlusToHex()) + assertEquals("", ByteArray(0).onePlusToHex()) + } + + @Test + fun `a session start answer is read on every target`() { + val writer = OnePlusByteWriter(OnePlusSessionStartRx.PACKET_LENGTH) + writer.put(OnePlusSessionStartRx.OPCODE) + writer.put(0x00) // status + writer.put(0x01) // info: OK + writer.putInt(1_000) // requested start + writer.putInt(1_010) // session start + writer.putInt(2_000) // transmitter time + val packet = writer.array() + val crc = OnePlusFastCrc16.calculate(packet, OnePlusSessionStartRx.PACKET_LENGTH - 2) + packet[OnePlusSessionStartRx.PACKET_LENGTH - 2] = crc[0] + packet[OnePlusSessionStartRx.PACKET_LENGTH - 1] = crc[1] + + val parsed = assertNotNull(OnePlusSessionStartRx.parse(packet)) + assertEquals(0, parsed.status) + assertEquals(1_000, parsed.requestedStartTime) + assertEquals(1_010, parsed.sessionStartTime) + assertEquals(2_000, parsed.transmitterTime) + assertTrue(parsed.isOkay()) + } + + @Test + fun `a glucose packet decodes on every target`() { + val writer = OnePlusByteWriter(16) + writer.put(0x4f) + writer.put(0x00) // status + writer.putInt(1) // sequence + writer.putInt(100) // transmitter time + writer.putShort(120) // glucose, not display only + writer.put(0x06) // Ok + writer.put(0) // trend + writer.putShort(0) // predicted + val raw = writer.array() + val crc = OnePlusFastCrc16.calculate(raw, raw.size - 2) + raw[raw.size - 2] = crc[0] + raw[raw.size - 1] = crc[1] + + val parsed = assertNotNull(OnePlusGlucoseParser.parseControlPacket(raw, nowMs = 1_700_000_000_000L)) + assertEquals(OnePlusCalibrationState.Ok, parsed.calibration) + assertTrue(parsed.usable) + assertEquals(120.0, assertNotNull(parsed.sample).mgdl) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCertsTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCertsTest.kt new file mode 100644 index 000000000000..d77f7a0e7218 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusKeksGuideCertsTest.kt @@ -0,0 +1,84 @@ +package app.aaps.plugins.dexcomoneplus.session + +import jamorham.keks.Plugin +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The three guide certificates must decode to exactly the bytes they decoded to before. + * + * [OnePlusKeksGuideCerts] used `android.util.Base64` while it lived in androidMain and now uses + * `kotlin.io.encoding.Base64`, which keeps the handshake in shared code. The two + * decoders are not the same class, and a certificate that came out one byte different would still + * look like a certificate: nothing in the app reads it, it is handed straight to the sensor, and + * the sensor's only answer is a pairing that fails. So the sizes are pinned here. + * + * The numbers are not invented. Each one is the DER length the certificate declares in its own + * first bytes: 0x82 0x01 0xEA plus 4 header bytes for part A, 0x82 0x01 0xCD plus 4 for part B, + * and 0x81 0x87 plus 3 for part C. + * + * No test name here may contain a comma: Kotlin/Native rejects one. + */ +class OnePlusKeksGuideCertsTest { + + private val pairingCode = "0000" + + /** + * `Plugin` keeps one instance per pairing code in a static field. Channel 3 drops it, which is + * what the driver itself does, so a later test never sees this one's certificates. + */ + @AfterTest + fun dropTheSharedInstance() { + Plugin.getInstance(pairingCode).setPersistence(3, ByteArray(0)) + } + + @Test + fun theGuideCertificatesDecodeToTheSameLengthsAsBefore() { + val plugin = Plugin.getInstance(pairingCode) + + OnePlusKeksGuideCerts.install(plugin) + + assertEquals(494, plugin.context.partA?.size, "part A") + assertEquals(465, plugin.context.partB?.size, "part B") + assertEquals(138, plugin.context.partC?.size, "part C") + } + + @Test + fun theDecodedCertificatesStartWithADerSequence() { + val plugin = Plugin.getInstance(pairingCode) + + OnePlusKeksGuideCerts.install(plugin) + + // 0x30 is the DER tag for SEQUENCE. A decoder that dropped or shifted a byte would not + // land on it, so this catches an offset error that a length check alone could miss. + assertEquals(0x30, plugin.context.partA?.get(0)?.toInt()) + assertEquals(0x30, plugin.context.partB?.get(0)?.toInt()) + assertEquals(0x30, plugin.context.partC?.get(0)?.toInt()) + } + + @Test + fun libkeksAcceptsTheInstalledCertificatesAsComplete() { + val plugin = Plugin.getInstance(pairingCode) + + OnePlusKeksGuideCerts.install(plugin) + + // The handshake's own gate: all three present and each over 100 bytes. Without it + // libkeks raises "Missing QR code" in the middle of an unbonded four-digit pairing. + assertTrue(plugin.context.validateParts()) + } + + @Test + fun installGivesTheSensorACopyAndKeepsItsOwn() { + val plugin = Plugin.getInstance(pairingCode) + + OnePlusKeksGuideCerts.install(plugin) + plugin.context.partA?.fill(0) + OnePlusKeksGuideCerts.install(plugin) + + // The second install must hand over untouched bytes. install() copies on the way out for + // exactly this reason, and it is called again on every connect. + assertEquals(0x30, plugin.context.partA?.get(0)?.toInt()) + } +} diff --git a/settings.gradle b/settings.gradle index cdaa8f50ed06..f8061c4a64f5 100644 --- a/settings.gradle +++ b/settings.gradle @@ -29,6 +29,7 @@ include ':plugins:automation' include ':plugins:calibration' include ':plugins:configuration' include ':plugins:constraints' +include ':plugins:dexcom_oneplus' include ':plugins:libkeks' include ':plugins:main' include ':plugins:sensitivity' From f9bebd40703d9fe2673ea287660f83e44c968d9f Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Wed, 28 Oct 2026 19:01:48 +0100 Subject: [PATCH 04/27] Dexcom ONE+ / G7: add the BG source plugin, its screens and pre-soak support New BG source "Dexcom ONE+ / G7" (DexcomOnePlusPlugin, plugin key 446, right after the Dexcom source). It runs the BLE driver of :plugins:dexcom_oneplus inside AAPS, so no Dexcom app or xDrip is needed, and hands each reading to the loop through insertCgmSourceData. What the plugin does - Ingest: readings are mapped to GV with SourceSensor.DEXCOM_ONEPLUS_NATIVE and the sensor slope as trend arrow. Readings are dropped while the sensor warms up, and duplicates are dropped (4 min window plus a sequence floor that survives a restart). - Two sensor slots. Production feeds the loop. Staging pre-soaks the next sensor next to the one in use: its readings are only collected, never given to the loop. Promotion needs 12 h of soak and 6 valid readings, or, when the user asks for an early switch, a recent reading. An optional automatic switch (off by default) uses the same checks. On promotion the plugin calls Calibration.ignoreEntriesBefore, so fingersticks paired with the old sensor are not fitted to the new one. If that call throws, the switch is kept and the user is told. - The plugin publishes warm-up and staging state through CgmWarmupProvider and CgmSensorStatusProvider, including stagingSettleRemainingMs. The 12 h settle rule stays in the plugin. - A reconnect watchdog asks for the session again after 5 min down, and a connectedDevice foreground service keeps the Bluetooth session alive while a sensor is stored in either slot. - Work runs only while the plugin is started. Its coroutine scope is made when work is first needed and cancelled in onStop, so nothing runs for a user who never enables the plugin. The warm-up status flow is set directly, with no collector, and all state flows have their empty values while the plugin is off. An automatic switch that has already started is not cut in half by a stop. - Sensor age: a SENSOR_CHANGE therapy event is written when a sensor is started (if "Create sensor change" is on). Three sensor change settings, normal user settings, on by default, in the plugin's settings screen: - Repair a missing sensor change: writes the missing event once per sensor, so the overview age is right. - Use a sensor change you logged as the start: a manual sensor change from the last 24 h becomes the session start. - Allow correcting the insertion date: adds an action on the Status screen that moves the sensor start. Advanced filtering: DEXCOM_ONEPLUS_NATIVE is in ADVANCED_FILTERING_SENSORS (previous commit), so it enables SMB-always and SMB-after-carbs like G7 / BYODA. This is a dosing input. Where the files are (plugins/source) - androidMain: everything that imports the driver - plugin, host interface and its Android implementation, ingest, warm-up mapper and notification, session foreground service, BLE permission helper, the Start / Status / Warm-up screens and activities, the driver log screen (CgmDriverLogActivity, DriverLogReader) and the Metro member injectors. The driver is an androidMain dependency only. - commonMain: ONE+ code that does not need the driver - staging rules, automatic switch rule, sensor start correction, sensor change anchor, warm-up countdown, the Cgm* compose parts and the preference keys. CgmWindow has an expect with android, ios and jvm actuals. - Activities use Metro @Inject fields; no javax interop is needed. - CgmSpacing: four sizes used only by these screens (content width, list row height, warm-up ring min and max). - Manifest: 4 activities, the service (connectedDevice) and FOREGROUND_SERVICE_CONNECTED_DEVICE. - 166 English strings under one comment block. Not in this commit - The temp basal guard and sending a fingerstick calibration to the sensor (with the Status screen calibration card): both change dosing inputs, so each has its own commit later in this series. - iOS host: the driver has no iOS target yet, so nothing here is contributed on iOS. - The driver log screen shows the ONE+ driver only, so it has no filter. Other changes - Golden lists: ContributedPluginsTest gets 446, prefs-schema.txt gets the 8 new keys. Tests: 172 tests for this code in :plugins:source:testAndroidHostTest: ingest and dedup, staging rules and promotion order, automatic switch, sensor age repair, insertion date, sensor change anchor, warm-up mapping and countdown, the settle countdown, the Start screen, string checks, and the plugin lifetime (nothing runs before onStart or after onStop, a database write still waiting is cancelled by onStop, the flows answer while the plugin is off). These are unit tests only; no test on a real sensor or phone is claimed for this branch. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../aaps/di/metro/ContributedPluginsTest.kt | 2 +- app/src/testFull/resources/prefs-schema.txt | 8 + plugins/source/build.gradle.kts | 5 + .../plugins/source/DexcomOnePlusIngestTest.kt | 127 ++ .../source/DexcomOnePlusInsertionDateTest.kt | 222 +++ .../source/DexcomOnePlusPluginLifetimeTest.kt | 187 +++ .../DexcomOnePlusPluginVisibilityTest.kt | 74 + .../source/DexcomOnePlusPromotionAlertTest.kt | 54 + .../source/DexcomOnePlusPromotionOrderTest.kt | 526 +++++++ .../DexcomOnePlusSensorAgeRepairTest.kt | 315 +++++ .../DexcomOnePlusSensorChangeAnchorTest.kt | 60 + .../DexcomOnePlusSensorStartCorrectionTest.kt | 105 ++ .../source/DexcomOnePlusSharedCodeTest.kt | 131 ++ .../source/DexcomOnePlusStagingTest.kt | 231 +++ .../source/DexcomOnePlusWarmupMapperTest.kt | 84 ++ .../source/StagingAutoPromotionTest.kt | 77 + .../compose/DexcomOnePlusStartRulesTest.kt | 134 ++ .../compose/DexcomOnePlusStartScreenTest.kt | 177 +++ .../compose/DexcomOnePlusStartStringsTest.kt | 148 ++ .../DexcomOnePlusWarmupCountdownTest.kt | 138 ++ .../compose/OnePlusWarmupMappingTest.kt | 30 + .../source/compose/SensorAgeFormatTest.kt | 72 + .../source/keys/StagingAutoPromoteKeysTest.kt | 26 + .../source/logs/DriverLogReaderTest.kt | 83 ++ .../src/androidMain/AndroidManifest.xml | 22 + .../source/DexcomOnePlusAndroidHost.kt | 91 ++ .../aaps/plugins/source/DexcomOnePlusHost.kt | 91 ++ .../plugins/source/DexcomOnePlusIngest.kt | 153 ++ .../plugins/source/DexcomOnePlusPlugin.kt | 1255 +++++++++++++++++ .../source/DexcomOnePlusSessionService.kt | 122 ++ .../source/DexcomOnePlusWarmupMapper.kt | 44 + .../source/DexcomOnePlusWarmupNotification.kt | 187 +++ .../source/OnePlusBlePermissionHelper.kt | 45 + .../source/activities/CgmDriverLogActivity.kt | 226 +++ .../activities/DexcomOnePlusStartActivity.kt | 119 ++ .../activities/DexcomOnePlusStatusActivity.kt | 596 ++++++++ .../activities/DexcomOnePlusWarmupActivity.kt | 74 + .../source/compose/CgmWindow.android.kt | 13 + .../source/compose/DexcomOnePlusStartRules.kt | 71 + .../compose/DexcomOnePlusStartScreen.kt | 896 ++++++++++++ .../compose/DexcomOnePlusStatusSummary.kt | 75 + .../source/compose/DexcomOnePlusUiLabels.kt | 52 + .../compose/DexcomOnePlusWarmupScreen.kt | 443 ++++++ .../compose/OnePlusBlePermissionGate.kt | 22 + .../source/compose/OnePlusWarmupMapping.kt | 27 + .../source/di/SourceMemberInjectors.kt | 57 + .../plugins/source/logs/DriverLogReader.kt | 90 ++ .../src/androidMain/res/values/strings.xml | 168 +++ .../source/DexcomOnePlusSensorChangeAnchor.kt | 34 + .../DexcomOnePlusSensorStartCorrection.kt | 90 ++ .../plugins/source/DexcomOnePlusStaging.kt | 144 ++ .../plugins/source/StagingAutoPromotion.kt | 88 ++ .../plugins/source/compose/CgmCardParts.kt | 381 +++++ .../plugins/source/compose/CgmScaffold.kt | 136 ++ .../aaps/plugins/source/compose/CgmSpacing.kt | 21 + .../plugins/source/compose/CgmStateChip.kt | 123 ++ .../aaps/plugins/source/compose/CgmWarmup.kt | 51 + .../plugins/source/compose/CgmWarmupRing.kt | 90 ++ .../aaps/plugins/source/compose/CgmWindow.kt | 73 + .../compose/DexcomOnePlusWarmupCountdown.kt | 78 + .../plugins/source/compose/SensorAgeFormat.kt | 41 + .../source/keys/DexcomOnePlusBooleanKey.kt | 80 ++ .../source/keys/DexcomOnePlusIntKey.kt | 35 + .../source/keys/DexcomOnePlusIntentKey.kt | 39 + .../plugins/source/compose/CgmWindow.ios.kt | 16 + .../plugins/source/compose/CgmWindow.jvm.kt | 16 + 66 files changed, 9490 insertions(+), 1 deletion(-) create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusIngestTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionAlertTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchorTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrectionTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSharedCodeTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusStagingTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapperTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/StagingAutoPromotionTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdownTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMappingTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/SensorAgeFormatTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/keys/StagingAutoPromoteKeysTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusIngest.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSessionService.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapper.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupNotification.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/OnePlusBlePermissionHelper.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivity.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusWarmupActivity.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.android.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupScreen.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusBlePermissionGate.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMapping.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMemberInjectors.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/logs/DriverLogReader.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchor.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrection.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusStaging.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmCardParts.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmSpacing.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmStateChip.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmup.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmupRing.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdown.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntKey.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt create mode 100644 plugins/source/src/iosMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.ios.kt create mode 100644 plugins/source/src/jvmMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.jvm.kt diff --git a/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt b/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt index 5d8d78c7e132..00dd903bb2e8 100644 --- a/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt +++ b/app/src/test/kotlin/app/aaps/di/metro/ContributedPluginsTest.kt @@ -37,7 +37,7 @@ class ContributedPluginsTest { // sensitivity 100, 110, 120, 200, 210, 220, 230, 240, - 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, + 400, 410, 420, 430, 440, 446, 450, 460, 470, 480, 490, 500, 510, 520, 530, 540, 550, // sync - the every-build part of the 300 block. SmsCommunicator 300 and Tidepool 320 are // @NotNSClient; 340 (OpenHumans) comes from its own graph extension. 310, 330, 350, 360, 370, diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index 08e6927563ab..7cf9bea8f609 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -159,6 +159,14 @@ danars_v3_randompairing_key_%s|DanaStringComposedKey|true danars_v3_randomsync_key_%s|DanaStringComposedKey|true device_type|MedtrumIntNonKey|true dexcom_lognssensorchange|BooleanKey|true +dexcom_oneplus_anchor_session_to_manual_sensor_change|DexcomOnePlusBooleanKey|false +dexcom_oneplus_correct_sensor_start|DexcomOnePlusBooleanKey|false +dexcom_oneplus_repair_missing_sensor_change|DexcomOnePlusBooleanKey|false +dexcom_oneplus_staging_auto_promote_hours|DexcomOnePlusIntKey|true +dexcom_oneplus_staging_auto_promote|DexcomOnePlusBooleanKey|false +dexcom_oneplus_start|DexcomOnePlusIntentKey|false +dexcom_oneplus_status|DexcomOnePlusIntentKey|false +dexcom_oneplus_warmup|DexcomOnePlusIntentKey|false dexcomg5_nsupload|BooleanKey|true diaconn_bt_selector|DiaconnIntentKey|false diaconn_g8_appuid|DiaconnStringNonKey|true diff --git a/plugins/source/build.gradle.kts b/plugins/source/build.gradle.kts index 192fefccaa62..9d0e1fc64e5f 100644 --- a/plugins/source/build.gradle.kts +++ b/plugins/source/build.gradle.kts @@ -84,6 +84,11 @@ kotlin { androidMain { kotlin.srcDir(generateSourceStrings.flatMap { it.androidOutputDir }) dependencies { + // The Dexcom ONE+ / G7 BLE driver. Android only: the driver has no other target yet, + // so the plugin, its host and its screens live in androidMain. commonMain keeps only + // the ONE+ code that does not need the driver. + implementation(project(":plugins:dexcom_oneplus")) + 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/DexcomOnePlusIngestTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusIngestTest.kt new file mode 100644 index 000000000000..2d373c9a36c7 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusIngestTest.kt @@ -0,0 +1,127 @@ +package app.aaps.plugins.source + +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.model.TrendArrow +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +class DexcomOnePlusIngestTest { + + @BeforeEach + fun clearDedup() { + DexcomOnePlusIngest.clearDedupForTests() + } + + @Test + fun `mapToGv uses native source sensor and trend`() { + val sample = OnePlusGlucoseSample( + mgdl = 118.0, + timestampMs = 1_700_000_000_000L, + trendSlopeMgdlPerMin = 1.2, + sequence = 42L, + ) + + val gv = DexcomOnePlusIngest.mapToGv(sample) + + assertThat(gv.timestamp).isEqualTo(1_700_000_000_000L) + assertThat(gv.value).isEqualTo(118.0) + assertThat(gv.raw).isNull() + assertThat(gv.noise).isNull() + assertThat(gv.trendArrow).isEqualTo(TrendArrow.FORTY_FIVE_UP) + assertThat(gv.sourceSensor).isEqualTo(SourceSensor.DEXCOM_ONEPLUS_NATIVE) + } + + @Test + fun `mapToGv keeps NONE when the sensor sent no usable trend`() { + val gv = DexcomOnePlusIngest.mapToGv( + OnePlusGlucoseSample(mgdl = 90.0, timestampMs = 1L, trendSlopeMgdlPerMin = null) + ) + assertThat(gv.trendArrow).isEqualTo(TrendArrow.NONE) + } + + /** + * The regression this covers: the parser reports a slope in mg/dL per minute, and that used to + * be matched against arrow *names*. Nothing matched, so every reading arrived as NONE and the + * glucose history showed the invalid-arrow icon for the whole ONE+ list. + */ + @Test + fun `a slope the parser really produces never degrades to NONE`() { + listOf(-5.0, -2.5, -1.4, -0.5, 0.0, 0.9, 1.2, 2.4, 4.0).forEach { slope -> + val gv = DexcomOnePlusIngest.mapToGv( + OnePlusGlucoseSample(mgdl = 118.0, timestampMs = 1L, trendSlopeMgdlPerMin = slope) + ) + assertThat(gv.trendArrow).isNotEqualTo(TrendArrow.NONE) + } + } + + @Test + fun `trendArrowFor maps slope to arrow at every boundary`() { + assertThat(DexcomOnePlusIngest.trendArrowFor(null)).isEqualTo(TrendArrow.NONE) + assertThat(DexcomOnePlusIngest.trendArrowFor(4.0)).isEqualTo(TrendArrow.DOUBLE_UP) + assertThat(DexcomOnePlusIngest.trendArrowFor(3.0)).isEqualTo(TrendArrow.DOUBLE_UP) + assertThat(DexcomOnePlusIngest.trendArrowFor(2.9)).isEqualTo(TrendArrow.SINGLE_UP) + assertThat(DexcomOnePlusIngest.trendArrowFor(2.0)).isEqualTo(TrendArrow.SINGLE_UP) + assertThat(DexcomOnePlusIngest.trendArrowFor(1.9)).isEqualTo(TrendArrow.FORTY_FIVE_UP) + assertThat(DexcomOnePlusIngest.trendArrowFor(1.0)).isEqualTo(TrendArrow.FORTY_FIVE_UP) + assertThat(DexcomOnePlusIngest.trendArrowFor(0.9)).isEqualTo(TrendArrow.FLAT) + assertThat(DexcomOnePlusIngest.trendArrowFor(0.0)).isEqualTo(TrendArrow.FLAT) + assertThat(DexcomOnePlusIngest.trendArrowFor(-0.9)).isEqualTo(TrendArrow.FLAT) + assertThat(DexcomOnePlusIngest.trendArrowFor(-1.0)).isEqualTo(TrendArrow.FORTY_FIVE_DOWN) + assertThat(DexcomOnePlusIngest.trendArrowFor(-1.9)).isEqualTo(TrendArrow.FORTY_FIVE_DOWN) + assertThat(DexcomOnePlusIngest.trendArrowFor(-2.0)).isEqualTo(TrendArrow.SINGLE_DOWN) + assertThat(DexcomOnePlusIngest.trendArrowFor(-2.9)).isEqualTo(TrendArrow.SINGLE_DOWN) + assertThat(DexcomOnePlusIngest.trendArrowFor(-3.0)).isEqualTo(TrendArrow.DOUBLE_DOWN) + assertThat(DexcomOnePlusIngest.trendArrowFor(-5.0)).isEqualTo(TrendArrow.DOUBLE_DOWN) + } + + @Test + fun `warmup WARMING blocks ingest`() { + assertThat(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.WARMING)).isTrue() + assertThat(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.READY)).isFalse() + assertThat(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.IDLE)).isFalse() + assertThat(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.PAIRING)).isFalse() + assertThat(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.FAILED)).isFalse() + } + + @Test + fun `shouldAccept drops near-duplicate timestamps`() { + val a = OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 1_000_000L) + val near = OnePlusGlucoseSample(mgdl = 101.0, timestampMs = 1_000_000L + 60_000L) + val far = OnePlusGlucoseSample(mgdl = 102.0, timestampMs = 1_000_000L + DexcomOnePlusIngest.DEDUP_WINDOW_MS) + assertThat(DexcomOnePlusIngest.shouldAccept(a)).isTrue() + assertThat(DexcomOnePlusIngest.shouldAccept(near)).isFalse() + assertThat(DexcomOnePlusIngest.shouldAccept(far)).isTrue() + } + + @Test + fun `shouldAccept drops duplicate sequence`() { + val a = OnePlusGlucoseSample(mgdl = 110.0, timestampMs = 10L, sequence = 7L) + val b = OnePlusGlucoseSample(mgdl = 111.0, timestampMs = 10L + DexcomOnePlusIngest.DEDUP_WINDOW_MS, sequence = 7L) + assertThat(DexcomOnePlusIngest.shouldAccept(a)).isTrue() + assertThat(DexcomOnePlusIngest.shouldAccept(b)).isFalse() + } + + @Test + fun `seed sequence floor rejects re-reads after a restart`() { + // Simulate rehydration after an app update: last accepted sequence was 100. + DexcomOnePlusIngest.seed(lastSequence = 100L, recentTimestampsMs = emptyList()) + // A backfilled/re-read reading at or below the floor is rejected even with a fresh timestamp. + assertThat(DexcomOnePlusIngest.shouldAccept(OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 5_000_000L, sequence = 100L))).isFalse() + assertThat(DexcomOnePlusIngest.shouldAccept(OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 5_000_000L, sequence = 99L))).isFalse() + // A genuinely new reading above the floor is accepted. + assertThat(DexcomOnePlusIngest.shouldAccept(OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 6_000_000L, sequence = 101L))).isTrue() + } + + @Test + fun `seed timestamps reject recomputed re-reads within window`() { + // The parser recomputes ts = now - age on each read, so a re-read after restart lands at a + // slightly different timestamp that DB dedup (exact match) misses. Seeding recent stored + // timestamps re-arms the near-duplicate window so the re-read is still dropped. + DexcomOnePlusIngest.seed(lastSequence = -1L, recentTimestampsMs = listOf(2_000_000L)) + val reRead = OnePlusGlucoseSample(mgdl = 120.0, timestampMs = 2_000_000L + 30_000L) // 30 s off, no sequence + assertThat(DexcomOnePlusIngest.shouldAccept(reRead)).isFalse() + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt new file mode 100644 index 000000000000..d13b86df59fe --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt @@ -0,0 +1,222 @@ +package app.aaps.plugins.source + +import android.content.Context +import android.content.SharedPreferences +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.GlucoseUnit +import app.aaps.core.data.model.TE +import app.aaps.core.data.ue.Action +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection.Verdict +import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey +import app.aaps.shared.tests.SharedPreferencesMock +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.lang.reflect.Field + +/** + * Insertion-date correction, `DexcomOnePlusPlugin.correctProductionSensorStart`. + * The setting is on by default; the tests set it explicitly. + */ +class DexcomOnePlusInsertionDateTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences + @Mock lateinit var config: Config + @Mock lateinit var context: Context + @Mock lateinit var persistenceLayer: PersistenceLayer + @Mock lateinit var notificationManager: NotificationManager + + private val activePlugin: ActivePlugin = mock() + private val prefs: SharedPreferences = SharedPreferencesMock() + + private lateinit var plugin: DexcomOnePlusPlugin + + @BeforeEach + fun setup() = runTest { + rxBus = mock() + setBuildField("MANUFACTURER", "Google") + setBuildField("MODEL", "Pixel") + whenever(context.applicationContext).thenReturn(context) + whenever(context.getSharedPreferences(PRODUCTION_PREFS, Context.MODE_PRIVATE)).thenReturn(prefs) + whenever(persistenceLayer.insertCgmSourceData(any(), any(), any(), anyOrNull())).thenAnswer { invocation -> + val result = PersistenceLayer.TransactionResult() + val stamp = invocation.arguments[3] as Long? + if (stamp != null) result.sensorInsertionsInserted.add(sensorChange(stamp)) + result + } + whenever(persistenceLayer.getTherapyEventDataFromToTime(any(), any())).thenReturn(emptyList()) + whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())).thenReturn(emptyList()) + plugin = DexcomOnePlusPlugin( + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + activePlugin, rxBus, + ) + } + + @Test + fun `the correction switch is on by default`() { + assertThat(DexcomOnePlusBooleanKey.CorrectSensorStart.defaultValue).isTrue() + } + + @Test + fun `a correction while the switch is off writes nothing`() = runTest { + whenever(preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart)).thenReturn(false) + val current = System.currentTimeMillis() - 2 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor(MAC, current, null) + + val verdict = plugin.correctProductionSensorStart(current - 6 * HOUR_MS) + + assertThat(verdict).isEqualTo(Verdict.Disabled) + assertNothingWritten(current) + } + + @Test + fun `InFuture invalidates nothing`() = runTest { + enableCorrection() + val current = System.currentTimeMillis() - 2 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor(MAC, current, null) + + val verdict = plugin.correctProductionSensorStart(System.currentTimeMillis() + HOUR_MS) + + assertThat(verdict).isEqualTo(Verdict.InFuture) + assertNothingWritten(current) + } + + @Test + fun `TooOld invalidates nothing`() = runTest { + enableCorrection() + val current = System.currentTimeMillis() - 2 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor(MAC, current, null) + + val verdict = plugin.correctProductionSensorStart(System.currentTimeMillis() - 11 * 24 * HOUR_MS) + + assertThat(verdict).isEqualTo(Verdict.TooOld) + assertNothingWritten(current) + } + + @Test + fun `NoSession invalidates nothing`() = runTest { + enableCorrection() + + val verdict = plugin.correctProductionSensorStart(System.currentTimeMillis() - HOUR_MS) + + assertThat(verdict).isEqualTo(Verdict.NoSession) + verify(persistenceLayer, never()).invalidateTherapyEvent(any(), any(), any(), anyOrNull(), any()) + verify(persistenceLayer, never()).invalidateCalibrationEntry(any(), any(), any(), anyOrNull(), any()) + verify(persistenceLayer, never()).insertCgmSourceData(any(), any(), any(), anyOrNull()) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(0L) + } + + @Test + fun `Accepted invalidates the sensor change then rewrites it`() = runTest { + enableCorrection() + val now = System.currentTimeMillis() + val current = now - 2 * HOUR_MS + val asked = now - 8 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor(MAC, current, null) + val event = sensorChange(current, id = 42L) + whenever(persistenceLayer.getTherapyEventDataFromToTime(any(), any())).thenReturn(listOf(event)) + whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())).thenReturn(listOf(event)) + + val verdict = plugin.correctProductionSensorStart(asked) + + assertThat(verdict).isEqualTo(Verdict.Accepted) + verify(persistenceLayer).invalidateTherapyEvent( + eq(42L), eq(Action.CAREPORTAL_REMOVED), any(), anyOrNull(), any(), + ) + verify(persistenceLayer).insertCgmSourceData(any(), any(), any(), eq(asked)) + verify(persistenceLayer, never()).invalidateCalibrationEntry(any(), any(), any(), anyOrNull(), any()) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(asked) + verify(rxBus).send(any()) + } + + @Test + fun `an occupied timestamp moves one second and not further`() = runTest { + enableCorrection() + val now = System.currentTimeMillis() + val current = now - 2 * HOUR_MS + val asked = now - 8 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor(MAC, current, null) + val blocking = sensorChange(asked, id = 7L) + whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())).thenReturn(listOf(blocking)) + whenever(persistenceLayer.getTherapyEventDataFromToTime(any(), any())).thenReturn(emptyList()) + + val verdict = plugin.correctProductionSensorStart(asked) + + assertThat(verdict).isEqualTo(Verdict.Accepted) + verify(persistenceLayer).insertCgmSourceData(any(), any(), any(), eq(asked + 1_000L)) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(asked + 1_000L) + verify(persistenceLayer, never()).invalidateCalibrationEntry(any(), any(), any(), anyOrNull(), any()) + } + + @Test + fun `overwriteSessionStart ignores a non positive time`() { + val current = 1_700_000_000_000L + val store = OnePlusSensorStore(context) + store.startSessionForSensor(MAC, current, null) + + store.overwriteSessionStart(0L) + store.overwriteSessionStart(-1L) + + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(current) + store.overwriteSessionStart(current - HOUR_MS) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(current - HOUR_MS) + } + + private fun enableCorrection() { + whenever(preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart)).thenReturn(true) + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + } + + private suspend fun assertNothingWritten(currentStart: Long) { + verify(persistenceLayer, never()).invalidateTherapyEvent(any(), any(), any(), anyOrNull(), any()) + verify(persistenceLayer, never()).invalidateCalibrationEntry(any(), any(), any(), anyOrNull(), any()) + verify(persistenceLayer, never()).insertCgmSourceData(any(), any(), any(), anyOrNull()) + verify(rxBus, never()).send(any()) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(currentStart) + } + + private fun sensorChange(timestamp: Long, id: Long = 11L): TE = TE( + id = id, + timestamp = timestamp, + type = TE.Type.SENSOR_CHANGE, + glucoseUnit = GlucoseUnit.MGDL, + ) + + private fun setBuildField(name: String, value: String) { + val field = android.os.Build::class.java.getDeclaredField(name) + val unsafeClass = Class.forName("sun.misc.Unsafe") + val unsafeField = unsafeClass.getDeclaredField("theUnsafe") + unsafeField.isAccessible = true + val unsafe = unsafeField.get(null) + val base = unsafeClass.getMethod("staticFieldBase", Field::class.java).invoke(unsafe, field) + val offset = unsafeClass.getMethod("staticFieldOffset", Field::class.java).invoke(unsafe, field) as Long + unsafeClass.getMethod("putObject", Any::class.java, java.lang.Long.TYPE, Any::class.java) + .invoke(unsafe, base, offset, value) + } + + companion object { + private const val HOUR_MS = 60L * 60L * 1000L + private const val MAC = "AA:BB:CC:DD:EE:30" + private const val PRODUCTION_PREFS = "dexcom_oneplus_sensor" + private const val KEY_SESSION_START = "session_start_ms" + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt new file mode 100644 index 000000000000..14400c7716ef --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt @@ -0,0 +1,187 @@ +package app.aaps.plugins.source + +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.keys.interfaces.PreferenceItem +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverStub +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub +import app.aaps.shared.tests.AAPSLoggerTest +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.whenever + +/** + * When the work of the Dexcom ONE+ plugin runs. + * + * Nothing may run for a user who never enables the plugin, and nothing may keep running after + * `onStop`. The state flows must still answer while the plugin is off, because the overview reads + * them for every BG source. + */ +class DexcomOnePlusPluginLifetimeTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences + @Mock lateinit var config: Config + @Mock lateinit var persistenceLayer: PersistenceLayer + @Mock lateinit var notificationManager: NotificationManager + @Mock lateinit var activePlugin: ActivePlugin + + private lateinit var driver: OnePlusCgmDriverStub + private lateinit var plugin: DexcomOnePlusPlugin + + @BeforeEach + fun setup() = runTest { + whenever(persistenceLayer.getBgReadingsDataFromTime(any(), any())).thenReturn(emptyList()) + driver = OnePlusCgmDriverStub() + plugin = DexcomOnePlusPlugin( + rh, AAPSLoggerTest(), preferences, config, notificationManager, FakeHost(driver), persistenceLayer, + activePlugin, rxBus, + ) + } + + @Test + fun `a plugin that was never started runs nothing and its flows still answer`() { + assertThat(plugin.hasRunningWork()).isFalse() + assertThat(plugin.warmupStatus.value).isNull() + assertThat(plugin.lifecycle.value).isNull() + assertThat(plugin.stagingState.value).isEqualTo(StagingState.ABSENT) + assertThat(plugin.stagingLifecycle.value).isNull() + assertThat(plugin.stagingEvidence.value).isNull() + assertThat(plugin.stagingSettleRemainingMs.value).isNull() + } + + @Test + fun `the warm-up status follows the driver without a running collector`() { + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.WARMING, remainingMs = 60_000L)) + + assertThat(plugin.warmupStatus.value).isNotNull() + assertThat(plugin.hasRunningWork()).isFalse() + + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY)) + + assertThat(plugin.warmupStatus.value).isNull() + } + + @Test + fun `nothing keeps running after onStop`() = runTest { + plugin.onStart() + // A lost link arms the reconnect watchdog: a coroutine that waits five minutes. + plugin.onSession(up = false, reason = "link lost") + assertThat(plugin.hasRunningWork()).isTrue() + + plugin.onStop() + + assertThat(plugin.hasRunningWork()).isFalse() + } + + @Test + fun `a database write still waiting is cancelled by onStop`() = runTest { + // The write of a reading never returns, so only onStop can end it. The watchdog is not + // involved here: onStop cancels the watchdog on its own, this checks the rest of the work. + whenever(persistenceLayer.insertCgmSourceData(any(), any(), any(), anyOrNull())).doSuspendableAnswer { awaitCancellation() } + plugin.onStart() + plugin.onGlucose(OnePlusGlucoseSample(mgdl = 120.0, timestampMs = System.currentTimeMillis(), sequence = 900_001L)) + assertThat(plugin.hasRunningWork()).isTrue() + + plugin.onStop() + + assertThat(plugin.hasRunningWork()).isFalse() + } + + @Test + fun `a start after a stop gets working again`() = runTest { + plugin.onStart() + plugin.onStop() + + plugin.onStart() + plugin.onSession(up = false, reason = "link lost") + + assertThat(plugin.hasRunningWork()).isTrue() + plugin.onStop() + assertThat(plugin.hasRunningWork()).isFalse() + } + + /** Everything the plugin asks of the phone, answered without Bluetooth or a file. */ + private class FakeHost(private val driver: OnePlusCgmDriver) : DexcomOnePlusHost { + + private val stores = mutableMapOf() + + override fun attachPlatform(driver: OnePlusCgmDriver) = Unit + override fun slotStore(namespace: String?): OnePlusSensorStore = + stores.getOrPut(namespace) { OnePlusSensorStore(MemoryPrefs()) } + + override val stagingNamespace: String = "staging" + override fun productionDriver(): OnePlusCgmDriver = driver + override fun stagingDriver(): OnePlusCgmDriver = driver + override fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = + driver.also { it.addWatcher(watcher) } + + override fun promoteStagingInstance(): OnePlusCgmDriver? = null + override fun setSessionServiceWanted(wanted: Boolean) = Unit + override fun showWarmup(state: OnePlusWarmupState) = Unit + override fun cancelWarmupNotification() = Unit + override fun alert(message: String) = Unit + override fun screenScanner(): OnePlusBleScanner = OnePlusBleScannerStub() + override fun screenItems(plugin: DexcomOnePlusPlugin): List = emptyList() + } + + /** An empty slot store in memory. */ + private class MemoryPrefs : OnePlusSensorPrefs { + + private val values = mutableMapOf() + + override fun getString(key: String): String? = values[key] as? String + override fun getLong(key: String, defaultValue: Long): Long = values[key] as? Long ?: defaultValue + override fun getInt(key: String, defaultValue: Int): Int = values[key] as? Int ?: defaultValue + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = values[key] as? Boolean ?: defaultValue + override fun contains(key: String): Boolean = values.containsKey(key) + + override fun edit(block: OnePlusSensorPrefs.Editor.() -> Unit) { + object : OnePlusSensorPrefs.Editor { + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + + override fun putLong(key: String, value: Long) { + values[key] = value + } + + override fun putInt(key: String, value: Int) { + values[key] = value + } + + override fun putBoolean(key: String, value: Boolean) { + values[key] = value + } + + override fun remove(key: String) { + values.remove(key) + } + + override fun clear() { + values.clear() + } + }.block() + } + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt new file mode 100644 index 000000000000..230446595026 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt @@ -0,0 +1,74 @@ +package app.aaps.plugins.source + +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.plugin.EnforcedState +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.StringKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock +import org.mockito.kotlin.whenever + +/** + * ONE+ is listed in every build, with nothing to set up first, like the other BG sources: Config + * Builder, the Setup Wizard, search and Quick Launch all read + * `ActivePlugin.getSpecificPluginsVisibleInList`, that is `PluginBase.showInList`. + * + * These tests make sure no hidden gate is added later. A missing AAPS directory must not hide it. + */ +class DexcomOnePlusPluginVisibilityTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences + @Mock lateinit var config: Config + @Mock lateinit var context: Context + @Mock lateinit var persistenceLayer: PersistenceLayer + @Mock lateinit var notificationManager: NotificationManager + @Mock lateinit var activePlugin: ActivePlugin + + + private lateinit var plugin: DexcomOnePlusPlugin + + @BeforeEach + fun setup() { + plugin = DexcomOnePlusPlugin( + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + activePlugin, rxBus + ) + } + + @Test + fun `11 - ONE+ is visible with no marker file and no set-up at all`() { + assertThat(plugin.showInList()).isTrue() + } + + @Test + fun `12 - ONE+ stays visible when no AAPS directory is selected`() { + whenever(preferences.getIfExists(StringKey.AapsDirectoryUri)).thenReturn(null) + + assertThat(plugin.showInList()).isTrue() + } + + @Test + fun `15 - a sibling BG source plugin behaves the same way`() { + val aidex = AidexPlugin(rh, aapsLogger, preferences, config, notificationManager) + + assertThat(plugin.showInList()).isTrue() + assertThat(aidex.showInList()).isTrue() + assertThat(aidex.enforcedState()).isNotEqualTo(EnforcedState.Disabled) + } + + @Test + fun `20 - being listed does not enable anything by itself`() { + // Visibility and the enable path were always separate, and they still are: a listed plugin + // is one the person may pick, not one that is running. + assertThat(plugin.enforcedState()).isNotEqualTo(EnforcedState.Disabled) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionAlertTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionAlertTest.kt new file mode 100644 index 000000000000..081439a0c116 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionAlertTest.kt @@ -0,0 +1,54 @@ +package app.aaps.plugins.source + +import android.app.Notification +import android.app.NotificationManager +import android.content.Intent +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config + +/** The status-bar alert that [DexcomOnePlusWarmupNotification.alert] posts for a promotion problem. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class DexcomOnePlusPromotionAlertTest { + + @Test + fun `bound failure notification shows the text and the action`() { + val context = RuntimeEnvironment.getApplication() + val text = context.getString(R.string.dexcom_oneplus_staging_promote_bound_failed) + + DexcomOnePlusWarmupNotification(context).alert(text) + + val manager = context.getSystemService(NotificationManager::class.java) + val posted = shadowOf(manager).allNotifications.single() + val shown = posted.extras.getCharSequence(Notification.EXTRA_BIG_TEXT).toString() + assertThat(shown).isEqualTo(text) + assertThat(shown).contains("older calibration entries could not be ignored") + assertThat(shown).contains("Remove fingerstick calibrations taken before this switch") + } + + @Test + fun `promotion alert and session service notification coexist`() { + val context = RuntimeEnvironment.getApplication() + val alertText = context.getString(R.string.dexcom_oneplus_staging_promote_bound_failed) + val sessionText = context.getString(R.string.dexcom_oneplus_notif_session_alive) + + DexcomOnePlusWarmupNotification(context).alert(alertText) + val service = Robolectric.buildService(DexcomOnePlusSessionService::class.java).create().get() + service.onStartCommand(Intent(context, DexcomOnePlusSessionService::class.java), 0, 1) + + val shown = shadowOf(context.getSystemService(NotificationManager::class.java)) + .allNotifications + .map { notification -> + notification.extras.getCharSequence(Notification.EXTRA_BIG_TEXT)?.toString() + ?: notification.extras.getCharSequence(Notification.EXTRA_TEXT)?.toString() + } + assertThat(shown).contains(alertText) + assertThat(shown).contains(sessionText) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt new file mode 100644 index 000000000000..3846f219cc4f --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt @@ -0,0 +1,526 @@ +package app.aaps.plugins.source + +import android.bluetooth.BluetoothManager +import android.content.Context +import android.content.SharedPreferences +import android.os.PowerManager +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.calibration.Calibration +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.dexcomoneplus.OnePlusAndroidPlatform +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.session.OnePlusMacArbiter +import app.aaps.plugins.source.activities.dexcomOnePlusPromotionMessage +import app.aaps.shared.tests.AAPSLoggerTest +import app.aaps.shared.tests.SharedPreferencesMock +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.timeout +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.io.File + +/** + * Promotion order of Dexcom ONE+. + * + * Every refusal returns before the irreversible steps. A success runs the guards, then the + * exchange, then `logSensorChange`, then `ignoreEntriesBefore`. A throw from + * `ignoreEntriesBefore` does not undo the exchange, and the result is not Ok. + */ +class DexcomOnePlusPromotionOrderTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences + @Mock lateinit var config: Config + @Mock lateinit var context: Context + @Mock lateinit var persistenceLayer: PersistenceLayer + + + private val notificationManager: NotificationManager = mock() + private val activeCalibration: Calibration = mock() + private val activePlugin: ActivePlugin = mock().also { + whenever(it.activeCalibration).thenReturn(activeCalibration) + } + private val logger = RecordingLogger() + private val alerts = mutableListOf() + + private val productionPrefs: SharedPreferences = SharedPreferencesMock() + private val stagingPrefs: SharedPreferences = SharedPreferencesMock() + + private lateinit var plugin: DexcomOnePlusPlugin + + @BeforeEach + fun setup() = runTest { + whenever(context.applicationContext).thenReturn(context) + whenever(context.getSharedPreferences(PRODUCTION_PREFS_NAME, Context.MODE_PRIVATE)).thenReturn(productionPrefs) + whenever(context.getSharedPreferences(STAGING_PREFS_NAME, Context.MODE_PRIVATE)).thenReturn(stagingPrefs) + whenever(persistenceLayer.insertCgmSourceData(any(), any(), any(), anyOrNull())) + .thenReturn(PersistenceLayer.TransactionResult()) + plugin = DexcomOnePlusPlugin( + rh, logger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + activePlugin, rxBus, + ) + plugin.promotionAlerter = { alerts += it } + } + + @AfterEach + fun tearDownDrivers() { + OnePlusCgmDrivers.shutdownAll() + OnePlusMacArbiter.reset() + } + + @Test + fun `absent staging writes nothing irreversible`() = runTest { + val stagingBefore = stagingPrefs.all.toMap() + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT)) + assertNothingIrreversible(stagingBefore) + } + + @Test + fun `fewer than six readings writes nothing irreversible`() = runTest { + setPrivate("stagingPresent", true) + setPrivate("stagingValidEgvCount", 5) + val stagingBefore = stagingPrefs.all.toMap() + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_NO_VALID_GLUCOSE)) + assertNothingIrreversible(stagingBefore) + } + + @Test + fun `a missing soak clock writes nothing irreversible`() = runTest { + setPrivate("stagingPresent", true) + setPrivate("stagingValidEgvCount", 6) + val stagingBefore = stagingPrefs.all.toMap() + + val result = plugin.promoteStagingToProduction(allowEarly = false) + + assertThat(result).isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_NOT_SETTLED)) + assertNothingIrreversible(stagingBefore) + } + + @Test + fun `an early promotion without a recent reading writes nothing irreversible`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:21", ageMs = 60_000L) + setPrivate("stagingLastValueAtMs", System.currentTimeMillis() - 30L * 60L * 1000L) + val stagingBefore = stagingPrefs.all.toMap() + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE)) + assertNothingIrreversible(stagingBefore) + } + + @Test + fun `a soak shorter than twelve hours writes nothing irreversible`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:22", ageMs = 60_000L) + setStagingState(StagingState.READY) + val stagingBefore = stagingPrefs.all.toMap() + + val result = plugin.promoteStagingToProduction(allowEarly = false) + + assertThat(result).isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_NOT_SETTLED)) + assertNothingIrreversible(stagingBefore) + } + + @Test + fun `a long soak that is not READY writes nothing irreversible`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:23", ageMs = 13L * 60L * 60L * 1000L) + setStagingState(StagingState.WARMUP) + val stagingBefore = stagingPrefs.all.toMap() + + val result = plugin.promoteStagingToProduction(allowEarly = false) + + assertThat(result).isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_NOT_SETTLED)) + assertNothingIrreversible(stagingBefore) + } + + @Test + fun `the bound runs after the exchange and before select`() = runTest { + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + val startMs = System.currentTimeMillis() - 60_000L + readyStaging(mac = "AA:BB:CC:DD:EE:24", ageMs = 60_000L, startMs = startMs) + val soak = OnePlusCgmDrivers.staging() + var productionWasSoakAtBound = false + var stagingClearedAtBound = false + var identityAdoptedAtBound = false + whenever(activeCalibration.ignoreEntriesBefore(any())).thenAnswer { + productionWasSoakAtBound = OnePlusCgmDrivers.realProduction() === soak + stagingClearedAtBound = stagingPrefs.getString(KEY_PIN, null) == null + identityAdoptedAtBound = productionPrefs.getString(KEY_PIN, null) == "1234" + null + } + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.Ok) + // At the bound the exchange is done. + assertThat(identityAdoptedAtBound).isTrue() + assertThat(stagingClearedAtBound).isTrue() + assertThat(productionWasSoakAtBound).isTrue() + val order = inOrder(preferences, activeCalibration) + order.verify(preferences).get(BooleanKey.BgSourceCreateSensorChange) + order.verify(activeCalibration).ignoreEntriesBefore(any()) + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(soak) + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(startMs)) + } + + @Test + fun `a thrown bound keeps the exchange and is not a silent success`() = runTest { + // The throw does not undo the exchange, and the result is not Ok. The user is told the + // sensor was promoted and what to do. + readyStaging(mac = "AA:BB:CC:DD:EE:25", ageMs = 60_000L) + val soak = OnePlusCgmDrivers.staging() + whenever(rh.gs(SourceStrings.dexcom_oneplus_staging_promote_bound_failed)).thenReturn(BOUND_FAILED_TEXT) + whenever(activeCalibration.ignoreEntriesBefore(any())).thenThrow(IllegalStateException("bound failed")) + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.OkBoundFailed) + verify(activeCalibration).ignoreEntriesBefore(any()) + assertThat(productionPrefs.getString(KEY_PIN, null)).isEqualTo("1234") + assertThat(stagingPrefs.getString(KEY_PIN, null)).isNull() + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(soak) + assertThat(alerts).containsExactly(BOUND_FAILED_TEXT) + assertThat(logger.errors).contains(BOUND_FAILED_TEXT) + } + + @Test + fun `a failure after the bound keeps the exchange and is not a complete success`() = runTest { + // load() / resume throws after the bound. The exchange stays. The result reads the + // production identity instead of announcing Ok. + readyStaging(mac = "AA:BB:CC:DD:EE:26", ageMs = 60_000L) + val soak = OnePlusCgmDrivers.staging() + whenever(rh.gs(SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed)).thenReturn(FOLLOW_UP_TEXT) + val steps = mutableListOf() + whenever(activeCalibration.ignoreEntriesBefore(any())).thenAnswer { + steps.add("bound") + null + } + val throwingStore = mock() + whenever(throwingStore.load()).thenAnswer { + steps.add("resume") + throw IllegalStateException("resume failed after the bound") + } + OnePlusCgmDriverReal::class.java.getDeclaredField("sensorStore").apply { + isAccessible = true + set(soak, throwingStore) + } + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.OkFollowUpFailed(productionIdentityPresent = true)) + assertThat(steps).containsExactly("bound", "resume").inOrder() + assertThat(productionPrefs.getString(KEY_PIN, null)).isEqualTo("1234") + assertThat(stagingPrefs.getString(KEY_PIN, null)).isNull() + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(soak) + assertThat(alerts).containsExactly(FOLLOW_UP_TEXT) + assertThat(logger.errors).contains(FOLLOW_UP_TEXT) + } + + @Test + fun `a thrown bound wins when the follow-up also fails`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:29", ageMs = 60_000L) + val soak = OnePlusCgmDrivers.staging() + whenever(rh.gs(SourceStrings.dexcom_oneplus_staging_promote_bound_failed)).thenReturn(BOUND_FAILED_TEXT) + whenever(rh.gs(SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed)).thenReturn(FOLLOW_UP_TEXT) + whenever(activeCalibration.ignoreEntriesBefore(any())).thenThrow(IllegalStateException("bound failed")) + val throwingStore = mock() + whenever(throwingStore.load()).thenThrow(IllegalStateException("resume failed after the bound")) + OnePlusCgmDriverReal::class.java.getDeclaredField("sensorStore").apply { + isAccessible = true + set(soak, throwingStore) + } + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.OkBoundFailed) + assertThat(productionPrefs.getString(KEY_PIN, null)).isEqualTo("1234") + assertThat(stagingPrefs.getString(KEY_PIN, null)).isNull() + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(soak) + } + + @Test + fun `a follow-up failure with no production identity is not a complete success`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:2A", ageMs = 60_000L) + val soak = OnePlusCgmDrivers.staging() + whenever(rh.gs(SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed_no_identity)) + .thenReturn(FOLLOW_UP_NO_IDENTITY_TEXT) + val throwingStore = mock() + whenever(throwingStore.load()).thenAnswer { + productionPrefs.edit().remove(KEY_PIN).commit() + throw IllegalStateException("resume failed after the bound") + } + OnePlusCgmDriverReal::class.java.getDeclaredField("sensorStore").apply { + isAccessible = true + set(soak, throwingStore) + } + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.OkFollowUpFailed(productionIdentityPresent = false)) + assertThat(productionPrefs.getString(KEY_PIN, null)).isNull() + assertThat(OnePlusCgmDrivers.default()).isSameInstanceAs(soak) + assertThat(alerts).containsExactly(FOLLOW_UP_NO_IDENTITY_TEXT) + } + + @Test + fun `promotion texts distinguish refusal, a failed bound, and a later failure`() { + val english = readResource("src/androidMain/res/values/strings.xml") + assertThat(english).contains( + "Sensor promoted, but older calibration entries could not be ignored. " + + "Remove fingerstick calibrations taken before this switch, then calibrate again if needed.", + ) + assertThat( + dexcomOnePlusPromotionMessage( + result = PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT), + ok = "ok", + boundFailed = "bound", + followUpIdentityPresent = "follow", + followUpIdentityMissing = "missing", + rejectedAbsent = "absent", + rejectedNotSettled = "settling", + rejectedNoGlucose = "glucose", + rejectedNoRecentGlucose = "recent", + ), + ).isEqualTo("absent") + assertThat( + dexcomOnePlusPromotionMessage( + result = PromotionResult.OkBoundFailed, + ok = "ok", + boundFailed = "bound", + followUpIdentityPresent = "follow", + followUpIdentityMissing = "missing", + rejectedAbsent = "absent", + rejectedNotSettled = "settling", + rejectedNoGlucose = "glucose", + rejectedNoRecentGlucose = "recent", + ), + ).isEqualTo("bound") + assertThat( + dexcomOnePlusPromotionMessage( + result = PromotionResult.OkFollowUpFailed(productionIdentityPresent = true), + ok = "ok", + boundFailed = "bound", + followUpIdentityPresent = "follow", + followUpIdentityMissing = "missing", + rejectedAbsent = "absent", + rejectedNotSettled = "settling", + rejectedNoGlucose = "glucose", + rejectedNoRecentGlucose = "recent", + ), + ).isEqualTo("follow") + assertThat( + dexcomOnePlusPromotionMessage( + result = PromotionResult.OkFollowUpFailed(productionIdentityPresent = false), + ok = "ok", + boundFailed = "bound", + followUpIdentityPresent = "follow", + followUpIdentityMissing = "missing", + rejectedAbsent = "absent", + rejectedNotSettled = "settling", + rejectedNoGlucose = "glucose", + rejectedNoRecentGlucose = "recent", + ), + ).isEqualTo("missing") + assertThat( + dexcomOnePlusPromotionMessage( + result = PromotionResult.Ok, + ok = "ok", + boundFailed = "bound", + followUpIdentityPresent = "follow", + followUpIdentityMissing = "missing", + rejectedAbsent = "absent", + rejectedNotSettled = "settling", + rejectedNoGlucose = "glucose", + rejectedNoRecentGlucose = "recent", + ), + ).isEqualTo("ok") + } + + @Test + fun `promotion shows the promoted driver's phase, not the retired one`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:27", ageMs = 60_000L) + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY)) + assertThat(plugin.warmup.value.phase).isEqualTo(OnePlusWarmupState.Phase.READY) + + val result = plugin.promoteStagingToProduction(allowEarly = true) + + assertThat(result).isEqualTo(PromotionResult.Ok) + assertThat(plugin.warmup.value.phase).isEqualTo(OnePlusWarmupState.Phase.IDLE) + } + + @Test + fun `after promotion the live link writes its MAC into the production file`() = runTest { + val mac = "AA:BB:CC:DD:EE:28" + readyStaging(mac = mac, ageMs = 60_000L) + val promoted = OnePlusCgmDrivers.staging() + bindDriverContext(promoted) + + assertThat(plugin.promoteStagingToProduction(allowEarly = true)).isEqualTo(PromotionResult.Ok) + + promoted.onAuthSucceeded(mac, ByteArray(16) { 7 }) + + assertThat(productionPrefs.getString(KEY_MAC, null)).isEqualTo(mac) + assertThat(stagingPrefs.getString(KEY_MAC, null)).isNull() + assertThat(stagingPrefs.getString(KEY_PIN, null)).isNull() + assertThat(promoted.sensorStore()?.load()?.identity?.pin).isEqualTo("1234") + } + + @Test + fun `the settle countdown is set by a state refresh and cleared by a cancel`() { + readyStaging(mac = "AA:BB:CC:DD:EE:30", ageMs = HOUR_MS) + assertThat(plugin.stagingSettleRemainingMs.value).isNull() + + refreshStagingState() + + assertCountdownAboutElevenHours() + plugin.cancelStaging() + assertThat(plugin.stagingSettleRemainingMs.value).isNull() + } + + @Test + fun `the settle countdown is cleared by a promotion`() = runTest { + readyStaging(mac = "AA:BB:CC:DD:EE:31", ageMs = HOUR_MS) + refreshStagingState() + assertCountdownAboutElevenHours() + + assertThat(plugin.promoteStagingToProduction(allowEarly = true)).isEqualTo(PromotionResult.Ok) + + assertThat(plugin.stagingSettleRemainingMs.value).isNull() + } + + @Test + fun `the settle countdown is cleared when a stored pre-soak cannot be resumed`() { + // A slot is marked present, but it has no MAC, so the driver refuses to resume it. + // The resume attaches the driver, and that builds a scanner from these two services. + whenever(context.getSystemService(Context.BLUETOOTH_SERVICE)).thenReturn(mock()) + whenever(context.getSystemService(Context.POWER_SERVICE)).thenReturn(mock()) + val stagingStore = OnePlusSensorStore(context, OnePlusCgmDrivers.STAGING_NAMESPACE) + stagingStore.saveIdentity(OnePlusSensorIdentity(pin = "1234", serial = "SOAK1")) + stagingStore.saveSlotProgress(present = true, validEgvCount = 6) + stagingStore.saveSessionStartIfAbsent(System.currentTimeMillis() - HOUR_MS) + setPrivate("stagingPresent", true) + refreshStagingState() + assertCountdownAboutElevenHours() + + val resumed = DexcomOnePlusPlugin::class.java.getDeclaredMethod("resumeStagingSessionIfStored") + .apply { isAccessible = true } + .invoke(plugin) as Boolean + + assertThat(resumed).isFalse() + assertThat(plugin.stagingSettleRemainingMs.value).isNull() + } + + private fun refreshStagingState() { + DexcomOnePlusPlugin::class.java.getDeclaredMethod("refreshStagingState") + .apply { isAccessible = true } + .invoke(plugin) + } + + /** The soak started one hour ago, so about eleven of the twelve hours are left. */ + private fun assertCountdownAboutElevenHours() { + val remaining = plugin.stagingSettleRemainingMs.value + assertThat(remaining).isNotNull() + assertThat(remaining!!).isAtMost(11L * HOUR_MS) + assertThat(remaining).isGreaterThan(11L * HOUR_MS - 60_000L) + } + + private suspend fun assertNothingIrreversible(stagingBefore: Map) { + verify(activeCalibration, never()).ignoreEntriesBefore(any()) + verify(persistenceLayer, never()).insertCgmSourceData(any(), any(), any(), anyOrNull()) + assertThat(productionPrefs.getString(KEY_PIN, null)).isNull() + assertThat(productionPrefs.getString(KEY_MAC, null)).isNull() + assertThat(OnePlusCgmDrivers.default()).isNotSameInstanceAs(OnePlusCgmDrivers.staging()) + // getAll() is the live map. The copy taken before promote must still match. + assertThat(stagingPrefs.all.toMap()).isEqualTo(stagingBefore) + } + + private fun readyStaging(mac: String, ageMs: Long, startMs: Long = System.currentTimeMillis() - ageMs) { + val stagingStore = OnePlusSensorStore(context, OnePlusCgmDrivers.STAGING_NAMESPACE) + stagingStore.saveIdentity(OnePlusSensorIdentity(pin = "1234", serial = "SOAK1")) + stagingStore.startSessionForSensor(mac, startMs, null) + setPrivate("stagingPresent", true) + setPrivate("stagingValidEgvCount", 6) + setPrivate("stagingLastValueMgdl", 120.0) + setPrivate("stagingLastValueAtMs", System.currentTimeMillis()) + } + + private fun setStagingState(state: StagingState) { + @Suppress("UNCHECKED_CAST") + val flow = DexcomOnePlusPlugin::class.java.getDeclaredField("_stagingState") + .apply { isAccessible = true } + .get(plugin) as MutableStateFlow + flow.value = state + } + + private fun readResource(relative: String): String { + val file = listOf(File(relative), File("plugins/source/$relative")).firstOrNull { it.isFile } + ?: error("missing $relative from ${File(".").absolutePath}") + return file.readText() + } + + private class RecordingLogger : AAPSLogger by AAPSLoggerTest() { + val errors = mutableListOf() + override fun error(tag: LTag, message: String, throwable: Throwable) { + errors += message + } + } + + private fun setPrivate(name: String, value: Any?) { + DexcomOnePlusPlugin::class.java.getDeclaredField(name).apply { isAccessible = true }.set(plugin, value) + } + + /** Platform and store, without `attach`: that call reads `Build.MANUFACTURER`. */ + private fun bindDriverContext(driver: OnePlusCgmDriverReal) { + OnePlusCgmDriverReal::class.java.getDeclaredField("platform") + .apply { isAccessible = true }.set(driver, OnePlusAndroidPlatform(context)) + OnePlusCgmDriverReal::class.java.getDeclaredField("sensorStore") + .apply { isAccessible = true } + .set(driver, OnePlusSensorStore(context, OnePlusCgmDrivers.STAGING_NAMESPACE)) + } + + companion object { + private const val PRODUCTION_PREFS_NAME = "dexcom_oneplus_sensor" + private const val STAGING_PREFS_NAME = "dexcom_oneplus_sensor_staging" + private const val KEY_PIN = "pin" + private const val KEY_MAC = "last_mac" + private const val HOUR_MS = 60L * 60L * 1000L + private const val BOUND_FAILED_TEXT = + "Sensor promoted, but older calibration entries could not be ignored. " + + "Remove fingerstick calibrations taken before this switch, then calibrate again if needed." + private const val FOLLOW_UP_TEXT = + "Sensor promoted, but reconnecting it failed. The production sensor is the one just promoted." + private const val FOLLOW_UP_NO_IDENTITY_TEXT = + "A step after the exchange failed, and the production sensor identity is missing." + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt new file mode 100644 index 000000000000..d0b65e63511e --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt @@ -0,0 +1,315 @@ +package app.aaps.plugins.source + +import android.content.Context +import android.content.SharedPreferences +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.GlucoseUnit +import app.aaps.core.data.model.TE +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.bus.RxBus +import app.aaps.core.interfaces.rx.events.EventRefreshOverview +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey +import app.aaps.shared.tests.SharedPreferencesMock +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock +import org.mockito.kotlin.after +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.clearInvocations +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.timeout +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.lang.reflect.Field + +/** + * Age anchor call sites and the once-per-session repair. + * + * The repair key is a user setting, on by default. The tests set it explicitly: with it off a + * refresh writes nothing, with it on the guards below still apply. + */ +class DexcomOnePlusSensorAgeRepairTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences + @Mock lateinit var config: Config + @Mock lateinit var context: Context + @Mock lateinit var persistenceLayer: PersistenceLayer + + + private val notificationManager: NotificationManager = mock() + private val activePlugin: ActivePlugin = mock() + private val prefs: SharedPreferences = SharedPreferencesMock() + + private lateinit var plugin: DexcomOnePlusPlugin + + @BeforeEach + fun setup() = runTest { + rxBus = mock() + setBuildField("MANUFACTURER", "Google") + setBuildField("MODEL", "Pixel") + whenever(context.applicationContext).thenReturn(context) + whenever(context.getSharedPreferences(PRODUCTION_PREFS, Context.MODE_PRIVATE)).thenReturn(prefs) + whenever(persistenceLayer.insertCgmSourceData(any(), any(), any(), anyOrNull())).thenAnswer { invocation -> + val result = PersistenceLayer.TransactionResult() + val stamp = invocation.arguments[3] as Long? + if (stamp != null) { + result.sensorInsertionsInserted.add(sensorChange(stamp)) + } + result + } + whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())) + .thenReturn(emptyList()) + plugin = DexcomOnePlusPlugin( + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + activePlugin, rxBus, + ) + DexcomOnePlusIngest.reset() + } + + @Test + fun `a start with no sensor change keeps the auto time`() = runTest { + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(null) + val auto = System.currentTimeMillis() + + plugin.onSensorSessionStarted(MAC, previousMac = null, startMs = auto) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(auto)) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(auto) + } + + @Test + fun `a start prefers a manual sensor change from the last day`() = runTest { + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + whenever(preferences.get(DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange)).thenReturn(true) + val auto = System.currentTimeMillis() + val manual = auto - 3 * HOUR_MS + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(manual)) + + plugin.onSensorSessionStarted(MAC, previousMac = null, startMs = auto) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(manual)) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(manual) + } + + @Test + fun `a start ignores a sensor change that is later or older than a day`() = runTest { + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + val auto = System.currentTimeMillis() + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)) + .thenReturn(sensorChange(auto + HOUR_MS)) + + plugin.onSensorSessionStarted("AA:BB:CC:DD:EE:02", previousMac = null, startMs = auto) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(auto)) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(auto) + + val stale = auto - 25 * HOUR_MS + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(stale)) + plugin.onSensorSessionStarted("AA:BB:CC:DD:EE:03", previousMac = null, startMs = auto + 1L) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(auto + 1L)) + } + + @Test + fun `the first reading uses the manual sensor change as the session start`() = runTest { + whenever(preferences.get(DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange)).thenReturn(true) + val auto = System.currentTimeMillis() + val manual = auto - 2 * HOUR_MS + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(manual)) + val sample = OnePlusGlucoseSample(mgdl = 110.0, timestampMs = auto, sequence = 1L) + + ingest(sample) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(null)) + assertThat(awaitSessionStart()).isEqualTo(manual) + } + + @Test + fun `the manual anchor switch defaults to on is a user setting and is not exported`() { + val key = DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange + assertThat(key.defaultValue).isTrue() + assertThat(key.engineeringModeOnly).isFalse() + assertThat(key.exportable).isFalse() + } + + @Test + fun `the three sensor change settings are on by default and shown to every user`() { + val keys = listOf( + DexcomOnePlusBooleanKey.RepairMissingSensorChange, + DexcomOnePlusBooleanKey.CorrectSensorStart, + DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange, + ) + for (key in keys) { + assertThat(key.defaultValue).isTrue() + assertThat(key.engineeringModeOnly).isFalse() + } + assertThat(plugin.getPreferenceScreenContent().items).containsAtLeastElementsIn(keys) + } + + @Test + fun `a start with the anchor switch off does not roll the date back`() = runTest { + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + val auto = System.currentTimeMillis() + val manual = auto - 3 * HOUR_MS + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(manual)) + + plugin.onSensorSessionStarted("AA:BB:CC:DD:EE:21", previousMac = null, startMs = auto) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(auto)) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(auto) + } + + @Test + fun `the first reading with the anchor switch off keeps the reading time`() = runTest { + val auto = System.currentTimeMillis() + val manual = auto - 2 * HOUR_MS + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(manual)) + val sample = OnePlusGlucoseSample(mgdl = 110.0, timestampMs = auto, sequence = 7L) + + ingest(sample) + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(null)) + assertThat(awaitSessionStart()).isEqualTo(auto) + } + + @Test + fun `repair switched off writes nothing`() = runTest { + assertThat(DexcomOnePlusBooleanKey.RepairMissingSensorChange.defaultValue).isTrue() + // Stubbed explicitly: the point is the switch-off path, not the Mockito default. + whenever(preferences.get(DexcomOnePlusBooleanKey.RepairMissingSensorChange)).thenReturn(false) + // Create-sensor-change stays on, as in the tests below. Without this stub Mockito + // returns false and the second guard would refuse the write even if the repair switch + // were gone, so the test would pass for the wrong reason. + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + val startedAt = System.currentTimeMillis() - 26 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor(MAC, startedAt, null) + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)) + .thenReturn(sensorChange(System.currentTimeMillis() - 13 * 24 * HOUR_MS)) + + refreshLifecycle() + + verify(persistenceLayer, after(500L).never()) + .insertCgmSourceData(any(), any(), any(), anyOrNull()) + verify(rxBus, never()).send(any()) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(startedAt) + } + + @Test + fun `repair off for create sensor change writes nothing`() = runTest { + whenever(preferences.get(DexcomOnePlusBooleanKey.RepairMissingSensorChange)).thenReturn(true) + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(false) + val startedAt = System.currentTimeMillis() - 26 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor("AA:BB:CC:DD:EE:11", startedAt, null) + + refreshLifecycle() + + verify(persistenceLayer, after(500L).never()) + .insertCgmSourceData(any(), any(), any(), anyOrNull()) + verify(rxBus, never()).send(any()) + assertThat(prefs.getLong(KEY_SESSION_START, 0L)).isEqualTo(startedAt) + } + + @Test + fun `a sensor whose therapy event is missing gets its age put back once`() = runTest { + whenever(preferences.get(DexcomOnePlusBooleanKey.RepairMissingSensorChange)).thenReturn(true) + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + val startedAt = System.currentTimeMillis() - 26 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor("AA:BB:CC:DD:EE:10", startedAt, null) + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)) + .thenReturn(sensorChange(System.currentTimeMillis() - 13 * 24 * HOUR_MS)) + + refreshLifecycle() + + verify(persistenceLayer, timeout(2_000L)).insertCgmSourceData(any(), any(), any(), eq(startedAt)) + verify(rxBus, timeout(2_000L)).send(any()) + + clearInvocations(persistenceLayer, rxBus) + refreshLifecycle() + + verify(persistenceLayer, after(500L).never()) + .insertCgmSourceData(any(), any(), any(), anyOrNull()) + verify(rxBus, never()).send(any()) + } + + @Test + fun `an age that already matches is left alone`() = runTest { + whenever(preferences.get(DexcomOnePlusBooleanKey.RepairMissingSensorChange)).thenReturn(true) + whenever(preferences.get(BooleanKey.BgSourceCreateSensorChange)).thenReturn(true) + val startedAt = System.currentTimeMillis() - 26 * HOUR_MS + OnePlusSensorStore(context).startSessionForSensor("AA:BB:CC:DD:EE:12", startedAt, null) + whenever(persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)).thenReturn(sensorChange(startedAt)) + + refreshLifecycle() + + verify(persistenceLayer, after(500L).never()) + .insertCgmSourceData(any(), any(), any(), anyOrNull()) + verify(rxBus, never()).send(any()) + } + + private fun setBuildField(name: String, value: String) { + val field = android.os.Build::class.java.getDeclaredField(name) + val unsafeClass = Class.forName("sun.misc.Unsafe") + val unsafeField = unsafeClass.getDeclaredField("theUnsafe") + unsafeField.isAccessible = true + val unsafe = unsafeField.get(null) + val base = unsafeClass.getMethod("staticFieldBase", Field::class.java).invoke(unsafe, field) + val offset = unsafeClass.getMethod("staticFieldOffset", Field::class.java).invoke(unsafe, field) as Long + unsafeClass.getMethod("putObject", Any::class.java, java.lang.Long.TYPE, Any::class.java) + .invoke(unsafe, base, offset, value) + } + + private fun refreshLifecycle() { + DexcomOnePlusPlugin::class.java.getDeclaredMethod("refreshProductionLifecycle") + .apply { isAccessible = true } + .invoke(plugin) + } + + private fun awaitSessionStart(): Long { + val deadline = System.currentTimeMillis() + 2_000L + var stored = prefs.getLong(KEY_SESSION_START, 0L) + while (stored == 0L && System.currentTimeMillis() < deadline) { + Thread.sleep(20) + stored = prefs.getLong(KEY_SESSION_START, 0L) + } + return stored + } + + private fun ingest(sample: OnePlusGlucoseSample) { + val store = OnePlusSensorStore(context) + DexcomOnePlusPlugin::class.java.getDeclaredMethod( + "ingestToLoop", + OnePlusGlucoseSample::class.java, + OnePlusSensorStore::class.java, + ).apply { isAccessible = true }.invoke(plugin, sample, store) + } + + private fun sensorChange(timestamp: Long): TE = TE( + id = 11L, + timestamp = timestamp, + type = TE.Type.SENSOR_CHANGE, + glucoseUnit = GlucoseUnit.MGDL, + ) + + companion object { + private const val HOUR_MS = 60L * 60L * 1000L + private const val MAC = "AA:BB:CC:DD:EE:01" + private const val PRODUCTION_PREFS = "dexcom_oneplus_sensor" + private const val KEY_SESSION_START = "session_start_ms" + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchorTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchorTest.kt new file mode 100644 index 000000000000..e3776fd18037 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchorTest.kt @@ -0,0 +1,60 @@ +package app.aaps.plugins.source + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** Rules of [DexcomOnePlusSensorChangeAnchor.resolve]. */ +class DexcomOnePlusSensorChangeAnchorTest { + + private val now = 1_700_100_000_000L + private val autoStartMs = now + private val hour = 60L * 60L * 1000L + + @Test + fun `resolve keeps the auto start when no sensor change exists yet`() { + val resolved = DexcomOnePlusSensorChangeAnchor.resolve( + autoStartMs = autoStartMs, + lastSensorChangeMs = null, + now = now, + ) + + assertThat(resolved).isEqualTo(autoStartMs) + } + + @Test + fun `resolve prefers a recent manual sensor change logged before the auto start`() { + val manualInsertMs = autoStartMs - 3 * hour + + val resolved = DexcomOnePlusSensorChangeAnchor.resolve( + autoStartMs = autoStartMs, + lastSensorChangeMs = manualInsertMs, + now = now, + ) + + assertThat(resolved).isEqualTo(manualInsertMs) + } + + @Test + fun `resolve ignores a manual sensor change older than the lookback window`() { + val staleManualMs = autoStartMs - 25 * hour + + val resolved = DexcomOnePlusSensorChangeAnchor.resolve( + autoStartMs = autoStartMs, + lastSensorChangeMs = staleManualMs, + now = now, + ) + + assertThat(resolved).isEqualTo(autoStartMs) + } + + @Test + fun `resolve ignores a sensor change that is not earlier than the auto start`() { + val resolved = DexcomOnePlusSensorChangeAnchor.resolve( + autoStartMs = autoStartMs, + lastSensorChangeMs = autoStartMs + hour, + now = now, + ) + + assertThat(resolved).isEqualTo(autoStartMs) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrectionTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrectionTest.kt new file mode 100644 index 000000000000..60a7a7a93877 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrectionTest.kt @@ -0,0 +1,105 @@ +package app.aaps.plugins.source + +import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection.Verdict +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * The step-cap case checks that a free timestamp is never more than 60 steps away. + */ +class DexcomOnePlusSensorStartCorrectionTest { + + private val now = 1_700_000_000_000L + private val hour = 60L * 60L * 1000L + private val day = 24L * hour + + @Test + fun `an earlier time on the running sensor is accepted`() { + assertThat( + DexcomOnePlusSensorStartCorrection.validate( + newStartMs = now - 8 * hour, + currentStartMs = now - 2 * hour, + nowMs = now, + ), + ).isEqualTo(Verdict.Accepted) + } + + @Test + fun `a later time is accepted too — the app may have been the early one`() { + assertThat( + DexcomOnePlusSensorStartCorrection.validate( + newStartMs = now - 1 * hour, + currentStartMs = now - 6 * hour, + nowMs = now, + ), + ).isEqualTo(Verdict.Accepted) + } + + @Test + fun `the future is refused`() { + assertThat( + DexcomOnePlusSensorStartCorrection.validate( + newStartMs = now + 1, + currentStartMs = now - 2 * hour, + nowMs = now, + ), + ).isEqualTo(Verdict.InFuture) + } + + @Test + fun `older than a whole sensor life is refused`() { + assertThat( + DexcomOnePlusSensorStartCorrection.validate( + newStartMs = now - 11 * day, + currentStartMs = now - 2 * hour, + nowMs = now, + ), + ).isEqualTo(Verdict.TooOld) + } + + @Test + fun `the last hours of the grace window are still allowed`() { + assertThat( + DexcomOnePlusSensorStartCorrection.validate( + newStartMs = now - (10 * day + 11 * hour), + currentStartMs = now - 2 * hour, + nowMs = now, + ), + ).isEqualTo(Verdict.Accepted) + } + + @Test + fun `with no session there is nothing to correct`() { + assertThat( + DexcomOnePlusSensorStartCorrection.validate( + newStartMs = now - 2 * hour, + currentStartMs = 0L, + nowMs = now, + ), + ).isEqualTo(Verdict.NoSession) + } + + @Test + fun `a moment another sensor change already holds is stepped over`() { + val taken = setOf(now, now + 1_000L) + + assertThat(DexcomOnePlusSensorStartCorrection.freeTimestamp(now, taken)).isEqualTo(now + 2_000L) + assertThat(DexcomOnePlusSensorStartCorrection.freeTimestamp(now, emptySet())).isEqualTo(now) + assertThat(DexcomOnePlusSensorStartCorrection.freeTimestamp(now, setOf(now)) - now).isAtMost(1_000L) + } + + @Test + fun `the walk stops after sixty seconds`() { + val taken = (0..60).map { now + it * 1_000L }.toSet() + + assertThat(DexcomOnePlusSensorStartCorrection.freeTimestamp(now, taken) - now).isEqualTo(60_000L) + } + + @Test + fun `the clean-up reaches back to whichever date is older`() { + assertThat(DexcomOnePlusSensorStartCorrection.cleanupFrom(newStartMs = now - 8 * hour, currentStartMs = now - 2 * hour)) + .isEqualTo(now - 8 * hour) + assertThat(DexcomOnePlusSensorStartCorrection.cleanupFrom(newStartMs = now - 1 * hour, currentStartMs = now - 6 * hour)) + .isEqualTo(now - 6 * hour) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSharedCodeTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSharedCodeTest.kt new file mode 100644 index 000000000000..0679fb103d3f --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSharedCodeTest.kt @@ -0,0 +1,131 @@ +package app.aaps.plugins.source + +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.interfaces.source.CgmWarmupStatus +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The Dexcom ONE+ ingest gate and warm-up mapping, written with kotlin.test only. + * + * The ingest gate is guarded by `AapsLock` rather than `synchronized`, so this code does not + * depend on the JVM. Test names stay free of commas, so the class can move to a shared test source + * set unchanged when the driver gets more targets. + */ +class DexcomOnePlusSharedCodeTest { + + @BeforeTest + fun clearDedup() = DexcomOnePlusIngest.reset() + + @AfterTest + fun clearDedupAfter() = DexcomOnePlusIngest.reset() + + // ---- ingest dedup, which now runs under AapsLock rather than synchronized ---- + + @Test + fun `a first reading is accepted and the same one again is not`() { + val sample = OnePlusGlucoseSample(mgdl = 120.0, timestampMs = 1_000_000L, sequence = 7L) + assertTrue(DexcomOnePlusIngest.shouldAccept(sample)) + assertFalse(DexcomOnePlusIngest.shouldAccept(sample)) + } + + @Test + fun `a reading inside the dedup window is dropped and one outside it is taken`() { + val first = OnePlusGlucoseSample(mgdl = 120.0, timestampMs = 1_000_000L, sequence = 1L) + assertTrue(DexcomOnePlusIngest.shouldAccept(first)) + val tooClose = first.copy(timestampMs = first.timestampMs + DexcomOnePlusIngest.DEDUP_WINDOW_MS - 1, sequence = 2L) + assertFalse(DexcomOnePlusIngest.shouldAccept(tooClose)) + val farEnough = first.copy(timestampMs = first.timestampMs + DexcomOnePlusIngest.DEDUP_WINDOW_MS, sequence = 3L) + assertTrue(DexcomOnePlusIngest.shouldAccept(farEnough)) + } + + @Test + fun `a sequence at or below the seeded high water mark is refused`() { + DexcomOnePlusIngest.seed(lastSequence = 10L, recentTimestampsMs = emptyList()) + assertFalse(DexcomOnePlusIngest.shouldAccept(OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 5_000_000L, sequence = 10L))) + assertTrue(DexcomOnePlusIngest.shouldAccept(OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 5_000_000L, sequence = 11L))) + } + + @Test + fun `reset clears the floor so a new sensor low sequence is taken again`() { + DexcomOnePlusIngest.seed(lastSequence = 500L, recentTimestampsMs = emptyList()) + val fresh = OnePlusGlucoseSample(mgdl = 100.0, timestampMs = 9_000_000L, sequence = 3L) + assertFalse(DexcomOnePlusIngest.shouldAccept(fresh)) + DexcomOnePlusIngest.reset() + assertTrue(DexcomOnePlusIngest.shouldAccept(fresh)) + } + + @Test + fun `ingest is blocked only while the sensor is warming`() { + assertTrue(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.WARMING)) + assertFalse(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.PAIRING)) + assertFalse(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.IDLE)) + assertFalse(DexcomOnePlusIngest.isWarmupBlockingIngest(OnePlusWarmupState.Phase.READY)) + } + + // ---- the slope to arrow mapping ---- + + @Test + fun `a missing slope stays NONE rather than becoming flat`() { + assertEquals(TrendArrow.NONE, DexcomOnePlusIngest.trendArrowFor(null)) + } + + @Test + fun `each slope step maps to its arrow`() { + assertEquals(TrendArrow.DOUBLE_UP, DexcomOnePlusIngest.trendArrowFor(3.0)) + assertEquals(TrendArrow.SINGLE_UP, DexcomOnePlusIngest.trendArrowFor(2.0)) + assertEquals(TrendArrow.FORTY_FIVE_UP, DexcomOnePlusIngest.trendArrowFor(1.0)) + assertEquals(TrendArrow.FLAT, DexcomOnePlusIngest.trendArrowFor(0.0)) + assertEquals(TrendArrow.FORTY_FIVE_DOWN, DexcomOnePlusIngest.trendArrowFor(-1.5)) + assertEquals(TrendArrow.SINGLE_DOWN, DexcomOnePlusIngest.trendArrowFor(-2.5)) + assertEquals(TrendArrow.DOUBLE_DOWN, DexcomOnePlusIngest.trendArrowFor(-3.0)) + } + + @Test + fun `a mapped reading carries the native source sensor`() { + val gv = DexcomOnePlusIngest.mapToGv( + OnePlusGlucoseSample(mgdl = 142.0, timestampMs = 1_700_000_000_000L, trendSlopeMgdlPerMin = 1.2, sequence = 4L) + ) + assertEquals(SourceSensor.DEXCOM_ONEPLUS_NATIVE, gv.sourceSensor) + assertEquals(142.0, gv.value) + assertEquals(1_700_000_000_000L, gv.timestamp) + assertEquals(TrendArrow.FORTY_FIVE_UP, gv.trendArrow) + } + + // ---- warm-up mapping ---- + + @Test + fun `a terminal warm-up phase shows nothing`() { + assertNull(DexcomOnePlusWarmupMapper.toCgmWarmupStatus(OnePlusWarmupState(OnePlusWarmupState.Phase.READY))) + assertNull(DexcomOnePlusWarmupMapper.toCgmWarmupStatus(OnePlusWarmupState(OnePlusWarmupState.Phase.IDLE))) + assertNull(DexcomOnePlusWarmupMapper.toCgmWarmupStatus(OnePlusWarmupState(OnePlusWarmupState.Phase.FAILED))) + } + + @Test + fun `warming carries the countdown and a total so the ring can fill`() { + val status = DexcomOnePlusWarmupMapper.toCgmWarmupStatus( + OnePlusWarmupState(OnePlusWarmupState.Phase.WARMING, remainingMs = 600_000L) + ) + assertTrue(status != null && status.active) + assertEquals(CgmWarmupStatus.Phase.WARMING, status.phase) + assertEquals(600_000L, status.remainingMs) + assertTrue((status.totalMs ?: 0L) > 0L) + } + + @Test + fun `a reconnect without a deadline has no countdown total`() { + val status = DexcomOnePlusWarmupMapper.toCgmWarmupStatus( + OnePlusWarmupState(OnePlusWarmupState.Phase.RECONNECTING) + ) + assertEquals(CgmWarmupStatus.Phase.RECONNECTING, status?.phase) + assertNull(status?.totalMs) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusStagingTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusStagingTest.kt new file mode 100644 index 000000000000..afdc60d6b055 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusStagingTest.kt @@ -0,0 +1,231 @@ +package app.aaps.plugins.source + +import app.aaps.core.interfaces.source.StagingState +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class DexcomOnePlusStagingTest { + + private val now = 1_000_000_000_000L + private val hour = 60L * 60L * 1000L + + // ---- computeLifecycle ---- + + @Test + fun `lifecycle is null when session start unknown`() { + assertThat(DexcomOnePlusStaging.computeLifecycle(0L, now)).isNull() + } + + @Test + fun `fresh sensor is not end of life`() { + val lc = DexcomOnePlusStaging.computeLifecycle(now - 1 * hour, now)!! + assertThat(lc.endOfLife).isFalse() + assertThat(lc.ageMs).isEqualTo(1 * hour) + assertThat(lc.startedAtEpochMs).isEqualTo(now - 1 * hour) + } + + @Test + fun `sensor near expiry is end of life`() { + // start so that remaining < END_OF_LIFE_MS (12 h): life+grace = 10 d + 12 h, leave 6 h. + val start = now - (DexcomOnePlusStaging.SENSOR_LIFE_MS + DexcomOnePlusStaging.SENSOR_GRACE_MS - 6 * hour) + val lc = DexcomOnePlusStaging.computeLifecycle(start, now)!! + assertThat(lc.endOfLife).isTrue() + } + + // ---- computeStagingState ---- + + @Test + fun `staging absent when no sensor`() { + assertThat(DexcomOnePlusStaging.computeStagingState(present = false, warming = false, sessionStartMs = 0L, validEgvCount = 0, nowMs = now)) + .isEqualTo(StagingState.ABSENT) + } + + @Test + fun `staging warmup while warming`() { + assertThat(DexcomOnePlusStaging.computeStagingState(present = true, warming = true, sessionStartMs = now, validEgvCount = 0, nowMs = now)) + .isEqualTo(StagingState.WARMUP) + } + + @Test + fun `staging settling before minimum settle time`() { + assertThat(DexcomOnePlusStaging.computeStagingState(present = true, warming = false, sessionStartMs = now - 1 * hour, validEgvCount = 10, nowMs = now)) + .isEqualTo(StagingState.SETTLING) + } + + @Test + fun `staging ready after settle time with enough valid egv`() { + assertThat(DexcomOnePlusStaging.computeStagingState(present = true, warming = false, sessionStartMs = now - 13 * hour, validEgvCount = 6, nowMs = now)) + .isEqualTo(StagingState.READY) + } + + @Test + fun `staging still settling when settle time reached but not enough valid egv`() { + assertThat(DexcomOnePlusStaging.computeStagingState(present = true, warming = false, sessionStartMs = now - 13 * hour, validEgvCount = 5, nowMs = now)) + .isEqualTo(StagingState.SETTLING) + } + + // ---- canPromoteEarly (explicit early promotion) ---- + + @Test + fun `early promotion is offered when the sensor reads enough and reads now`() { + assertThat( + DexcomOnePlusStaging.canPromoteEarly( + validEgvCount = DexcomOnePlusStaging.STAGING_MIN_VALID_EGV, + lastValueAtEpochMs = now - 5 * 60_000L, + nowMs = now, + ), + ).isTrue() + } + + @Test + fun `early promotion needs the same evidence as the normal path`() { + assertThat( + DexcomOnePlusStaging.canPromoteEarly( + validEgvCount = DexcomOnePlusStaging.STAGING_MIN_VALID_EGV - 1, + lastValueAtEpochMs = now, + nowMs = now, + ), + ).isFalse() + } + + @Test + fun `a sensor that went silent is never offered for early promotion`() { + // The 12 h soak is what normally proves the sensor lives; without it, freshness must. + assertThat( + DexcomOnePlusStaging.canPromoteEarly( + validEgvCount = 50, + lastValueAtEpochMs = now - DexcomOnePlusStaging.STAGING_MAX_EGV_AGE_MS - 1, + nowMs = now, + ), + ).isFalse() + } + + @Test + fun `a reading exactly at the age limit still counts`() { + assertThat( + DexcomOnePlusStaging.canPromoteEarly( + validEgvCount = 10, + lastValueAtEpochMs = now - DexcomOnePlusStaging.STAGING_MAX_EGV_AGE_MS, + nowMs = now, + ), + ).isTrue() + } + + @Test + fun `no reading at all blocks early promotion`() { + assertThat(DexcomOnePlusStaging.canPromoteEarly(validEgvCount = 10, lastValueAtEpochMs = null, nowMs = now)).isFalse() + assertThat(DexcomOnePlusStaging.canPromoteEarly(validEgvCount = 10, lastValueAtEpochMs = 0L, nowMs = now)).isFalse() + } + + @Test + fun `a reading stamped in the future cannot unlock early promotion`() { + assertThat( + DexcomOnePlusStaging.canPromoteEarly(validEgvCount = 10, lastValueAtEpochMs = now + 60_000L, nowMs = now), + ).isFalse() + } + + // ---- applyWarmupPhase (warm-up latch) ---- + + @Test + fun `connecting during warm-up keeps the slot warming`() { + val d = DexcomOnePlusStaging.applyWarmupPhase(warmupDoneBefore = false, readyPhase = false) + + assertThat(d.warmupDone).isFalse() + assertThat(d.warming).isTrue() + } + + @Test + fun `ready ends the warm-up`() { + val d = DexcomOnePlusStaging.applyWarmupPhase(warmupDoneBefore = false, readyPhase = true) + + assertThat(d.warmupDone).isTrue() + assertThat(d.warming).isFalse() + } + + @Test + fun `a later reconnect cycle cannot send a settled slot back to warm-up`() { + // This is the defect the latch fixes: a healthy sensor reconnects every radio cycle for life. + val d = DexcomOnePlusStaging.applyWarmupPhase(warmupDoneBefore = true, readyPhase = false) + + assertThat(d.warmupDone).isTrue() + assertThat(d.warming).isFalse() + } + + @Test + fun `a sensor that failed before warm-up is never shown as settling`() { + // A dead sensor must not display a 12 h stabilisation countdown it can never finish. + val d = DexcomOnePlusStaging.applyWarmupPhase(warmupDoneBefore = false, readyPhase = false) + val state = DexcomOnePlusStaging.computeStagingState( + present = true, + warming = d.warming, + sessionStartMs = now - 13 * hour, + validEgvCount = 0, + nowMs = now, + ) + + assertThat(state).isEqualTo(StagingState.WARMUP) + } + + @Test + fun `a settled slot still reaches ready after a reconnect cycle`() { + val d = DexcomOnePlusStaging.applyWarmupPhase(warmupDoneBefore = true, readyPhase = false) + val state = DexcomOnePlusStaging.computeStagingState( + present = true, + warming = d.warming, + sessionStartMs = now - 13 * hour, + validEgvCount = DexcomOnePlusStaging.STAGING_MIN_VALID_EGV, + nowMs = now, + ) + + assertThat(state).isEqualTo(StagingState.READY) + } + + // ---- isSameTransmitter: the cross-slot guard's rule ---- + + @Test + fun `same transmitter whatever the case the mac was stored in`() { + assertThat(DexcomOnePlusStaging.isSameTransmitter("c8:4e:07:b2:31:1f", "C8:4E:07:B2:31:1F")).isTrue() + assertThat(DexcomOnePlusStaging.isSameTransmitter("C8:4E:07:B2:31:1F", "c8:4e:07:b2:31:1f")).isTrue() + assertThat(DexcomOnePlusStaging.isSameTransmitter(" C8:4E:07:B2:31:1F ", "C8:4E:07:B2:31:1F")).isTrue() + } + + @Test + fun `different transmitters are not the same`() { + assertThat(DexcomOnePlusStaging.isSameTransmitter("C8:4E:07:B2:31:1F", "D1:22:9C:4E:80:74")).isFalse() + } + + @Test + fun `an empty slot never claims a transmitter`() { + // A slot with nothing stored must not block a start: that would make the guard refuse the + // first pairing of every sensor. + assertThat(DexcomOnePlusStaging.isSameTransmitter(null, "C8:4E:07:B2:31:1F")).isFalse() + assertThat(DexcomOnePlusStaging.isSameTransmitter("", "C8:4E:07:B2:31:1F")).isFalse() + assertThat(DexcomOnePlusStaging.isSameTransmitter(" ", "C8:4E:07:B2:31:1F")).isFalse() + } + + @Test + fun `a blank target never matches a stored sensor`() { + assertThat(DexcomOnePlusStaging.isSameTransmitter("C8:4E:07:B2:31:1F", "")).isFalse() + assertThat(DexcomOnePlusStaging.isSameTransmitter("C8:4E:07:B2:31:1F", " ")).isFalse() + } + + // ---- settleRemainingMs ---- + + @Test + fun `settle countdown is the time left to 12 hours`() { + assertThat(DexcomOnePlusStaging.settleRemainingMs(present = true, sessionStartMs = now - 3 * hour, nowMs = now)) + .isEqualTo(9 * hour) + } + + @Test + fun `settle countdown is null once the soak is long enough`() { + assertThat(DexcomOnePlusStaging.settleRemainingMs(present = true, sessionStartMs = now - 12 * hour, nowMs = now)).isNull() + assertThat(DexcomOnePlusStaging.settleRemainingMs(present = true, sessionStartMs = now - 20 * hour, nowMs = now)).isNull() + } + + @Test + fun `settle countdown is null without a staging sensor or a start`() { + assertThat(DexcomOnePlusStaging.settleRemainingMs(present = false, sessionStartMs = now - 3 * hour, nowMs = now)).isNull() + assertThat(DexcomOnePlusStaging.settleRemainingMs(present = true, sessionStartMs = 0L, nowMs = now)).isNull() + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapperTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapperTest.kt new file mode 100644 index 000000000000..7e0adcb80bb2 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapperTest.kt @@ -0,0 +1,84 @@ +package app.aaps.plugins.source + +import app.aaps.core.interfaces.source.CgmWarmupStatus +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.source.compose.DexcomOnePlusWarmupCountdown +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class DexcomOnePlusWarmupMapperTest { + + @Test + fun `WARMING maps to active WARMING with fields passed through`() { + val out = DexcomOnePlusWarmupMapper.toCgmWarmupStatus( + OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + remainingMs = 1_684_000L, + endsAtEpochMs = 42L, + message = "warming", + ), + ) + assertThat(out).isNotNull() + assertThat(out!!.active).isTrue() + assertThat(out.phase).isEqualTo(CgmWarmupStatus.Phase.WARMING) + assertThat(out.remainingMs).isEqualTo(1_684_000L) + assertThat(out.endsAtEpochMs).isEqualTo(42L) + // Nominal total supplied only for WARMING → determinate warm-up ring. + assertThat(out.totalMs).isEqualTo(DexcomOnePlusWarmupCountdown.LOCAL_FALLBACK_DURATION_MS) + } + + @Test + fun `CONNECTING RECONNECTING PAIRING map to active with same phase`() { + val cases = mapOf( + OnePlusWarmupState.Phase.CONNECTING to CgmWarmupStatus.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING to CgmWarmupStatus.Phase.RECONNECTING, + OnePlusWarmupState.Phase.PAIRING to CgmWarmupStatus.Phase.PAIRING, + ) + cases.forEach { (inPhase, outPhase) -> + val out = DexcomOnePlusWarmupMapper.toCgmWarmupStatus(OnePlusWarmupState(phase = inPhase)) + assertThat(out).isNotNull() + assertThat(out!!.active).isTrue() + assertThat(out.phase).isEqualTo(outPhase) + // Pre-warm-up phases have no countdown total → indeterminate ring. + assertThat(out.totalMs).isNull() + } + } + + @Test + fun `a reconnect that still carries the warm-up deadline keeps a determinate ring`() { + val out = DexcomOnePlusWarmupMapper.toCgmWarmupStatus( + OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.RECONNECTING, + endsAtEpochMs = 1_700_000_000_000L, + message = "waiting_for_adv", + ), + ) + assertThat(out).isNotNull() + assertThat(out!!.phase).isEqualTo(CgmWarmupStatus.Phase.RECONNECTING) + assertThat(out.endsAtEpochMs).isEqualTo(1_700_000_000_000L) + // Duty-cycle reconnect during warm-up must not blank the warm-up ring. + assertThat(out.totalMs).isEqualTo(DexcomOnePlusWarmupCountdown.LOCAL_FALLBACK_DURATION_MS) + } + + @Test + fun `terminal and idle phases map to null`() { + listOf( + OnePlusWarmupState.Phase.READY, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.FAILED, + ).forEach { phase -> + assertThat(DexcomOnePlusWarmupMapper.toCgmWarmupStatus(OnePlusWarmupState(phase = phase))) + .isNull() + } + } + + @Test + fun `null countdown fields are preserved on active status`() { + val out = DexcomOnePlusWarmupMapper.toCgmWarmupStatus( + OnePlusWarmupState(phase = OnePlusWarmupState.Phase.WARMING), + ) + assertThat(out).isNotNull() + assertThat(out!!.remainingMs).isNull() + assertThat(out.endsAtEpochMs).isNull() + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/StagingAutoPromotionTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/StagingAutoPromotionTest.kt new file mode 100644 index 000000000000..c4f3ae1fd8c8 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/StagingAutoPromotionTest.kt @@ -0,0 +1,77 @@ +package app.aaps.plugins.source + +import app.aaps.plugins.source.StagingAutoPromotion.Decision +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class StagingAutoPromotionTest { + + private val minute = 60L * 1000L + private val hour = 60L * minute + private val now = 1_000L * hour + private val start = now - 11L * hour + + /** One reading every 5 min over the last 30 min, the newest one 1 min ago. */ + private fun everyFiveMinutes(mgdl: Double = 120.0) = + (0 until 6).map { i -> (now - minute - i * 5L * minute) to mgdl } + + private fun decide( + enabled: Boolean = true, + delayHours: Int = 10, + startMs: Long = start, + readings: List> = everyFiveMinutes(), + minRecent: Int = 4, + ) = StagingAutoPromotion.decide(enabled, delayHours, startMs, readings, minRecent, now) + + @Test + fun `promotes when every check passes`() { + assertThat(decide()).isEqualTo(Decision.PROMOTE) + } + + @Test + fun `does nothing when the setting is off`() { + assertThat(decide(enabled = false)).isEqualTo(Decision.DISABLED) + } + + @Test + fun `does nothing without a start time`() { + assertThat(decide(startMs = 0L)).isEqualTo(Decision.NO_START) + } + + @Test + fun `waits until the set hours have passed`() { + assertThat(decide(delayHours = 12)).isEqualTo(Decision.TOO_EARLY) + assertThat(decide(startMs = now - 10L * hour)).isEqualTo(Decision.PROMOTE) + assertThat(decide(startMs = now - 10L * hour + 1)).isEqualTo(Decision.TOO_EARLY) + } + + @Test + fun `needs enough recent readings`() { + assertThat(decide(readings = everyFiveMinutes().take(3))).isEqualTo(Decision.TOO_FEW_RECENT) + assertThat(decide(readings = emptyList())).isEqualTo(Decision.TOO_FEW_RECENT) + } + + @Test + fun `old readings do not count as recent`() { + val old = (0 until 10).map { i -> (now - 40L * minute - i * minute) to 120.0 } + assertThat(decide(readings = old)).isEqualTo(Decision.TOO_FEW_RECENT) + } + + @Test + fun `refuses when the newest reading is too old`() { + val readings = (0 until 4).map { i -> (now - 16L * minute - i * minute) to 120.0 } + assertThat(decide(readings = readings)).isEqualTo(Decision.STALE) + } + + @Test + fun `refuses when a recent reading is at the sensor limit`() { + assertThat(decide(readings = everyFiveMinutes() + ((now - 2L * minute) to 39.0))).isEqualTo(Decision.RAILED) + assertThat(decide(readings = everyFiveMinutes() + ((now - 2L * minute) to 400.0))).isEqualTo(Decision.RAILED) + } + + @Test + fun `a reading in the future is ignored`() { + val readings = everyFiveMinutes().take(3) + ((now + 5L * minute) to 120.0) + assertThat(decide(readings = readings)).isEqualTo(Decision.TOO_FEW_RECENT) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt new file mode 100644 index 000000000000..8f0ce070c2d9 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt @@ -0,0 +1,134 @@ +package app.aaps.plugins.source.compose + +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanResult +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * The sensor start screen's own decisions. + * + * Which step the user is on, and which sensor is offered first. + */ +class DexcomOnePlusStartRulesTest { + + private fun hit(address: String, name: String? = null, rssi: Int = -70) = + OnePlusScanResult(address = address, name = name, rssi = rssi) + + private fun stored(mac: String?, pin: String = "1234", serial: String? = "ABCD") = + OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = pin, serial = serial), + lastMac = mac, + ) + + // ------------ currentStep(): the guided flow ------------ + + @Test + fun `a missing permission is the first step whatever else is filled in`() { + assertEquals( + DexcomOnePlusStartRules.STEP_PREPARE, + DexcomOnePlusStartRules.currentStep(hasPermissions = false, hasCode = true, hasDevice = true), + ) + } + + @Test + fun `with the permission granted and no code the user is on the code step`() { + assertEquals( + DexcomOnePlusStartRules.STEP_CODE, + DexcomOnePlusStartRules.currentStep(hasPermissions = true, hasCode = false, hasDevice = true), + ) + } + + @Test + fun `a code without a chosen sensor is the connect step`() { + assertEquals( + DexcomOnePlusStartRules.STEP_CONNECT, + DexcomOnePlusStartRules.currentStep(hasPermissions = true, hasCode = true, hasDevice = false), + ) + } + + @Test + fun `everything in place is the warm-up step`() { + assertEquals( + DexcomOnePlusStartRules.STEP_WARMUP, + DexcomOnePlusStartRules.currentStep(hasPermissions = true, hasCode = true, hasDevice = true), + ) + } + + // ------------ signalBars(): what the row draws ------------ + + @Test + fun `a stored sensor with no live sighting draws no bars`() { + assertEquals(0, DexcomOnePlusStartRules.signalBars(0)) + } + + @Test + fun `a strong signal draws four bars and a weak one draws one`() { + assertEquals(4, DexcomOnePlusStartRules.signalBars(-55)) + assertEquals(4, DexcomOnePlusStartRules.signalBars(-60)) + assertEquals(3, DexcomOnePlusStartRules.signalBars(-61)) + assertEquals(3, DexcomOnePlusStartRules.signalBars(-70)) + assertEquals(2, DexcomOnePlusStartRules.signalBars(-71)) + assertEquals(2, DexcomOnePlusStartRules.signalBars(-80)) + assertEquals(1, DexcomOnePlusStartRules.signalBars(-81)) + assertEquals(1, DexcomOnePlusStartRules.signalBars(-110)) + } + + // ------------ rank(): the order the list is drawn in ------------ + + @Test + fun `the stored sensor is offered before a stronger neighbour`() { + val neighbour = hit("AA:AA:AA:AA:AA:AA", name = "DXCM00", rssi = -40) + val mine = hit("BB:BB:BB:BB:BB:BB", name = "DXCM11", rssi = -85) + val ranked = DexcomOnePlusStartRules.rank( + listOf(neighbour, mine), + stored(mac = "BB:BB:BB:BB:BB:BB"), + ) + assertEquals(mine.address, ranked.first().address) + } + + @Test + fun `without a hint the stronger signal comes first`() { + val far = hit("AA:AA:AA:AA:AA:AA", name = "DXCM00", rssi = -85) + val near = hit("BB:BB:BB:BB:BB:BB", name = "DXCM11", rssi = -45) + val ranked = DexcomOnePlusStartRules.rank(listOf(far, near), hint = null) + assertEquals(near.address, ranked.first().address) + } + + @Test + fun `ranking keeps every sensor it was given`() { + val devices = listOf(hit("AA:AA:AA:AA:AA:AA"), hit("BB:BB:BB:BB:BB:BB"), hit("CC:CC:CC:CC:CC:CC")) + val ranked = DexcomOnePlusStartRules.rank(devices, stored(mac = "CC:CC:CC:CC:CC:CC")) + assertEquals(devices.map { it.address }.toSet(), ranked.map { it.address }.toSet()) + } + + // ------------ adoptsAnotherSensor(): when the screen asks before overwriting ------------ + + @Test + fun `an empty slot adopts without a question`() { + assertFalse(DexcomOnePlusStartRules.adoptsAnotherSensor(storedMac = null, address = "AA:BB:CC:DD:EE:FF")) + } + + @Test + fun `the same sensor in different letter case is not another sensor`() { + assertFalse( + DexcomOnePlusStartRules.adoptsAnotherSensor( + storedMac = "aa:bb:cc:dd:ee:ff", + address = "AA:BB:CC:DD:EE:FF", + ), + ) + } + + @Test + fun `a different MAC in the slot is another sensor`() { + assertTrue( + DexcomOnePlusStartRules.adoptsAnotherSensor( + storedMac = "AA:BB:CC:DD:EE:FF", + address = "11:22:33:44:55:66", + ), + ) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt new file mode 100644 index 000000000000..a450d87cdad4 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt @@ -0,0 +1,177 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasScrollToKeyAction +import androidx.compose.ui.test.junit4.v2.createComposeRule +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performScrollToKey +import app.aaps.core.interfaces.resources.TextRefIdRegistry +import app.aaps.core.keys.interfaces.PreferenceItem +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverStub +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub +import app.aaps.plugins.source.DexcomOnePlusHost +import app.aaps.plugins.source.DexcomOnePlusPlugin +import app.aaps.plugins.source.SourceStringIds +import app.aaps.plugins.source.SourceStringsValues +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.GraphicsMode +import org.robolectric.annotation.Config as RobolectricConfig + +/** + * The sensor start screen, rendered. + * + * Two things this proves that no unit test can. The strings really resolve - every one of them is + * a `TextRef.Named`, so a name that no longer matched would draw as the raw name here. And the + * pre-soak slot is **absent** when no second slot is offered, rather than present and broken. + */ +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@RobolectricConfig(sdk = [35]) +class DexcomOnePlusStartScreenTest { + + @get:Rule val compose = createComposeRule() + + /** The English text of a string, which is what the screen must draw. */ + private fun text(name: String): String = + requireNotNull(SourceStringsValues.textOf(name, null)) { "no English text for $name" } + + private fun render(twoSlots: Boolean) { + // MainApp does this in production. Without it every TextRef.Named draws as its raw name and + // the assertions below read "the node is not displayed" without saying why. + TextRefIdRegistry.register("source") { name -> SourceStringIds.idOf(name) } + compose.setContent { + DexcomOnePlusStartScreen( + host = FakeHost, + permissions = GrantedPermissions, + onBack = {}, + onEnsureDriver = { OnePlusCgmDriverStub.instance }, + onActivatePlugin = {}, + onStarted = {}, + onBeginStaging = { true }, + onIsStagingSensor = { false }, + onCancelStaging = {}, + onOpenPromote = {}, + onStagingDriver = if (twoSlots) ({ error("not reached in this test") }) else null, + onSensorSessionStarted = { _, _ -> }, + ) + } + } + + @Test + fun `a phone with two slots offers the pre-soak choice`() { + render(twoSlots = true) + compose.onNodeWithText(text("dexcom_oneplus_slot_staging_short")).assertIsDisplayed() + compose.onNodeWithText(text("dexcom_oneplus_slot_production_short")).assertIsDisplayed() + } + + @Test + fun `a phone with one slot does not show the pre-soak choice at all`() { + render(twoSlots = false) + compose.onNodeWithText(text("dexcom_oneplus_slot_staging_short")).assertDoesNotExist() + compose.onNodeWithText(text("dexcom_oneplus_slot_production_short")).assertDoesNotExist() + } + + @Test + fun `the converted strings are drawn as their text and not as their names`() { + render(twoSlots = true) + compose.onNodeWithText(text("dexcom_oneplus_start_title")).assertIsDisplayed() + compose.onNodeWithText(text("dexcom_oneplus_section_pairing_code")).assertIsDisplayed() + compose.onNodeWithText(text("dexcom_oneplus_applicator_gs1_label")).assertIsDisplayed() + // The bottom bar is pinned, so this one is on screen whatever the list is doing. + compose.onNodeWithText(text("dexcom_oneplus_connect_follow")).assertIsDisplayed() + } + + @Test + fun `the scan part of the screen reads correctly once it is scrolled to`() { + render(twoSlots = true) + // The screen is one long list and the test window is a phone sized one, so the scan rows + // are not composed until the list is asked for them. + compose.onNode(hasScrollToKeyAction()).performScrollToKey("scanEmpty") + compose.onNodeWithText(text("dexcom_oneplus_section_sensors_nearby")).assertExists() + compose.onNodeWithText(text("dexcom_oneplus_scan_pick_hint")).assertExists() + compose.onNodeWithText(text("dexcom_oneplus_scan_empty")).assertExists() + // dexcom_oneplus_scan_idle is one of the six lines that take an argument. Nothing has been + // heard yet so it must read zero - and a wrong argument count would leave a placeholder. + val idle = SourceStringsValues.textOf("dexcom_oneplus_scan_idle", null)!!.replace("%1\$d", "0") + compose.onNodeWithText(idle, useUnmergedTree = true).assertExists() + } + + /** A phone where the Bluetooth permission is already granted. */ + private object GrantedPermissions : OnePlusBlePermissionGate { + override fun granted(): Boolean = true + override fun request() = Unit + } + + /** Everything the screen asks of the phone, answered without Bluetooth or a file. */ + private object FakeHost : DexcomOnePlusHost { + + override fun attachPlatform(driver: OnePlusCgmDriver) = Unit + override fun slotStore(namespace: String?): OnePlusSensorStore = OnePlusSensorStore(MemoryPrefs()) + override val stagingNamespace: String = "staging" + override fun productionDriver(): OnePlusCgmDriver = OnePlusCgmDriverStub.instance + override fun stagingDriver(): OnePlusCgmDriver = OnePlusCgmDriverStub.instance + override fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = + OnePlusCgmDriverStub.instance + + override fun promoteStagingInstance(): OnePlusCgmDriverReal? = null + override fun setSessionServiceWanted(wanted: Boolean) = Unit + override fun showWarmup(state: OnePlusWarmupState) = Unit + override fun cancelWarmupNotification() = Unit + override fun alert(message: String) = Unit + override fun screenScanner(): OnePlusBleScanner = OnePlusBleScannerStub() + override fun screenItems(plugin: DexcomOnePlusPlugin): List = emptyList() + } + + /** An empty slot store in memory, so the screen starts with no sensor remembered. */ + private class MemoryPrefs : OnePlusSensorPrefs { + + private val values = mutableMapOf() + + override fun getString(key: String): String? = values[key] as? String + override fun getLong(key: String, defaultValue: Long): Long = values[key] as? Long ?: defaultValue + override fun getInt(key: String, defaultValue: Int): Int = values[key] as? Int ?: defaultValue + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = + values[key] as? Boolean ?: defaultValue + + override fun contains(key: String): Boolean = values.containsKey(key) + + override fun edit(block: OnePlusSensorPrefs.Editor.() -> Unit) { + object : OnePlusSensorPrefs.Editor { + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + + override fun putLong(key: String, value: Long) { + values[key] = value + } + + override fun putInt(key: String, value: Int) { + values[key] = value + } + + override fun putBoolean(key: String, value: Boolean) { + values[key] = value + } + + override fun remove(key: String) { + values.remove(key) + } + + override fun clear() { + values.clear() + } + }.block() + } + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt new file mode 100644 index 000000000000..4546528d0be6 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt @@ -0,0 +1,148 @@ +package app.aaps.plugins.source.compose + +import app.aaps.core.interfaces.resources.formatTemplate +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.source.SourceStrings +import app.aaps.plugins.source.SourceStringsValues +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Every line of the sensor start screen that takes arguments. + * + * A wrong **id** cannot happen - `SourceStrings` is generated from `strings.xml`, so it would not + * compile. A wrong argument **count or order** compiles perfectly and is only seen by the person + * reading the screen, because the resolvers catch the format error and answer with a fallback. So + * each template is filled here with the same number of arguments the screen passes - of the same + * types - and the result has to carry every one of them with no placeholder left over. + * + * `allArgumentsLand` is the assertion, and the last test in this file is the test of it: a call + * with one argument too few must fail it. + */ +class DexcomOnePlusStartStringsTest { + + private fun template(ref: TextRef): String { + val named = ref as TextRef.Named + return assertNotNull( + SourceStringsValues.textOf(named.name, null), + "no English text for ${named.name}", + ) + } + + /** Fills [ref] with [args] and checks every one of them is in the result and nothing is left. */ + private fun allArgumentsLand(ref: TextRef, vararg args: Any): String { + val name = (ref as TextRef.Named).name + val text = formatTemplate(template(ref), args.toList()) + assertTrue(!text.contains('%'), "$name left a placeholder unfilled: $text") + var at = -1 + for (arg in args) { + val found = text.indexOf(arg.toString(), startIndex = at + 1) + assertTrue(found > at, "$name does not carry $arg in the expected order: $text") + at = found + } + return text + } + + @Test + fun `the parsed applicator line carries the code and then the serial`() { + val text = allArgumentsLand(SourceStrings.dexcom_oneplus_applicator_parsed, "1234", "ABCDEF") + assertTrue(text.indexOf("1234") < text.indexOf("ABCDEF"), text) + } + + @Test + fun `the last MAC hint carries the address`() { + allArgumentsLand(SourceStrings.dexcom_oneplus_last_mac_hint, "AA:BB:CC:DD:EE:FF") + } + + @Test + fun `the connect target line carries the sensor name`() { + allArgumentsLand(SourceStrings.dexcom_oneplus_connect_target, "DX02ABCD") + } + + @Test + fun `the idle scan chip carries the number of sensors found`() { + allArgumentsLand(SourceStrings.dexcom_oneplus_scan_idle, 2) + } + + @Test + fun `the signal reading carries a negative dBm value`() { + allArgumentsLand(SourceStrings.dexcom_oneplus_scan_signal, -67) + } + + @Test + fun `the step counter carries the current step and then the total`() { + val text = allArgumentsLand(SourceStrings.cgm_step_counter, 2, 4) + assertTrue(text.indexOf("2") < text.indexOf("4"), text) + } + + @Test + fun `every other line of this screen takes no arguments at all`() { + // The ones left out are the six above. If a plain line ever gains a placeholder this fails + // here rather than on a phone. + val plain = listOf( + SourceStrings.cgm_help_collapse, + SourceStrings.cgm_help_expand, + SourceStrings.cgm_nav_close, + SourceStrings.dexcom_oneplus_applicator_gs1_hint, + SourceStrings.dexcom_oneplus_applicator_gs1_label, + SourceStrings.dexcom_oneplus_applicator_serial_none, + SourceStrings.dexcom_oneplus_connect_follow, + SourceStrings.dexcom_oneplus_device_required, + SourceStrings.dexcom_oneplus_dexcom_recovery_warning, + SourceStrings.dexcom_oneplus_help_before_pairing, + SourceStrings.dexcom_oneplus_help_how_to_start, + SourceStrings.dexcom_oneplus_help_permissions, + SourceStrings.dexcom_oneplus_help_slot, + SourceStrings.dexcom_oneplus_nav_back, + SourceStrings.dexcom_oneplus_new_sensor_code_warning, + SourceStrings.dexcom_oneplus_pairing_code_invalid, + SourceStrings.dexcom_oneplus_pairing_code_required, + SourceStrings.dexcom_oneplus_permissions_hint, + SourceStrings.dexcom_oneplus_permissions_needed, + SourceStrings.dexcom_oneplus_request_permissions, + SourceStrings.dexcom_oneplus_scan_empty, + SourceStrings.dexcom_oneplus_scan_hint, + SourceStrings.dexcom_oneplus_scan_last_used, + SourceStrings.dexcom_oneplus_scan_pick_hint, + SourceStrings.dexcom_oneplus_scan_rescan, + SourceStrings.dexcom_oneplus_scan_scanning, + SourceStrings.dexcom_oneplus_scan_start, + SourceStrings.dexcom_oneplus_scan_stop, + SourceStrings.dexcom_oneplus_scan_unnamed, + SourceStrings.dexcom_oneplus_section_pairing_code, + SourceStrings.dexcom_oneplus_section_sensors_nearby, + SourceStrings.dexcom_oneplus_slot_conflict_dismiss, + SourceStrings.dexcom_oneplus_slot_conflict_message, + SourceStrings.dexcom_oneplus_slot_conflict_promote, + SourceStrings.dexcom_oneplus_slot_conflict_restart, + SourceStrings.dexcom_oneplus_slot_conflict_title, + SourceStrings.dexcom_oneplus_slot_hint, + SourceStrings.dexcom_oneplus_slot_production_short, + SourceStrings.dexcom_oneplus_slot_staging_short, + SourceStrings.dexcom_oneplus_staging_connect, + SourceStrings.dexcom_oneplus_staging_is_production, + SourceStrings.dexcom_oneplus_staging_return_note, + SourceStrings.dexcom_oneplus_start_return_warmup, + SourceStrings.dexcom_oneplus_start_steps, + SourceStrings.dexcom_oneplus_start_title, + SourceStrings.dexcom_oneplus_step_code, + SourceStrings.dexcom_oneplus_step_connect, + SourceStrings.dexcom_oneplus_step_prepare, + SourceStrings.dexcom_oneplus_step_warmup, + ) + assertEquals(49, plain.size, "the screen names 55 strings - 6 of them take arguments") + for (ref in plain) { + val name = (ref as TextRef.Named).name + assertTrue(!template(ref).contains('%'), "$name has a placeholder but is used without arguments") + } + } + + @Test + fun `a template filled with one argument too few keeps its placeholder`() { + // The test of the test. Without this a passing suite would prove nothing about the check. + val text = formatTemplate(template(SourceStrings.dexcom_oneplus_applicator_parsed), listOf("1234")) + assertTrue(text.contains('%'), "the unfilled check has no teeth: $text") + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdownTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdownTest.kt new file mode 100644 index 000000000000..3b6fd00e0c05 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdownTest.kt @@ -0,0 +1,138 @@ +package app.aaps.plugins.source.compose + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class DexcomOnePlusWarmupCountdownTest { + + // Built from the driver state and mapped, so the test still covers the real driver phases. + private fun warming(remainingMs: Long? = null, endsAtEpochMs: Long? = null) = + OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + remainingMs = remainingMs, + endsAtEpochMs = endsAtEpochMs, + ).toCgmWarmupInfo() + + // ---- formatMmSs ---- + + @Test + fun `formatMmSs formats minutes and zero-padded seconds`() { + assertThat(DexcomOnePlusWarmupCountdown.formatMmSs(28L * 60_000L + 14_000L)).isEqualTo("28:14") + assertThat(DexcomOnePlusWarmupCountdown.formatMmSs(5_000L)).isEqualTo("0:05") + assertThat(DexcomOnePlusWarmupCountdown.formatMmSs(60_000L)).isEqualTo("1:00") + } + + @Test + fun `formatMmSs clamps negative to zero`() { + assertThat(DexcomOnePlusWarmupCountdown.formatMmSs(-5_000L)).isEqualTo("0:00") + } + + // ---- resolveRemainingMs (priority: remainingMs > endsAt > localFallback) ---- + + @Test + fun `resolveRemainingMs prefers protocol remainingMs over everything`() { + val out = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = warming(remainingMs = 90_000L, endsAtEpochMs = 1_000L), + nowEpochMs = 10_000L, + localFallbackEndsAtEpochMs = 999_999L, + ) + assertThat(out).isEqualTo(90_000L) + } + + @Test + fun `resolveRemainingMs falls back to endsAt minus now when remaining is null`() { + val out = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = warming(endsAtEpochMs = 100_000L), + nowEpochMs = 40_000L, + localFallbackEndsAtEpochMs = null, + ) + assertThat(out).isEqualTo(60_000L) + } + + @Test + fun `resolveRemainingMs uses local fallback only when protocol values are null`() { + val out = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = warming(), + nowEpochMs = 40_000L, + localFallbackEndsAtEpochMs = 100_000L, + ) + assertThat(out).isEqualTo(60_000L) + } + + @Test + fun `resolveRemainingMs returns null when nothing is available`() { + val out = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = warming(), + nowEpochMs = 40_000L, + localFallbackEndsAtEpochMs = null, + ) + assertThat(out).isNull() + } + + @Test + fun `resolveRemainingMs coerces an elapsed endsAt to zero`() { + val out = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = warming(endsAtEpochMs = 10_000L), + nowEpochMs = 40_000L, + localFallbackEndsAtEpochMs = null, + ) + assertThat(out).isEqualTo(0L) + } + + // ---- shouldStartLocalFallback ---- + + @Test + fun `shouldStartLocalFallback only when WARMING and both protocol values null`() { + assertThat(DexcomOnePlusWarmupCountdown.shouldStartLocalFallback(warming())).isTrue() + assertThat(DexcomOnePlusWarmupCountdown.shouldStartLocalFallback(warming(remainingMs = 1L))).isFalse() + assertThat(DexcomOnePlusWarmupCountdown.shouldStartLocalFallback(warming(endsAtEpochMs = 1L))).isFalse() + assertThat( + DexcomOnePlusWarmupCountdown.shouldStartLocalFallback( + OnePlusWarmupState(phase = OnePlusWarmupState.Phase.CONNECTING).toCgmWarmupInfo(), + ), + ).isFalse() + } + + // ---- shouldClearLocalFallback / showsCountdown ---- + + @Test + fun `the local fallback survives a duty-cycle reconnect and is cleared only when warm-up ends`() { + // Dropping the deadline on every CONNECTING / RECONNECTING blanked the countdown and then + // restarted a fresh ~30 min timer on the next WARMING packet. + listOf( + OnePlusWarmupState.Phase.WARMING, + OnePlusWarmupState.Phase.PAIRING, + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING, + ).forEach { phase -> + assertThat(DexcomOnePlusWarmupCountdown.shouldClearLocalFallback(phase.toCgmWarmupPhase())).isFalse() + } + listOf( + OnePlusWarmupState.Phase.READY, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.FAILED, + ).forEach { phase -> + assertThat(DexcomOnePlusWarmupCountdown.shouldClearLocalFallback(phase.toCgmWarmupPhase())).isTrue() + } + } + + @Test + fun `the countdown is shown while re-establishing the link but not once warm-up is over`() { + listOf( + OnePlusWarmupState.Phase.WARMING, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.PAIRING, + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING, + ).forEach { phase -> + assertThat(DexcomOnePlusWarmupCountdown.showsCountdown(phase.toCgmWarmupPhase())).isTrue() + } + assertThat( + DexcomOnePlusWarmupCountdown.showsCountdown(OnePlusWarmupState.Phase.READY.toCgmWarmupPhase()), + ).isFalse() + assertThat( + DexcomOnePlusWarmupCountdown.showsCountdown(OnePlusWarmupState.Phase.FAILED.toCgmWarmupPhase()), + ).isFalse() + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMappingTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMappingTest.kt new file mode 100644 index 000000000000..e1e9ac6b86c1 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMappingTest.kt @@ -0,0 +1,30 @@ +package app.aaps.plugins.source.compose + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The ONE+ warm-up mapping: every driver phase lands on the same vendor-neutral phase, so the + * screens and the notification read the driver the same way. + */ +class OnePlusWarmupMappingTest { + + @Test + fun everyDriverPhaseMapsToTheSharedPhaseOfTheSameName() { + OnePlusWarmupState.Phase.entries.forEach { phase -> + assertEquals(phase.name, phase.toCgmWarmupPhase().name) + } + } + + @Test + fun theCountdownFactsAreCarriedOverUnchanged() { + val info = OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.WARMING, + remainingMs = 120_000L, + endsAtEpochMs = 5_000_000L, + ).toCgmWarmupInfo() + + assertEquals(CgmWarmupInfo(CgmWarmupPhase.WARMING, 120_000L, 5_000_000L), info) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/SensorAgeFormatTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/SensorAgeFormatTest.kt new file mode 100644 index 000000000000..0008e185a0ed --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/SensorAgeFormatTest.kt @@ -0,0 +1,72 @@ +package app.aaps.plugins.source.compose + +import app.aaps.core.interfaces.InterfacesStringsValues +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.resources.formatTemplate +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.keys.interfaces.TextRef.Companion.withArgs +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * The sensor age keeps the two largest units, and is built only from translated templates. + * + * The resolver reads the real English table of `:core:interfaces`, so a wrong template or a wrong + * argument order shows up here as wrong words. + */ +class SensorAgeFormatTest { + + private object EnglishText : TextResolver { + + override fun gs(ref: TextRef): String = when (ref) { + is TextRef.Literal -> ref.text + is TextRef.Named -> { + val template = InterfacesStringsValues.textOf(ref.name, null) ?: ref.name + if (ref.args.isEmpty()) template else formatTemplate(template, ref.args) + } + + is TextRef.AndroidRes -> "res:${ref.id}" + } + + override fun gs(ref: TextRef, vararg args: Any?): String = gs(ref.withArgs(*args)) + override fun gsNotLocalised(ref: TextRef): String = gs(ref) + } + + @Test + fun daysAndHours() { + val age = (2.days + 5.hours + 40.minutes).inWholeMilliseconds + assertEquals("2 days, 5 hours", formatSensorAge(age, EnglishText)) + } + + @Test + fun hoursAndMinutes() { + val age = (3.hours + 10.minutes + 59.seconds).inWholeMilliseconds + assertEquals("3 hours, 10 minutes", formatSensorAge(age, EnglishText)) + } + + @Test + fun onlyMinutes() { + assertEquals("7 minutes", formatSensorAge(7.minutes.inWholeMilliseconds, EnglishText)) + } + + @Test + fun oneOfEachUsesTheSingular() { + val age = (1.days + 1.hours).inWholeMilliseconds + assertEquals("1 day, 1 hour", formatSensorAge(age, EnglishText)) + assertEquals("1 minute", formatSensorAge(1.minutes.inWholeMilliseconds, EnglishText)) + } + + @Test + fun fullDaysShowZeroHours() { + assertEquals("10 days, 0 hours", formatSensorAge(10.days.inWholeMilliseconds, EnglishText)) + } + + @Test + fun negativeAgeIsZeroMinutes() { + assertEquals("0 minutes", formatSensorAge(-5_000L, EnglishText)) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/keys/StagingAutoPromoteKeysTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/keys/StagingAutoPromoteKeysTest.kt new file mode 100644 index 000000000000..1f8b4a5db6dd --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/keys/StagingAutoPromoteKeysTest.kt @@ -0,0 +1,26 @@ +package app.aaps.plugins.source.keys + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * The automatic switch from a pre-soak sensor stops the sensor in use, so it must stay off until + * the user turns it on. + */ +class StagingAutoPromoteKeysTest { + + @Test + fun `the automatic switch is off by default`() { + assertThat(DexcomOnePlusBooleanKey.AutoPromote.defaultValue).isFalse() + } + + @Test + fun `the default delay is 12 hours`() { + assertThat(DexcomOnePlusIntKey.AutoPromoteHours.defaultValue).isEqualTo(12) + } + + @Test + fun `the delay is hidden until the switch is on`() { + assertThat(DexcomOnePlusIntKey.AutoPromoteHours.dependency).isEqualTo(DexcomOnePlusBooleanKey.AutoPromote) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt new file mode 100644 index 000000000000..853cb19115f7 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt @@ -0,0 +1,83 @@ +package app.aaps.plugins.source.logs + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File + +/** What the log screen is allowed to show, and what it must not lose on the way. */ +class DriverLogReaderTest { + + @Test + fun `keeps only the lines of the driver`() { + val lines = listOf( + "10:00:00.001 [main] I/BGSOURCE: something from another source", + "10:00:00.002 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_SESSION: link is up", + "10:00:00.003 [main] D/LoopPlugin: something else entirely", + ) + + assertThat(DriverLogReader.keep(lines, DriverLogReader.DRIVER_LOGGERS, 100)) + .containsExactly("10:00:00.002 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_SESSION: link is up") + } + + @Test + fun `a stack trace stays with the line it belongs to`() { + val lines = listOf( + "10:00:00.001 [main] E/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_ERROR: the handshake stopped", + "java.io.IOException: link closed", + "\tat app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession.open(OnePlusBleSession.kt:120)", + "10:00:00.002 [main] E/OtherPlugin: not ours", + "java.lang.IllegalStateException: not ours either", + ) + + val kept = DriverLogReader.keep(lines, DriverLogReader.DRIVER_LOGGERS, 100) + + assertThat(kept).hasSize(3) + assertThat(kept[1]).isEqualTo("java.io.IOException: link closed") + assertThat(kept).doesNotContain("java.lang.IllegalStateException: not ours either") + } + + @Test + fun `when there are too many lines the newest are the ones kept`() { + val lines = (1..10).map { "10:00:00.00$it [main] I/DEXCOM_ONEPLUS: line $it" } + + val kept = DriverLogReader.keep(lines, DriverLogReader.DRIVER_LOGGERS, 3) + + assertThat(kept).hasSize(3) + assertThat(kept.last()).endsWith("line 10") + assertThat(kept.first()).endsWith("line 8") + } + + @Test + fun `a whole small file is read, and a big one only from its end`(@TempDir folder: File) { + val file = File(folder, DriverLogReader.CURRENT_FILE) + file.writeText("first line\nsecond line\nthird line\n") + + assertThat(DriverLogReader.tail(file, 1024L)).containsAtLeast("first line", "third line") + + // Reading from an offset lands in the middle of a line, so that half line is dropped. + val fromTheEnd = DriverLogReader.tail(file, 15L) + assertThat(fromTheEnd).doesNotContain("first line") + assertThat(fromTheEnd).contains("third line") + } + + @Test + fun `a build that has not written anything yet answers with nothing`(@TempDir folder: File) { + assertThat(DriverLogReader.read(folder.absolutePath)).isEmpty() + } + + @Test + fun `reads the driver lines back out of a real file`(@TempDir folder: File) { + File(folder, DriverLogReader.CURRENT_FILE).writeText( + "10:00:00.001 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_SCAN: sensor heard\n" + + "10:00:00.002 [main] I/SomethingElse: ignore me\n" + + "10:00:00.003 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_BG: value taken\n" + ) + + val all = DriverLogReader.read(folder.absolutePath) + + assertThat(all).hasSize(2) + assertThat(all.first()).contains("DEXCOM_ONEPLUS_SCAN") + assertThat(all.last()).contains("DEXCOM_ONEPLUS_BG") + } +} diff --git a/plugins/source/src/androidMain/AndroidManifest.xml b/plugins/source/src/androidMain/AndroidManifest.xml index 607a2dbf65df..fd232df66307 100644 --- a/plugins/source/src/androidMain/AndroidManifest.xml +++ b/plugins/source/src/androidMain/AndroidManifest.xml @@ -2,6 +2,7 @@ + @@ -18,6 +19,27 @@ + + + + + + + + \ No newline at end of file diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt new file mode 100644 index 000000000000..4b7a3347ae48 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt @@ -0,0 +1,91 @@ +package app.aaps.plugins.source + +import android.content.Context +import android.content.Intent +import app.aaps.core.keys.interfaces.PreferenceItem +import app.aaps.core.keys.interfaces.withClick +import app.aaps.plugins.dexcomoneplus.OnePlusAndroidPlatform +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerAndroid +import app.aaps.plugins.source.activities.DexcomOnePlusStartActivity +import app.aaps.plugins.source.activities.DexcomOnePlusStatusActivity +import app.aaps.plugins.source.activities.DexcomOnePlusWarmupActivity +import app.aaps.plugins.source.keys.DexcomOnePlusIntentKey +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn +import dev.zacsweers.metro.binding + +/** + * [DexcomOnePlusHost] on Android: the driver registry, the three setup screens, the + * `connectedDevice` foreground service and the status-bar warm-up notification. + */ +@ContributesBinding(AppScope::class, binding = binding()) +@SingleIn(AppScope::class) +@Inject +class DexcomOnePlusAndroidHost( + private val context: Context, +) : DexcomOnePlusHost { + + /** + * Resolved on first use, not in the constructor. + * + * Nothing here needs it until the plugin actually runs, and building the host must not depend + * on a `Context` that can answer `getApplicationContext`. The visibility tests build the host + * around a bare mock to read `showInList`, and they never reach a screen or a store. + */ + private val appContext: Context by lazy { context.applicationContext } + + private val platform by lazy { OnePlusAndroidPlatform(appContext) } + + override fun attachPlatform(driver: OnePlusCgmDriver) = driver.attach(platform) + + override fun slotStore(namespace: String?): OnePlusSensorStore = + OnePlusSensorStore(appContext, namespace) + + override val stagingNamespace: String = OnePlusCgmDrivers.STAGING_NAMESPACE + + private val warmupNotification by lazy { DexcomOnePlusWarmupNotification(appContext) } + + override fun productionDriver(): OnePlusCgmDriver = OnePlusCgmDrivers.default() + + override fun stagingDriver(): OnePlusCgmDriver = OnePlusCgmDrivers.staging() + + override fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = + OnePlusCgmDrivers.production(watcher) + + override fun promoteStagingInstance(): OnePlusCgmDriver? = OnePlusCgmDrivers.promoteStagingInstance() + + override fun setSessionServiceWanted(wanted: Boolean) { + if (wanted) DexcomOnePlusSessionService.start(appContext) + else DexcomOnePlusSessionService.stop(appContext) + } + + override fun showWarmup(state: OnePlusWarmupState) = warmupNotification.update(state) + + override fun cancelWarmupNotification() = warmupNotification.cancel() + + override fun alert(message: String) = warmupNotification.alert(message) + + /** The start screen's own scanner instance, with no hint until the screen sets one. */ + override fun screenScanner(): OnePlusBleScanner = + OnePlusBleScannerAndroid(appContext, sessionHint = null) + + override fun screenItems(plugin: DexcomOnePlusPlugin): List = listOf( + DexcomOnePlusIntentKey.Status.withClick { open(DexcomOnePlusStatusActivity::class.java) }, + DexcomOnePlusIntentKey.Start.withClick { open(DexcomOnePlusStartActivity::class.java) }, + DexcomOnePlusIntentKey.Warmup.withClick { open(DexcomOnePlusWarmupActivity::class.java) }, + ) + + private fun open(screen: Class<*>) { + context.startActivity( + Intent(context, screen).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt new file mode 100644 index 000000000000..39472e486ef4 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt @@ -0,0 +1,91 @@ +package app.aaps.plugins.source + +import app.aaps.core.keys.interfaces.PreferenceItem +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner + +/** + * Everything [DexcomOnePlusPlugin] needs from the phone it runs on. + * + * The plugin keeps the sensor slots, the pre-soak rules, the promotion gates and the ingest path. + * What needs an Android `Context` is asked here: the driver registry, how the three setup screens + * are opened, the foreground service and the status-bar notification. Each of those is named one + * by one, the same way `OnePlusPlatform` names what the driver needs, so the plugin never has to + * know what a `Context` is and the tests can replace the host with a fake. + * + * ⚠️ Nothing here may answer with something that pretends to work. A CGM plugin that is switched on + * and quietly never produces a reading is read by the dosing engine as "no glucose", which is not + * the same thing as a reading. + */ +interface DexcomOnePlusHost { + + /** + * Give [driver] what it needs from this phone, before anything else is asked of it. + * + * This is `OnePlusCgmDriver.attach` with the platform filled in by the host: a key-value file, + * an LE scanner, a GATT stack and a wake lock. + */ + fun attachPlatform(driver: OnePlusCgmDriver) + + /** + * The private key-value store of one sensor slot: its identity, its pairing code, its key and + * the marks that let a restart pick the sensor up again. + * + * @param namespace null for the slot that feeds the loop, [stagingNamespace] for the pre-soak. + */ + fun slotStore(namespace: String?): OnePlusSensorStore + + /** Key-value file namespace of the pre-soak slot, so both slots keep their own identity. */ + val stagingNamespace: String + + /** The driver feeding the loop. */ + fun productionDriver(): OnePlusCgmDriver + + /** The second, independent driver for a pre-soak sensor. */ + fun stagingDriver(): OnePlusCgmDriver + + /** The driver feeding the loop, with [watcher] attached. */ + fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver + + /** + * Hand the pre-soak driver the production role, keeping its live link. + * + * @return the driver that has just been retired, for the caller to shut down, or null when + * there was no pre-soak driver to promote. + */ + fun promoteStagingInstance(): OnePlusCgmDriver? + + /** + * Ask for, or give back, the privilege that keeps a Bluetooth session alive in the background: + * the `connectedDevice` foreground service. + */ + fun setSessionServiceWanted(wanted: Boolean) + + /** Show the live warm-up / reconnect state where the user can see it. */ + fun showWarmup(state: OnePlusWarmupState) + + /** Take the warm-up display down. */ + fun cancelWarmupNotification() + + /** Tell the user about a problem that happened while they were not looking. */ + fun alert(message: String) + + /** + * A scanner for the setup screens to drive themselves, separate from the driver's own. + * + * The start screen lists what is in range so the user can pick their sensor, which is a + * different job from the driver's pre-connect wait for one known MAC. + */ + fun screenScanner(): OnePlusBleScanner + + /** + * The entries that open this plugin's own screens, for the settings screen. + * + * @param plugin the plugin these screens act on. It is passed in rather than injected because + * the plugin builds the host, so a host that asked for the plugin would be a loop. + */ + fun screenItems(plugin: DexcomOnePlusPlugin): List +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusIngest.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusIngest.kt new file mode 100644 index 000000000000..160bd12e2cee --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusIngest.kt @@ -0,0 +1,153 @@ +package app.aaps.plugins.source + +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import kotlin.concurrent.Volatile +import kotlin.math.abs + +/** + * Pure mapping / gate helpers for Dexcom ONE+ → [GV] ingest. + * Kept beside [DexcomOnePlusPlugin] so UI edits stay out of the insert path. + * + * Dedup mirrors Ob1 `getForPreciseTimestamp(..., 4 min)` so backfill + live EGV + * (and EGV re-poll) do not double-insert near-duplicate points. + * + * Provenance: NightscoutFoundation/xDrip `Ob1G5CollectionService.getForPreciseTimestamp` + * at pin `1e86d9a2a52577ed2c30fbf7b69d75fd56e6918f` (GPL-3.0). See plugins/dexcom_oneplus/NOTICE. + */ +internal object DexcomOnePlusIngest { + + /** Ob1 precise-timestamp window. */ + const val DEDUP_WINDOW_MS: Long = 4L * 60L * 1000L + + private const val RECENT_CAP: Int = 64 + + /** + * One lock for the whole dedup state. + * + * Was `synchronized(Any())`, which is JVM only. [AapsLock.withLock] is inline and reentrant, so + * the `return` statements inside the guarded blocks below still mean what they meant before. + */ + private val lock = AapsLock() + private val recentTimestampsMs = ArrayDeque() + private val recentSequences = LinkedHashSet() + + /** + * Persistent monotonic high-water mark of the last accepted EGV sequence, survived across + * process restarts via [seed] (rehydrated from `OnePlusSensorStore`). -1 = nothing recorded yet. + * Prevents an app update / restart from re-ingesting already-stored readings (which the loop + * rejects as duplicates), because the in-memory [recentSequences] alone is wiped on restart. + */ + @Volatile + private var lastAcceptedSequence: Long = -1L + + /** + * Rehydrate the dedup state after a process restart, so backfilled/re-read EGVs are not + * re-inserted. [lastSequence] is the persisted high-water mark (-1 if none); [recentTimestampsMs] + * are recent already-stored reading timestamps (from the DB) to re-seed the near-duplicate window. + */ + fun seed(lastSequence: Long, recentTimestampsMs: List) { + lock.withLock { + lastAcceptedSequence = lastSequence + this.recentTimestampsMs.clear() + recentTimestampsMs.takeLast(RECENT_CAP).forEach { this.recentTimestampsMs.addLast(it) } + } + } + + /** + * Block PersistenceLayer inserts only while the protocol/UI reports `WARMING`. + * PAIRING / IDLE must not block — otherwise attach-to-ready sensors never ingest. + */ + fun isWarmupBlockingIngest(phase: OnePlusWarmupState.Phase): Boolean = + phase == OnePlusWarmupState.Phase.WARMING + + /** + * @return true if this sample should be inserted (not a near-duplicate of a recent one). + */ + fun shouldAccept(sample: OnePlusGlucoseSample): Boolean { + lock.withLock { + val seq = sample.sequence + // Persistent floor: reject anything at or below the last accepted sequence — survives + // restarts, so backfill/re-reads after an app update are not re-inserted. + if (seq != null && lastAcceptedSequence >= 0 && seq <= lastAcceptedSequence) { + return false + } + if (seq != null && recentSequences.contains(seq)) { + return false + } + val ts = sample.timestampMs + for (prev in recentTimestampsMs) { + if (abs(prev - ts) < DEDUP_WINDOW_MS) { + return false + } + } + recentTimestampsMs.addLast(ts) + if (seq != null) { + recentSequences.add(seq) + lastAcceptedSequence = maxOf(lastAcceptedSequence, seq) + } + while (recentTimestampsMs.size > RECENT_CAP) { + recentTimestampsMs.removeFirst() + } + while (recentSequences.size > RECENT_CAP) { + val first = recentSequences.first() + recentSequences.remove(first) + } + return true + } + } + + fun mapToGv(sample: OnePlusGlucoseSample): GV = + GV( + timestamp = sample.timestampMs, + value = sample.mgdl, + raw = null, + noise = null, + trendArrow = trendArrowFor(sample.trendSlopeMgdlPerMin), + sourceSensor = SourceSensor.DEXCOM_ONEPLUS_NATIVE, + ) + + /** + * Turns the sensor's rate of change into the arrow AAPS stores and draws. + * + * The sensor reports a slope in mg/dL per minute, not an arrow name. This used to be handed + * straight to `TrendArrow.fromString`, which compares against labels like "Flat" and + * "FortyFiveUp": a number never matched one, so every ONE+ reading was stored as + * [TrendArrow.NONE] and the glucose history drew the invalid-arrow icon on all of them. + * + * Thresholds are the usual Dexcom ones: one arrow step per mg/dL/min, doubling above three. + * A null slope (the sensor's own invalid marker) stays [TrendArrow.NONE] — honest, since no + * direction was measured. + */ + fun trendArrowFor(slopeMgdlPerMin: Double?): TrendArrow = when { + slopeMgdlPerMin == null -> TrendArrow.NONE + slopeMgdlPerMin >= 3.0 -> TrendArrow.DOUBLE_UP + slopeMgdlPerMin >= 2.0 -> TrendArrow.SINGLE_UP + slopeMgdlPerMin >= 1.0 -> TrendArrow.FORTY_FIVE_UP + slopeMgdlPerMin > -1.0 -> TrendArrow.FLAT + slopeMgdlPerMin > -2.0 -> TrendArrow.FORTY_FIVE_DOWN + slopeMgdlPerMin > -3.0 -> TrendArrow.SINGLE_DOWN + else -> TrendArrow.DOUBLE_DOWN + } + + /** + * Reset all dedup state (in-memory windows + persistent sequence floor). Call when the loop's + * sensor changes — e.g. promoting a staging sensor to production — because the new sensor's EGV + * sequence counter restarts from a low value and must not be rejected against the old floor. + */ + fun reset() { + lock.withLock { + recentTimestampsMs.clear() + recentSequences.clear() + lastAcceptedSequence = -1L + } + } + + /** Test-only: clear in-memory dedup state. */ + internal fun clearDedupForTests() = reset() +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt new file mode 100644 index 000000000000..33297ad8f41d --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt @@ -0,0 +1,1255 @@ +package app.aaps.plugins.source + +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.model.TE +import app.aaps.core.data.plugin.PluginType +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.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.notifications.NotificationId +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginDescription +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.rx.bus.RxBus +import app.aaps.core.interfaces.rx.events.EventRefreshOverview +import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.interfaces.source.CgmSensorStatusProvider +import app.aaps.core.interfaces.source.CgmStagingEvidence +import app.aaps.core.interfaces.source.CgmWarmupProvider +import app.aaps.core.interfaces.source.CgmWarmupStatus +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.ui.CoreUiStrings +import app.aaps.core.ui.compose.icons.IcPluginByoda +import app.aaps.core.ui.compose.preference.PreferenceSubScreenDef +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.source.compose.BgSourceComposeContent +import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey +import app.aaps.plugins.source.keys.DexcomOnePlusIntKey +import app.aaps.plugins.source.keys.DexcomOnePlusIntentKey +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.ContributesIntoMap +import dev.zacsweers.metro.IntKey +import dev.zacsweers.metro.SingleIn +import dev.zacsweers.metro.binding +import app.aaps.core.interfaces.concurrent.aapsIoDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlin.concurrent.Volatile +import kotlin.time.Clock + +/** + * Native Dexcom ONE+ / G7 BG source: the BLE driver of `:plugins:dexcom_oneplus` runs inside AAPS, + * no Dexcom app or xDrip is needed. + * + * Two sensor slots. The production slot feeds the loop. The staging slot can pre-soak the next + * sensor while the old one still works; its readings are only collected and shown, never given to + * the loop, until the user (or the optional automatic switch) promotes it. + * + * Everything that needs an Android `Context` (driver registry, setup screens, foreground service, + * warm-up notification) is asked of [DexcomOnePlusHost], so this class can be tested without one. + * + * Registers itself into the plugin list. Scoped with Metro's own [SingleIn]. + */ +@ContributesIntoMap(AppScope::class, binding = binding()) +@IntKey(446) +@SingleIn(AppScope::class) +class DexcomOnePlusPlugin @Inject constructor( + rh: TextResolver, + aapsLogger: AAPSLogger, + preferences: Preferences, + config: Config, + // Not a `val`: PluginBase already keeps it as a protected property, so a second one here would + // shadow it. This only carries it to the super constructor. + notificationManager: NotificationManager, + private val host: DexcomOnePlusHost, + private val persistenceLayer: PersistenceLayer, + private val activePlugin: ActivePlugin, + private val rxBus: RxBus, +) : AbstractBgSourcePlugin( + pluginDescription = PluginDescription() + .mainType(PluginType.BGSOURCE) + // No `showInList` call: the plugin is listed in every build, like the other BG sources. + .composeContent { plugin -> + BgSourceComposeContent( + title = rh.gs(SourceStrings.dexcom_oneplus_native), + ) + } + .icon(IcPluginByoda) + .pluginName(SourceStrings.dexcom_oneplus_native) + .preferencesVisibleInSimpleMode(false) + .description(SourceStrings.description_source_dexcom_oneplus_native), + ownPreferences = DexcomOnePlusIntentKey.entries + DexcomOnePlusBooleanKey.entries + DexcomOnePlusIntKey.entries, + aapsLogger, + rh, + preferences, + config, + notificationManager, +), BgSource, OnePlusGlucoseWatcher, CgmSensorStatusProvider { + + private val resources: TextResolver = rh + + /** + * Scope of the work this plugin starts: database writes of readings, the sensor age repair, the + * reconnect watchdog and the automatic promotion. + * + * Made when work is first needed (normally by [onStart]) and cancelled in [onStop], so nothing + * runs for a user who never enables the plugin, and nothing keeps running after it is stopped. + * A user action on a setup screen after a stop makes a new one. + */ + private var workScope: CoroutineScope? = null + + /** Guards [workScope]. */ + private val workScopeLock = AapsLock() + + private fun ioScope(): CoroutineScope = workScopeLock.withLock { + workScope ?: CoroutineScope(SupervisorJob() + aapsIoDispatcher).also { workScope = it } + } + + /** Cancels everything started on [ioScope]. */ + private fun cancelWork() { + workScopeLock.withLock { + workScope?.cancel() + workScope = null + } + } + + /** True while a job started by this plugin is still running. For tests. */ + internal fun hasRunningWork(): Boolean = workScopeLock.withLock { + workScope?.coroutineContext?.get(Job)?.children?.any { it.isActive } == true + } + + /** + * The last resort that brings a sensor back. + * + * The driver has its own ladder of retries and it is the one that should do the work. This is + * the net for the case where that ladder itself stops, whatever the reason: as long as a sensor + * is stored and the session is down, the plugin asks for a connection again. Without it the + * only way back was to open the Start screen and connect by hand. + */ + private var reconnectWatchdog: Job? = null + + private val driver: OnePlusCgmDriver + get() = host.productionDriver() + + /** Dedicated STAGING (pre-soak) driver instance — its own BLE session and its own store. */ + private val stagingDriver: OnePlusCgmDriver + get() = host.stagingDriver() + + @Volatile + private var warmupPhase: OnePlusWarmupState.Phase = OnePlusWarmupState.Phase.IDLE + + private val _warmup = MutableStateFlow(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE)) + + /** Live warm-up / session status of the native driver — feeds the ongoing notification and the warm-up ring. */ + val warmup: StateFlow = _warmup.asStateFlow() + + /** + * Generic [CgmWarmupProvider] view derived from the single source of truth [_warmup]. + * null while nothing is warming up / (re)connecting (READY / IDLE / FAILED). + */ + private val _warmupStatus = MutableStateFlow(DexcomOnePlusWarmupMapper.toCgmWarmupStatus(_warmup.value)) + override val warmupStatus: StateFlow = _warmupStatus.asStateFlow() + + /** Posts the user-visible alert. Tests replace it; production posts a status-bar notification. */ + internal var promotionAlerter: (String) -> Unit = { message -> host.alert(message) } + + /** Private key-value sensor store — used here only to persist/read the ingest + * high-water mark so restarts/updates don't re-insert duplicate readings. */ + private val sensorStore by lazy { host.slotStore(null) } + + /** Namespaced store for the STAGING sensor (identity / markers / session start kept separate). */ + private val stagingStore by lazy { host.slotStore(host.stagingNamespace) } + + /** Session start already checked by [healMissingSensorChange], so a deletion is not undone twice. */ + @Volatile + private var healedSensorChangeStartMs: Long = 0L + + // ---- Dual-sensor (staging / pre-soak) state ---- + + private val _lifecycle = MutableStateFlow(null) + override val lifecycle: StateFlow = _lifecycle.asStateFlow() + + private val _stagingLifecycle = MutableStateFlow(null) + override val stagingLifecycle: StateFlow = _stagingLifecycle.asStateFlow() + + private val _stagingState = MutableStateFlow(StagingState.ABSENT) + override val stagingState: StateFlow = _stagingState.asStateFlow() + + private val _stagingEvidence = MutableStateFlow(null) + override val stagingEvidence: StateFlow = _stagingEvidence.asStateFlow() + + /** + * Time left before the staging sensor has soaked [DexcomOnePlusStaging.STAGING_MIN_SETTLE_MS]. + * Updated together with [stagingState], so the overview can count down without its own copy of + * the settle rule. + */ + private val _stagingSettleRemainingMs = MutableStateFlow(null) + override val stagingSettleRemainingMs: StateFlow = _stagingSettleRemainingMs.asStateFlow() + + /** A staging sensor session exists (warming/settling), collect-only until promoted. */ + @Volatile private var stagingPresent = false + + /** Staging sensor is still warming up / (re)connecting (no glucose yet). */ + @Volatile private var stagingWarming = false + + /** Latched once the staging sensor has left warm-up; survives restarts through the slot store. */ + @Volatile private var stagingWarmupDone = false + + /** Count of valid staging EGVs collected (promotion gate). */ + @Volatile private var stagingValidEgvCount = 0 + + /** Last reading collected from the staging sensor (mg/dL), for the evidence surface. */ + @Volatile private var stagingLastValueMgdl: Double? = null + + /** Timestamp of [stagingLastValueMgdl]. */ + @Volatile private var stagingLastValueAtMs: Long? = null + + /** Recent staging readings (ts→mgdl), read by the automatic switch. Never published. */ + private val stagingBuffer = ArrayDeque>() + + /** + * Guards [stagingBuffer]. Was `stagingBufferLock.withLock`, which is JVM only; [AapsLock] is + * reentrant and blocking, the same bargain the monitor made. + */ + private val stagingBufferLock = AapsLock() + + /** + * Only one promotion at a time. Without it the button and the automatic switch could both pass + * the [stagingPresent] check and swap the driver instances twice. + */ + private val promoteMutex = Mutex() + + /** + * An automatic promotion is already on its way, so the next reading does not start another. + * + * Guarded by [autoPromoteLock] rather than by an `AtomicBoolean`, which is JVM only. The claim + * and the test of the flag happen in one guarded step, so two readings arriving together still + * start exactly one promotion. + */ + private val autoPromoteLock = AapsLock() + + @Volatile + private var autoPromoteInFlight = false + + /** Time of the last automatic try that was refused, see [StagingAutoPromotion.RETRY_INTERVAL_MS]. */ + @Volatile + private var lastAutoPromoteTryMs = 0L + + /** Watches the STAGING driver; routes glucose to a local buffer (never the loop) until promoted. */ + private val stagingWatcher = object : OnePlusGlucoseWatcher { + override fun onWarmup(state: OnePlusWarmupState) = handleStagingWarmup(state) + override fun onGlucose(sample: OnePlusGlucoseSample) = handleStagingGlucose(sample) + override fun onSession(up: Boolean, reason: String?) { + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_STAGING: session up=$up reason=$reason") + } + + override fun onError(message: String, fatal: Boolean) { + aapsLogger.error(LTag.BGSOURCE, "DEXCOM_ONEPLUS_STAGING: error fatal=$fatal $message") + } + } + + + override fun getPreferenceScreenContent() = PreferenceSubScreenDef( + key = "dexcom_oneplus_settings", + title = SourceStrings.dexcom_oneplus_native, + summary = SourceStrings.dexcom_oneplus_plugin_summary, + // The three screen buttons come from the host, because opening a screen needs a Context. + items = host.screenItems(this) + listOf( + DexcomOnePlusBooleanKey.AutoPromote, + DexcomOnePlusIntKey.AutoPromoteHours, + DexcomOnePlusBooleanKey.RepairMissingSensorChange, + DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange, + DexcomOnePlusBooleanKey.CorrectSensorStart, + // Sensor age on the overview comes from the SENSOR_CHANGE therapy event this writes. + BooleanKey.BgSourceCreateSensorChange, + ), + icon = pluginDescription.icon, + ) + + override suspend fun onStart() { + super.onStart() + ioScope() + syncDriverFromPrefs() + // Rehydrate the ingest dedup BEFORE any reconnect can deliver glucose, so an app update / + // restart cannot re-insert already-stored readings (duplicates halt the loop). Sequence floor + // from the sensor store + recent already-stored ONE+ timestamps from the DB. + val recentTs = try { + persistenceLayer.getBgReadingsDataFromTime(nowMs() - INGEST_SEED_WINDOW_MS, ascending = true) + .filter { it.sourceSensor == SourceSensor.DEXCOM_ONEPLUS_NATIVE } + .map { it.timestamp } + } catch (t: Throwable) { + aapsLogger.error(LTag.BGSOURCE, "DEXCOM_ONEPLUS_BG: ingest seed query failed: ${t.message}", t) + emptyList() + } + DexcomOnePlusIngest.seed(sensorStore.loadLastIngestSequence(), recentTs) + refreshProductionLifecycle() + // Before either slot resumes: an install that hit the cross-slot collision was left with the + // same MAC in both stores, and the two resumes below would recreate it on every start. + reconcileSlotsOnSameSensor() + val autoResumeQueued = driver.resumeStoredSession() + val stagingResumeQueued = resumeStagingSessionIfStored() + warmupPhase = driver.warmupState().phase + // The privilege the OEM profiles have been asking for since they were written. Only when a + // sensor is actually stored: no session wanted, no service, no notification. + refreshSessionService() + // Reconcile a warm-up notification that survived a process restart with the driver's current + // state — cancels it when warm-up is already READY/IDLE (otherwise nothing clears the stale + // status-bar notification until the next onWarmup event, which may never arrive after restart). + host.showWarmup(driver.warmupState()) + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: plugin start " + + "autoResumeQueued=$autoResumeQueued " + + "stagingResumeQueued=$stagingResumeQueued", + ) + } + + override suspend fun onStop() { + cancelReconnectWatchdog() + driver.removeWatcher(this) + driver.shutdown() + // Tear down any staging session too (independent of production). + runCatching { stagingDriver.removeWatcher(stagingWatcher) } + runCatching { stagingDriver.shutdown() } + host.cancelWarmupNotification() + host.setSessionServiceWanted(false) + // Last, after the drivers are stopped, so no late callback can start new work after it. + cancelWork() + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_SESSION: plugin stop") + super.onStop() + } + + /** + * Make sure this plugin watches the production driver and that the driver has its platform. + * Safe to call from the Start screen before connect. + */ + fun syncDriverFromPrefs() { + host.attachPlatform(host.attachProductionDriver(watcher = this)) + } + + override fun onWarmup(state: OnePlusWarmupState) { + warmupPhase = state.phase + _warmup.value = state + // Set here, together with _warmup, instead of a collector: no coroutine runs while the + // plugin is off, and the value can never lag behind _warmup. + _warmupStatus.value = DexcomOnePlusWarmupMapper.toCgmWarmupStatus(state) + host.showWarmup(state) + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_WARMUP: phase=${state.phase} remainingMs=${state.remainingMs} msg=${state.message}", + ) + } + + /** + * Watcher callback thread is not guaranteed (the real driver may call from its BLE executor). + * + * ⚠️ ASYNC IMPACT: GV mapping on the callback thread; [PersistenceLayer.insertCgmSourceData] + * runs on [ioScope] (IO). Do not block the BLE executor from this callback. + */ + override fun onGlucose(sample: OnePlusGlucoseSample) { + if (DexcomOnePlusIngest.isWarmupBlockingIngest(warmupPhase)) { + aapsLogger.debug( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_BG: ignored during WARMING ${sample.mgdl.toInt()} @${sample.timestampMs}", + ) + return + } + // A real glucose reading means warm-up / (re)connection is over. Force READY so the lingering + // ongoing notification is cancelled, even if the driver never emits an explicit READY event + // (the reported "notification stuck forever" case). Idempotent: only fires while a + // non-terminal warm-up phase is still showing. + if (warmupPhase != OnePlusWarmupState.Phase.READY && warmupPhase != OnePlusWarmupState.Phase.IDLE) { + onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY)) + } + ingestToLoop(sample, sensorStore) + } + + /** + * Dedup + publish a reading to the loop (`insertCgmSourceData`) and persist its ingest high-water + * mark to [store]. + */ + private fun ingestToLoop(sample: OnePlusGlucoseSample, store: OnePlusSensorStore) { + if (!DexcomOnePlusIngest.shouldAccept(sample)) { + aapsLogger.debug( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_BG: dedup drop ${sample.mgdl.toInt()} @${sample.timestampMs} seq=${sample.sequence}", + ) + return + } + val glucoseValues = listOf(DexcomOnePlusIngest.mapToGv(sample)) + ioScope().launch { + val result = persistenceLayer.insertCgmSourceData( + Sources.DexcomOnePlus, + glucoseValues, + emptyList(), + sensorInsertionTime = null, + ) + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_BG: insert complete — inserted: ${result.inserted.size}, updated: ${result.updated.size}", + ) + // Persist the ingest high-water mark so a restart/update can't re-insert this reading, + // and anchor the production sensor's lifecycle (session start) on first reading. + store.saveLastIngest(sample.sequence, sample.timestampMs) + // Off: the reading time. On: a manual SENSOR_CHANGE from the last day. + val sessionStartMs = if (preferences.get(DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange)) { + DexcomOnePlusSensorChangeAnchor.resolve( + autoStartMs = sample.timestampMs, + lastSensorChangeMs = persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)?.timestamp, + now = nowMs(), + ) + } else { + sample.timestampMs + } + store.saveSessionStartIfAbsent(sessionStartMs) + refreshProductionLifecycle() + } + } + + /** + * The user explicitly started [deviceAddress] from the Start screen: anchor the sensor age on + * that moment and log a `SENSOR_CHANGE` therapy event. + * + * Without it the overview sensor age stayed empty for this source (nothing ever wrote the event) + * and had to be entered by hand in Care. Anchoring on the user action rather than on the first + * reading keeps the age honest — the first reading only arrives after the ~30 min warm-up. + * + * No-op when the same sensor is simply re-connected, so re-pairing a running sensor does not + * rejuvenate its age. The therapy event itself follows [BooleanKey.BgSourceCreateSensorChange]. + * + * @param previousMac MAC stored for the running session before this start, so a sensor anchored + * by an older build (session start without its owner MAC) is still seen as the same sensor. + */ + fun onSensorSessionStarted( + deviceAddress: String, + previousMac: String?, + startMs: Long = nowMs(), + ) { + // A first pairing happens after onStart, when nothing was stored yet and so no service was + // asked for. Before the early return: adopting the same sensor again is still a session. + if (profileWantsForegroundService()) { + host.setSessionServiceWanted(true) + } + if (!preferences.get(DexcomOnePlusBooleanKey.AnchorSessionToManualSensorChange)) { + // Not anchored: the caller's timestamp, on the caller's thread. + if (!sensorStore.startSessionForSensor(deviceAddress, startMs, previousMac)) return + refreshProductionLifecycle() + logSensorChange(startMs) + return + } + ioScope().launch { + val anchoredStartMs = DexcomOnePlusSensorChangeAnchor.resolve( + autoStartMs = startMs, + lastSensorChangeMs = persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)?.timestamp, + now = nowMs(), + ) + if (!sensorStore.startSessionForSensor(deviceAddress, anchoredStartMs, previousMac)) return@launch + refreshProductionLifecycle() + logSensorChange(anchoredStartMs) + } + } + + /** + * Creates the `SENSOR_CHANGE` therapy event the overview sensor age reads. The DB transaction + * ignores a second event with the same timestamp, so this is safe to call again for one session. + */ + private fun logSensorChange(startMs: Long) { + if (!preferences.get(BooleanKey.BgSourceCreateSensorChange)) return + ioScope().launch { writeSensorChange(startMs) } + } + + /** @return true when a sensor change was really written (the DB refuses a duplicate timestamp). */ + private suspend fun writeSensorChange(startMs: Long): Boolean { + val result = persistenceLayer.insertCgmSourceData( + Sources.DexcomOnePlus, + emptyList(), + emptyList(), + sensorInsertionTime = startMs, + ) + val inserted = result.sensorInsertionsInserted.isNotEmpty() + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: sensor change logged startMs=$startMs " + + "inserted=${result.sensorInsertionsInserted.size}", + ) + return inserted + } + + /** + * Move the insertion time of the sensor that feeds the loop — the Status screen's "correct the + * insertion date". + * + * Two clocks have to agree, or the correction is only half visible: this source's own session + * start and the `SENSOR_CHANGE` therapy event. Calibration entries are kept. + * + * Returns [DexcomOnePlusSensorStartCorrection.Verdict.Disabled] and changes nothing while + * [DexcomOnePlusBooleanKey.CorrectSensorStart] is off. + */ + suspend fun correctProductionSensorStart(newStartMs: Long): DexcomOnePlusSensorStartCorrection.Verdict { + if (!preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart)) { + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: insertion date refused — correction switch is off", + ) + return DexcomOnePlusSensorStartCorrection.Verdict.Disabled + } + val currentStartMs = sensorStore.loadSessionStart() + val now = nowMs() + val verdict = DexcomOnePlusSensorStartCorrection.validate(newStartMs, currentStartMs, now) + if (verdict != DexcomOnePlusSensorStartCorrection.Verdict.Accepted) { + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: insertion date refused verdict=$verdict " + + "newStartMs=$newStartMs currentStartMs=$currentStartMs", + ) + return verdict + } + val from = DexcomOnePlusSensorStartCorrection.cleanupFrom(newStartMs, currentStartMs) + val taken = persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(from, true) + .filter { it.type == TE.Type.SENSOR_CHANGE } + .map { it.timestamp } + .toSet() + val stampMs = DexcomOnePlusSensorStartCorrection.freeTimestamp(newStartMs, taken) + val stale = persistenceLayer.getTherapyEventDataFromToTime(from, now) + .filter { it.type == TE.Type.SENSOR_CHANGE } + stale.forEach { event -> + persistenceLayer.invalidateTherapyEvent( + id = event.id, + action = Action.CAREPORTAL_REMOVED, + source = Sources.DexcomOnePlus, + note = event.note, + listValues = listOf( + ValueWithUnit.Timestamp(event.timestamp), + ValueWithUnit.TEType(event.type), + ), + ) + } + sensorStore.overwriteSessionStart(stampMs) + val written = writeSensorChange(stampMs) + healedSensorChangeStartMs = stampMs + refreshProductionLifecycle() + rxBus.send(EventRefreshOverview(from = "DexcomOnePlus insertion date")) + val nowShowing = persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)?.timestamp + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: insertion date corrected from=$currentStartMs to=$stampMs " + + "asked=$newStartMs removedSensorChanges=${stale.size} written=$written " + + "lastSensorChangeNow=$nowShowing", + ) + return verdict + } + + override fun onSession(up: Boolean, reason: String?) { + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_SESSION: up=$up reason=$reason") + // A session that ended because someone asked for it must stay ended. Everything else — a + // lost link, an error, the EGV loop falling out — is a candidate for the watchdog. + when { + up -> cancelReconnectWatchdog() + reason in DELIBERATE_STOPS -> cancelReconnectWatchdog() + else -> armReconnectWatchdog() + } + } + + /** + * Asks for a connection again when the session has been down for a while. + * + * One watch at a time: a new one replaces the old, so a session that flaps does not leave a + * queue behind. It does nothing when the driver has already brought the session back by itself, + * which is the normal case, and nothing when no sensor is stored. + */ + private fun armReconnectWatchdog() { + reconnectWatchdog?.cancel() + reconnectWatchdog = ioScope().launch { + delay(RECONNECT_WATCHDOG_MS) + if (driver.isSessionUp()) return@launch + val real = driver + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: session still down after ${RECONNECT_WATCHDOG_MS / 60_000} min, asking again", + ) + host.attachPlatform(real) + real.resumeStoredSession() + } + } + + private fun cancelReconnectWatchdog() { + reconnectWatchdog?.cancel() + reconnectWatchdog = null + } + + /** + * Whether this phone's OEM profile asks for a foreground service. + * + * Every profile says true today, which is why the flag looked dead. It is read rather than + * assumed so a future profile can opt out on a stack where the service costs more than it buys. + */ + private fun profileWantsForegroundService(): Boolean = + DeviceProfileRegistry.resolve().useForegroundService + + /** + * Keep the `connectedDevice` service alive while EITHER slot has a sensor stored, and give the + * privilege back when neither does. + * + * A pre-soak is a Bluetooth session like any other, so a phone whose only stored sensor is a + * pre-soak needs the service just as much. It never throws: it is called from production paths + * as well as from pre-soak ones. + * + * The `runCatching` is on purpose: a failure is logged and does not break a promotion. + */ + private fun refreshSessionService() { + runCatching { + val wanted = profileWantsForegroundService() && + (sensorStore.load() != null || stagingStore.load() != null) + host.setSessionServiceWanted(wanted) + }.onFailure { t -> + aapsLogger.error(LTag.BGSOURCE, "DEXCOM_ONEPLUS_SESSION: session service refresh failed, ${t.message}", t) + } + } + + override fun onError(message: String, fatal: Boolean) { + aapsLogger.error(LTag.BGSOURCE, "DEXCOM_ONEPLUS_ERROR: fatal=$fatal $message") + } + + // ---------------- Dual-sensor (staging / pre-soak) ---------------- + + /** + * Undoes a poisoned pair of stores: the same transmitter recorded in both slots. + * + * The arbiter stops a second session being opened, but it cannot decide *which* slot was the + * mistake, and it would leave the loser of the race silently unable to connect for the rest of + * the run. So the ambiguity is resolved here, once, before anything connects. + * + * Production wins on purpose. It is the sensor the loop is dosing on, its store carries the + * session start the overview sensor age reads, and a pre-soak is by definition the disposable + * one. The staging slot is cleared the same way an explicit cancel clears it, so a later pre-soak + * starts from a genuine fresh soak clock rather than inheriting a start time it did not earn. + */ + private fun reconcileSlotsOnSameSensor() { + val productionMac = sensorStore.load()?.lastMac ?: return + if (!DexcomOnePlusStaging.isSameTransmitter(stagingStore.load()?.lastMac, productionMac)) return + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_STAGING: both slots hold the same sensor — clearing the pre-soak slot, " + + "production keeps it (cross-slot collision recovery)", + ) + runCatching { stagingDriver.removeWatcher(stagingWatcher) } + runCatching { stagingDriver.disconnect() } + runCatching { stagingDriver.shutdown() } + runCatching { stagingStore.clearAll() } + stagingPresent = false + stagingWarmupDone = false + stagingValidEgvCount = 0 + stagingLastValueMgdl = null + stagingLastValueAtMs = null + stagingBufferLock.withLock { stagingBuffer.clear() } + _stagingLifecycle.value = null + refreshStagingState() + refreshStagingEvidence() + } + + /** + * Whether [deviceAddress] is the sensor the pre-soak slot holds. + * + * The one thing the dual-slot design cannot separate is the sensor itself. Two slots on one MAC + * means two KEKS handshakes over a single ACL link: both GATT clients subscribe to the same Auth + * and ExtraData characteristics, so each receives the other's notifications and the transmitter + * sees one interleaved write stream. A field log showed both sides dying inside libkeks within + * 1.6 s of the second connect, on a handshake that had just reported `authenticated=1`. It is + * not a race that sometimes bites — it is certain. + */ + fun isStagingSensor(deviceAddress: String): Boolean = + DexcomOnePlusStaging.isSameTransmitter(stagingStore.load()?.lastMac, deviceAddress) + + /** Whether [deviceAddress] is the sensor currently feeding the loop — see [isStagingSensor]. */ + fun isProductionSensor(deviceAddress: String): Boolean = + DexcomOnePlusStaging.isSameTransmitter(sensorStore.load()?.lastMac, deviceAddress) + + /** + * Starts a pre-soak on [deviceAddress]. + * + * @return false when the request was refused because that sensor already feeds the loop. The + * caller must not connect the staging driver in that case. Refusing here rather than only in + * the UI keeps the invariant for every future call site. + */ + fun beginStaging(deviceAddress: String): Boolean { + // Like onSensorSessionStarted, and before the early return: a pre-soak started while + // production is stopped is still a Bluetooth session, and without this it would run its GATT + // link with no foreground service at all. + if (profileWantsForegroundService()) { + host.setSessionServiceWanted(true) + } + if (isProductionSensor(deviceAddress)) { + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_STAGING: refused — this sensor already feeds the loop, a pre-soak on it " + + "would run a second KEKS handshake on the same link", + ) + return false + } + host.attachPlatform(stagingDriver) + stagingDriver.addWatcher(stagingWatcher) + stagingPresent = true + // The soak clock starts when the sensor is applied, not at its first reading (~30 min later). + // MAC-owned, so re-running the start on the same sensor keeps its clock while a different + // sensor restarts it — a PIN-only entry can no longer inherit a previous sensor's soak. + // Read before the driver overwrites the slot's MAC in saveIdentity / connect. + val previousStagingMac = stagingStore.load()?.lastMac + val newSensor = stagingStore.startSessionForSensor(deviceAddress, nowMs(), previousStagingMac) + if (newSensor) { + // Another sensor: everything the previous soak collected is void. + stagingWarmupDone = false + stagingValidEgvCount = 0 + stagingLastValueMgdl = null + stagingLastValueAtMs = null + stagingBufferLock.withLock { stagingBuffer.clear() } + // Durability: a restart must be able to tell "a staging sensor is warming" from "no + // staging sensor" — see resumeStagingSessionIfStored. + stagingStore.saveSlotProgress(present = true, validEgvCount = 0) + stagingStore.saveSlotWarmupDone(false) + } else { + // Same sensor started again (one extra tap on the Start screen is enough). The store keeps + // its soak clock, so its progress must be kept too: resetting it sent a settled slot back + // to warm-up and hid the promote button for another ~30 min for nothing. + stagingWarmupDone = stagingStore.loadSlotWarmupDone() + stagingValidEgvCount = stagingStore.loadSlotValidEgvCount() + stagingStore.saveSlotProgress(present = true, validEgvCount = stagingValidEgvCount) + } + stagingWarming = !stagingWarmupDone + refreshStagingLifecycle() + refreshStagingState() + refreshStagingEvidence() + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_STAGING: begin") + return true + } + + /** + * Restore a STAGING sensor after a process / plugin restart. + * + * Without this the dual-instance split silently lost the pre-soak sensor: [onStart] only resumed + * the production driver, so a staged sensor that was already authenticated (identity + MAC + + * KEKS key persisted in its own store) had **no** session recreated — it could never reconnect, + * never leave warm-up and never reach the promotion gate, while its in-memory state reset to + * ABSENT. Never publishes to the loop: promotion stays an explicit user action. + */ + private fun resumeStagingSessionIfStored(): Boolean { + if (!stagingStore.loadSlotPresent()) return false + host.attachPlatform(stagingDriver) + stagingDriver.addWatcher(stagingWatcher) + // The driver itself vetoes an incomplete stored session (no MAC / PIN / KEKS key). + // It also returns false when a session is ALREADY running (nothing to queue) — tearing the + // slot down there would drop a live pre-soak on a plugin disable/enable cycle. + val alreadyRunning = stagingDriver.isSessionUp() + val queued = stagingDriver.resumeStoredSession() + if (!queued && !alreadyRunning) { + // Nothing is running for this slot, so it must not be shown as a warming sensor — that + // was the "stuck in warm-up forever" state. The store is kept intact (clearing it would + // reset session_start and let a re-start skip the soak), so the user can simply re-run + // the staging start from the Start screen. + runCatching { stagingDriver.removeWatcher(stagingWatcher) } + stagingPresent = false + stagingWarming = false + _stagingLifecycle.value = null + _stagingState.value = StagingState.ABSENT + _stagingSettleRemainingMs.value = null + aapsLogger.warn( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_STAGING: auto-resume skipped — stored staging session incomplete, re-run the sensor start", + ) + return false + } + stagingPresent = true + stagingValidEgvCount = stagingStore.loadSlotValidEgvCount() + // A settled sensor must not be shown as warming again after a restart — the latch is durable. + stagingWarmupDone = stagingStore.loadSlotWarmupDone() + stagingWarming = !stagingWarmupDone + refreshStagingLifecycle() + refreshStagingState() + refreshStagingEvidence() + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_STAGING: auto-resume queued=$queued alreadyRunning=$alreadyRunning " + + "egvCount=$stagingValidEgvCount warmupDone=$stagingWarmupDone", + ) + return true + } + + /** + * Stop and discard the staging sensor (no effect on production). + * + * Safe to call right after a promotion too: [stagingDriver] then resolves a brand new instance + * (the promoted one was handed to [DexcomOnePlusHost.promoteStagingInstance] and is production + * now), so there is nothing here to tear down. + */ + fun cancelStaging() { + runCatching { stagingDriver.removeWatcher(stagingWatcher) } + runCatching { stagingDriver.disconnect() } + runCatching { stagingDriver.shutdown() } + // Clear the staging store so a re-started staging session gets a FRESH session start. Without + // this, a stale session_start_ms would let a new sensor reach READY without a real 12 h soak + // (safety-critical settle-guard bypass). + runCatching { stagingStore.clearAll() } + stagingPresent = false + stagingWarming = false + stagingWarmupDone = false + stagingValidEgvCount = 0 + stagingLastValueMgdl = null + stagingLastValueAtMs = null + stagingBufferLock.withLock { stagingBuffer.clear() } + _stagingLifecycle.value = null + _stagingEvidence.value = null + _stagingState.value = StagingState.ABSENT + _stagingSettleRemainingMs.value = null + // Cancelling the only pre-soak on a phone with no production sensor must give the privilege + // back, otherwise the notification would stay for ever. + refreshSessionService() + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_STAGING: cancelled") + } + + /** + * SAFETY-CRITICAL: promote the staging + * sensor to production — the ONLY action that changes the loop's glucose source. Guarded on + * [StagingState.READY]. On success: stops the old production sensor, resets the ingest dedup floor + * (new EGV sequence space), migrates the staging identity into the production store (so a restart + * durably resumes the promoted sensor), and hands the staging driver INSTANCE the production role + * via [DexcomOnePlusHost.promoteStagingInstance] — its live BLE link keeps feeding the loop + * with no gap, and every other reader of [DexcomOnePlusHost.productionDriver] (the + * Status/Warmup screens, the reconnect watchdog) now sees it too. + */ + override suspend fun promoteStagingToProduction(allowEarly: Boolean): PromotionResult = + promoteMutex.withLock { promoteLocked(allowEarly, byAuto = false) } + + /** The promotion itself. Call it only while holding [promoteMutex]. */ + private suspend fun promoteLocked(allowEarly: Boolean, byAuto: Boolean): PromotionResult { + if (!stagingPresent) return rejectPromotion(PromotionRejectReason.STAGING_ABSENT, allowEarly) + if (stagingValidEgvCount < DexcomOnePlusStaging.STAGING_MIN_VALID_EGV) + return rejectPromotion(PromotionRejectReason.STAGING_NO_VALID_GLUCOSE, allowEarly) + // Defense-in-depth: re-verify the REAL soak time from the trusted persisted start rather than + // trusting the cached _stagingState — a stale start (e.g. cancel/restage) must never authorise + // an under-soaked promotion onto the loop. + val startMs = stagingStore.loadSessionStart() + if (startMs <= 0L) return rejectPromotion(PromotionRejectReason.STAGING_NOT_SETTLED, allowEarly) + if (allowEarly) { + // The user knowingly gives up the soak (production sensor stopped early). The evidence + // gates stay: enough valid readings, and one of them recent — never a silent sensor. + if (!DexcomOnePlusStaging.canPromoteEarly(stagingValidEgvCount, stagingLastValueAtMs, nowMs())) + return rejectPromotion(PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE, allowEarly) + } else { + if (nowMs() - startMs < DexcomOnePlusStaging.STAGING_MIN_SETTLE_MS) + return rejectPromotion(PromotionRejectReason.STAGING_NOT_SETTLED, allowEarly) + if (_stagingState.value != StagingState.READY) + return rejectPromotion(PromotionRejectReason.STAGING_NOT_SETTLED, allowEarly) + } + + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_PROMOTE: staging → production (by ${if (byAuto) "auto" else "user"}) early=$allowEarly " + + "soakMs=${nowMs() - startMs} egvCount=$stagingValidEgvCount", + ) + // The net must not ask for a link while the two instances are being swapped: it would ask the + // instance that is about to be retired. + cancelReconnectWatchdog() + // Taken before the swap below: after it, `stagingDriver` would build a brand new instance, + // and `driver` would already be the promoted one. + val promoted = stagingDriver + val outgoing = driver + // 1) Retire the old production sensor — stop its callbacks (no more loop feed from it). + runCatching { outgoing.removeWatcher(this) } + runCatching { outgoing.disconnect() } + // The live link is kept, so there is no gap in the glucose. Adding first and removing second + // on purpose: a moment where both watchers fire costs one buffered reading (harmless, still + // gated by [stagingPresent] below), while removing first would lose one. + promoted.addWatcher(this) + runCatching { promoted.removeWatcher(stagingWatcher) } + // 2) New sensor = different EGV sequence space → reset the persistent dedup floor. + DexcomOnePlusIngest.reset() + // 3) Durability: migrate the staging identity into the production store so a later restart + // resumes the promoted sensor on the production driver. + stagingStore.load()?.let { sensorStore.adopt(it, startMs) } + // 4) Close the pre-soak slot BEFORE its file is wiped: the staging + // callbacks are guarded on [stagingPresent], so a reading still in flight can no longer + // write `slot_warmup_done` / `slot_present` back into the file that is about to be cleared. + stagingPresent = false + stagingWarming = false + stagingWarmupDone = false + stagingValidEgvCount = 0 + stagingLastValueMgdl = null + stagingLastValueAtMs = null + stagingBufferLock.withLock { stagingBuffer.clear() } + _stagingLifecycle.value = null + _stagingEvidence.value = null + _stagingState.value = StagingState.ABSENT + _stagingSettleRemainingMs.value = null + // 5) Swap the registry: the host's production driver is now the promoted instance + // everywhere — the Status/Warmup screens and the reconnect watchdog read it directly, and + // before this swap they kept reading the retired instance for the rest of the session (the + // "Status stuck at IDLE" and "no reconnect after a dropped link" bugs). + // It also rebinds the promoted instance onto the production file, so it must happen BEFORE + // the staging file is cleared: its live link reads that file on every reconnect. + val retired = host.promoteStagingInstance() + runCatching { retired?.shutdown() } + runCatching { if (outgoing !== promoted && outgoing !== retired) outgoing.shutdown() } + // 6) Only now retire the staging store — nothing points at it any more. + stagingStore.clearAll() + // The promoted sensor becomes the loop's sensor: its age must show on the overview from the + // moment it was applied (its staging start, verified above), not from the promotion. + logSensorChange(startMs) + // That back-dated session start would otherwise pull every fingerstick taken during the + // pre-soak into this sensor's fit — all of them paired against the sensor just retired. + // A throw here does not roll the exchange above back: the result is OkBoundFailed and the + // user is told. Same wall clock as the soak math in this file (`Clock.System`). + val boundFailure: Throwable? = try { + activePlugin.activeCalibration.ignoreEntriesBefore(nowMs()) + null + } catch (thrown: Throwable) { + thrown + } + if (boundFailure != null) { + notifyPromotionProblem(SourceStrings.dexcom_oneplus_staging_promote_bound_failed, boundFailure) + } + // The promoted instance is now `default()`. Make sure this plugin watches it. + runCatching { host.attachProductionDriver(watcher = this) } + // The production status (_warmup) was last set by the OLD production driver and nothing else + // pushes to it here: a steady-state promoted driver emits no new phase-change event, so + // without this the Status screen keeps showing whatever phase production had before the + // promotion (e.g. stuck at IDLE) until the app restarts and onStart() re-polls the driver. + onWarmup(promoted.warmupState()) + refreshProductionLifecycle() + // One sensor moved from the pre-soak slot into production, so the service is still wanted, + // but the reason for it has changed. Asked again so the two slots are counted as they are. + refreshSessionService() + // A pre-soak whose link happened to be down at this exact moment must not leave the loop + // without a sensor until the watchdog wakes up 5 min later. + val followUpFailure: Throwable? = try { + if (!promoted.isSessionUp()) promoted.resumeStoredSession() + null + } catch (thrown: Throwable) { + thrown + } + if (followUpFailure != null) { + // Same protection as refreshSessionService: a throw while reading the + // store must not escape. The flag is whatever load() actually returned. + val identityPresent = runCatching { sensorStore.load() != null }.getOrElse { thrown -> + aapsLogger.error( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_PROMOTE: production identity unreadable, ${thrown.message}", + thrown, + ) + false + } + val text = if (identityPresent) { + SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed + } else { + SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed_no_identity + } + notifyPromotionProblem(text, followUpFailure) + if (boundFailure != null) return PromotionResult.OkBoundFailed + return PromotionResult.OkFollowUpFailed(productionIdentityPresent = identityPresent) + } + if (boundFailure != null) return PromotionResult.OkBoundFailed + return PromotionResult.Ok + } + + /** Error log plus the user-visible alert. Does not roll the exchange back. */ + private fun notifyPromotionProblem(text: TextRef, error: Throwable) { + val message = resources.gs(text) + aapsLogger.error(LTag.BGSOURCE, message, error) + promotionAlerter(message) + } + + /** + * A refused promotion used to be visible only as a toast, so a support package could not say why + * the user's "Promote" did nothing. Every refusal now leaves one line, with the state it saw. + */ + private fun rejectPromotion(reason: PromotionRejectReason, allowEarly: Boolean): PromotionResult { + val startMs = stagingStore.loadSessionStart() + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_PROMOTE: refused reason=$reason early=$allowEarly present=$stagingPresent " + + "state=${_stagingState.value} egvCount=$stagingValidEgvCount " + + "soakMs=${if (startMs > 0L) nowMs() - startMs else -1L} " + + "lastValueAgeMs=${stagingLastValueAtMs?.let { nowMs() - it } ?: -1L}", + ) + return PromotionResult.Rejected(reason) + } + + private fun handleStagingWarmup(state: OnePlusWarmupState) { + // A slot that is no longer there must not write its progress back into a file that was just + // wiped — a promotion detaches this watcher from the promoted instance (see + // promoteStagingToProduction), so from that moment this is only ever called for a genuinely + // new pre-soak. + if (!stagingPresent) return + // Leaving warm-up is a latched EVENT, never re-derived from the live phase — see + // [DexcomOnePlusStaging.applyWarmupPhase] for why. + val decision = DexcomOnePlusStaging.applyWarmupPhase( + warmupDoneBefore = stagingWarmupDone, + readyPhase = state.phase == OnePlusWarmupState.Phase.READY, + ) + if (decision.warmupDone) markStagingWarmupDone() else stagingWarming = decision.warming + refreshStagingState() + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_STAGING: warmup phase=${state.phase} warmupDone=$stagingWarmupDone", + ) + } + + /** Latch (and persist) "this staging sensor has left warm-up" — see [handleStagingWarmup]. */ + private fun markStagingWarmupDone() { + if (stagingWarmupDone) return + stagingWarmupDone = true + stagingWarming = false + stagingStore.saveSlotWarmupDone(true) + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_STAGING: warm-up done — slot is settling") + } + + private fun handleStagingGlucose(sample: OnePlusGlucoseSample) { + // A slot that is no longer there must not buffer a reading into state that was just reset — + // a promotion detaches this watcher from the promoted instance (see + // promoteStagingToProduction), so from that moment this is only ever called for a genuinely + // new pre-soak. + if (!stagingPresent) return + // Collect-only: kept in the local buffer, NEVER passed to insertCgmSourceData. + stagingBufferLock.withLock { + stagingBuffer.addLast(sample.timestampMs to sample.mgdl) + while (stagingBuffer.size > STAGING_BUFFER_CAP) stagingBuffer.removeFirst() + } + // A collected reading is proof warm-up is over, even if no READY phase was ever emitted. + markStagingWarmupDone() + stagingValidEgvCount++ + stagingLastValueMgdl = sample.mgdl + stagingLastValueAtMs = sample.timestampMs + // Survive a restart with the promotion gate intact (the count is the gate). + stagingStore.saveSlotProgress(present = true, validEgvCount = stagingValidEgvCount) + refreshStagingLifecycle() + refreshStagingState() + refreshStagingEvidence() + aapsLogger.debug( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_STAGING: buffered ${sample.mgdl.toInt()} count=$stagingValidEgvCount (not published)", + ) + maybeAutoPromote() + } + + /** + * Switches the pre-soak sensor to production by itself when [DexcomOnePlusBooleanKey.AutoPromote] + * is on and [StagingAutoPromotion] agrees. + * + * Called on every staging reading, so it needs no timer and survives a restart. The switch runs + * on [ioScope], never on the BLE thread that delivered the reading, and goes through the same + * [promoteLocked] as the button, with all of its checks. Before the 12 hour settling time it uses + * the button's "not settled" path. + */ + private fun maybeAutoPromote() { + // Named `askedAtMs`, not `nowMs`, so it cannot be mistaken for the `nowMs()` clock helper + // that the rest of this file calls. One reading of the clock for the whole decision. + val askedAtMs = nowMs() + if (askedAtMs - lastAutoPromoteTryMs < StagingAutoPromotion.RETRY_INTERVAL_MS) return + if (!preferences.get(DexcomOnePlusBooleanKey.AutoPromote)) return + val delayHours = preferences.get(DexcomOnePlusIntKey.AutoPromoteHours) + val startMs = stagingStore.loadSessionStart() + val decision = StagingAutoPromotion.decide( + enabled = true, + delayHours = delayHours, + startMs = startMs, + readings = stagingBufferLock.withLock { stagingBuffer.toList() }, + minRecentReadings = AUTO_PROMOTE_MIN_RECENT_READINGS, + nowMs = askedAtMs, + ) + if (decision != StagingAutoPromotion.Decision.PROMOTE) return + val claimed = autoPromoteLock.withLock { + if (autoPromoteInFlight) false else { autoPromoteInFlight = true; true } + } + if (!claimed) return + ioScope().launch { + try { + val allowEarly = askedAtMs - startMs < DexcomOnePlusStaging.STAGING_MIN_SETTLE_MS + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_PROMOTE: auto switch asked delayHours=$delayHours soakMs=${askedAtMs - startMs} early=$allowEarly", + ) + // Not cancellable: a stop must not cut the exchange in half. It is a bounded piece + // of work that schedules nothing new. + val result = withContext(NonCancellable) { + promoteMutex.withLock { promoteLocked(allowEarly, byAuto = true) } + } + if (result is PromotionResult.Rejected) { + // Refused: the reason is already in the log, see rejectPromotion. Try again later. + lastAutoPromoteTryMs = nowMs() + } else { + // Any other result means the swap happened, also when a follow-up step failed. + notificationManager.post( + NotificationId.CGM_STAGING_AUTO_PROMOTED, + resources.gs(SourceStrings.staging_auto_promote_done, resources.gs(CoreUiStrings.units_format_hours, delayHours)), + ) + } + } finally { + autoPromoteLock.withLock { autoPromoteInFlight = false } + } + } + } + + private fun refreshProductionLifecycle() { + val startMs = sensorStore.loadSessionStart() + _lifecycle.value = + DexcomOnePlusStaging.computeLifecycle(startMs, nowMs()) + if (startMs > 0L) ioScope().launch { healMissingSensorChange(startMs) } + } + + /** + * Put back the `SENSOR_CHANGE` of the running sensor when the database has none. + * + * The driver knows when its sensor started; the overview, the status line and the calibration + * plugin all read a therapy event instead. When that event is missing, every one of them falls + * back to the previous sensor. + * + * Healed once per session start: if the user deliberately deletes the event again, it is not + * resurrected on the next reading. + * + * [DexcomOnePlusBooleanKey.RepairMissingSensorChange] is a user setting, on by default. Nothing + * is written while "create sensor change" is off (see below). An occupied timestamp is stepped + * by [DexcomOnePlusSensorStartCorrection.freeTimestamp]. + */ + private suspend fun healMissingSensorChange(startMs: Long) { + if (!preferences.get(DexcomOnePlusBooleanKey.RepairMissingSensorChange)) return + if (healedSensorChangeStartMs == startMs) return + if (!preferences.get(BooleanKey.BgSourceCreateSensorChange)) { + // Said once per session, because it explains an age that can never be right: with this + // setting off nothing writes a sensor change, so every screen that reads the therapy + // event keeps showing the sensor before this one. + healedSensorChangeStartMs = startMs + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: sensor age not repaired — 'create sensor change' is off " + + "(driver start $startMs)", + ) + return + } + val last = persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)?.timestamp + // A valid event at or after this session's start means the age is already right. + if (last != null && last >= startMs - SENSOR_CHANGE_MATCH_TOLERANCE_MS) { + healedSensorChangeStartMs = startMs + return + } + healedSensorChangeStartMs = startMs + val taken = persistenceLayer.getTherapyEventDataIncludingInvalidFromTime( + startMs - SENSOR_CHANGE_MATCH_TOLERANCE_MS, + true, + ) + .filter { it.type == TE.Type.SENSOR_CHANGE } + .map { it.timestamp } + .toSet() + val stampMs = DexcomOnePlusSensorStartCorrection.freeTimestamp(startMs, taken) + val written = writeSensorChange(stampMs) + aapsLogger.info( + LTag.BGSOURCE, + "DEXCOM_ONEPLUS_SESSION: sensor age had no therapy event — rewritten at $stampMs " + + "(driver start $startMs, previous last=$last, written=$written)", + ) + if (written) rxBus.send(EventRefreshOverview(from = "DexcomOnePlus sensor age repair")) + } + + private fun refreshStagingLifecycle() { + _stagingLifecycle.value = + if (stagingPresent) DexcomOnePlusStaging.computeLifecycle(stagingStore.loadSessionStart(), nowMs()) + else null + } + + /** + * Publish what the collect-only slot has actually gathered. Without it the user is asked to wait + * ~12 h on a sensor that shows no reading anywhere, so a dead staging sensor is indistinguishable + * from a healthy one. + */ + private fun refreshStagingEvidence() { + _stagingEvidence.value = + if (!stagingPresent) null + else CgmStagingEvidence( + validCount = stagingValidEgvCount, + lastValueMgdl = stagingLastValueMgdl, + lastValueAtEpochMs = stagingLastValueAtMs, + ) + } + + private fun refreshStagingState() { + val sessionStartMs = stagingStore.loadSessionStart() + val now = nowMs() + _stagingState.value = DexcomOnePlusStaging.computeStagingState( + present = stagingPresent, + warming = stagingWarming, + sessionStartMs = sessionStartMs, + validEgvCount = stagingValidEgvCount, + nowMs = now, + ) + _stagingSettleRemainingMs.value = DexcomOnePlusStaging.settleRemainingMs( + present = stagingPresent, + sessionStartMs = sessionStartMs, + nowMs = now, + ) + } + + /** + * Wall clock, in milliseconds since the epoch. + * + * One place, so every soak, promotion and lifecycle sum in this file reads the same clock. + */ + private fun nowMs(): Long = Clock.System.now().toEpochMilliseconds() + + companion object { + + /** + * How far before the driver's own session start a therapy event may sit and still count as + * this sensor's. Covers a manual entry made a few minutes before the sensor was paired. + * A date correction may shift the stamp by a few seconds, see + * [DexcomOnePlusSensorStartCorrection.freeTimestamp]. + */ + private const val SENSOR_CHANGE_MATCH_TOLERANCE_MS = 15L * 60L * 1000L + + /** How far back to seed the ingest dedup from the DB on start — wide enough to cover any + * plausible on-reconnect backfill, capped downstream by [DexcomOnePlusIngest] RECENT_CAP. */ + private const val INGEST_SEED_WINDOW_MS = 6L * 60L * 60L * 1000L + + /** Automatic switch: readings needed in the last 30 min (6 expected at a 5 min cadence). */ + private const val AUTO_PROMOTE_MIN_RECENT_READINGS = 4 + + /** Staging QA buffer cap (~24 h at 5-min cadence). */ + private const val STAGING_BUFFER_CAP = 288 + + /** How long the session may stay down before the plugin asks for a connection again. */ + private const val RECONNECT_WATCHDOG_MS = 5L * 60L * 1000L + + /** + * Session-end reasons the user or the app asked for. The watchdog must not undo those; every + * other reason is a link that went away on its own and is worth chasing. + */ + private val DELIBERATE_STOPS = setOf("disconnect", "shutdown", "cancelled") + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSessionService.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSessionService.kt new file mode 100644 index 000000000000..aafe01561167 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSessionService.kt @@ -0,0 +1,122 @@ +package app.aaps.plugins.source + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat +import app.aaps.plugins.source.activities.DexcomOnePlusStatusActivity +import app.aaps.core.ui.R as CoreUiR + +/** + * Keeps the Dexcom ONE+ / G7 Bluetooth session alive while the screen is off. + * + * Why this exists: the OEM profiles have carried `useForegroundService = true` since they were + * written, but nothing started a service until this class. The driver ran on whatever else in the + * app happened to be alive, and the only foreground service in the process is the + * persistent-notification one, declared `dataSync`. Since the app targets Android 14 the + * foreground service **type** is what grants a privilege, and `dataSync` grants nothing for + * Bluetooth: a GATT link owned by no `connectedDevice` service is exactly what an aggressive OEM + * tears down when the phone goes to sleep. + * + * The service holds no logic and owns no driver. It exists so the platform sees a `connectedDevice` + * foreground service for as long as a sensor session is wanted, and it disappears the moment it is + * not — see [start] and [stop]. + * + * The notification is separate from [DexcomOnePlusWarmupNotification]: that one is about warm-up + * progress and clears at READY, while this one has to stay for the whole session or the service is + * not a foreground service any more. Both live on the same channel, so the user has one switch. + */ +class DexcomOnePlusSessionService : Service() { + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + createChannel() + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + buildNotification(), + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE + } else { + 0 + }, + ) + // The session lives on the driver, not here. If the platform kills us, coming back with a + // null intent must not be read as "start a session"; the plugin asks again when it needs to. + return START_NOT_STICKY + } + + private fun buildNotification() = + NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(CoreUiR.drawable.notif_icon) + .setContentTitle(getString(R.string.dexcom_oneplus_notif_title)) + .setContentText(getString(R.string.dexcom_oneplus_notif_session_alive)) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setShowWhen(false) + .setContentIntent(openStatusIntent()) + .build() + + private fun openStatusIntent(): PendingIntent = + PendingIntent.getActivity( + this, + REQUEST_CODE, + Intent(this, DexcomOnePlusStatusActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + + private fun createChannel() { + val manager = getSystemService(NotificationManager::class.java) ?: return + if (manager.getNotificationChannel(CHANNEL_ID) != null) return + manager.createNotificationChannel( + NotificationChannel( + CHANNEL_ID, + getString(R.string.dexcom_oneplus_notif_channel_name), + DEXCOM_ONEPLUS_STATUS_CHANNEL_IMPORTANCE, + ).apply { description = getString(R.string.dexcom_oneplus_notif_channel_desc) }, + ) + } + + companion object { + + private const val CHANNEL_ID = "DEXCOM_ONEPLUS_STATUS" + + /** Distinct from the warm-up notification id: both may be shown at the same time. */ + private const val NOTIFICATION_ID = 8932 + private const val REQUEST_CODE = 8932 + + /** + * Ask the platform for a `connectedDevice` foreground service. + * + * Safe to call repeatedly: a second start on a running service only re-posts the same + * notification. Failures are swallowed on purpose — a sensor session that cannot get a + * service is worse off, but it must still run. + */ + fun start(context: Context) { + runCatching { + val intent = Intent(context, DexcomOnePlusSessionService::class.java) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + context.startForegroundService(intent) + } else { + context.startService(intent) + } + } + } + + /** Give the privilege back. Safe when the service is not running. */ + fun stop(context: Context) { + runCatching { + context.stopService(Intent(context, DexcomOnePlusSessionService::class.java)) + } + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapper.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapper.kt new file mode 100644 index 000000000000..e15809147b81 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupMapper.kt @@ -0,0 +1,44 @@ +package app.aaps.plugins.source + +import app.aaps.core.interfaces.source.CgmWarmupStatus +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.source.compose.DexcomOnePlusWarmupCountdown + +/** + * Pure mapping of the native [OnePlusWarmupState] onto the generic [CgmWarmupStatus] consumed by the + * warm-up ring and the ongoing notification. + * + * Active phases (WARMING / CONNECTING / RECONNECTING / PAIRING) → an active status carrying the + * countdown/message; terminal or idle phases (READY / IDLE / FAILED) → `null` (nothing to show). + * + * Extracted from [DexcomOnePlusPlugin] so it is unit-testable without the DI graph. + */ +internal object DexcomOnePlusWarmupMapper { + + fun toCgmWarmupStatus(state: OnePlusWarmupState): CgmWarmupStatus? { + val mappedPhase = when (state.phase) { + OnePlusWarmupState.Phase.WARMING -> CgmWarmupStatus.Phase.WARMING + OnePlusWarmupState.Phase.CONNECTING -> CgmWarmupStatus.Phase.CONNECTING + OnePlusWarmupState.Phase.RECONNECTING -> CgmWarmupStatus.Phase.RECONNECTING + OnePlusWarmupState.Phase.PAIRING -> CgmWarmupStatus.Phase.PAIRING + OnePlusWarmupState.Phase.READY, + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.FAILED -> return null + } + return CgmWarmupStatus( + active = true, + phase = mappedPhase, + remainingMs = state.remainingMs, + endsAtEpochMs = state.endsAtEpochMs, + // Nominal ONE+/G7 warm-up length (~30 min) so the warm-up ring fills. Supplied while + // warming, and also when a connection phase still carries the sticky warm-up deadline + // (a duty-cycle reconnect during warm-up must not blank the ring). Phases without any + // deadline have no countdown total → indeterminate ring. + totalMs = if (mappedPhase == CgmWarmupStatus.Phase.WARMING || state.endsAtEpochMs != null) { + DexcomOnePlusWarmupCountdown.LOCAL_FALLBACK_DURATION_MS + } else { + null + }, + ) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupNotification.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupNotification.kt new file mode 100644 index 000000000000..11b2cb7d229f --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupNotification.kt @@ -0,0 +1,187 @@ +package app.aaps.plugins.source + +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.os.Build +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.source.activities.DexcomOnePlusWarmupActivity +import app.aaps.plugins.source.compose.DexcomOnePlusWarmupCountdown +import app.aaps.plugins.source.compose.toCgmWarmupInfo +import app.aaps.core.ui.R as CoreUiR + +/** Importance of the shared ONE+ status channel. One value, so it can be changed in one place. */ +internal const val DEXCOM_ONEPLUS_STATUS_CHANNEL_IMPORTANCE = NotificationManager.IMPORTANCE_LOW + +/** + * Ongoing status-bar notification mirroring the live Dexcom ONE+ session / warm-up state + * ([OnePlusWarmupState]). It lets the user leave the warm-up screen and the app while the driver + * session keeps running in the background: the notification reflects the honest phase + * (connecting / reconnecting / warming) with a live countdown, and clears at READY / IDLE. + * + * Plugin-owned; touches no shared module. + * + * NOTE: [CoreUiR.drawable.notif_icon] is the shared status-bar glyph. + */ +class DexcomOnePlusWarmupNotification(private val context: Context) { + + init { + createChannel() + } + + /** Reflect [state] into the ongoing notification, or clear it when there is nothing to show. */ + fun update(state: OnePlusWarmupState) { + when (state.phase) { + OnePlusWarmupState.Phase.IDLE, + OnePlusWarmupState.Phase.READY -> { + cancel() + return + } + + else -> Unit + } + + val ongoing = state.phase != OnePlusWarmupState.Phase.FAILED + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(CoreUiR.drawable.notif_icon) + .setContentTitle(context.getString(R.string.dexcom_oneplus_notif_title)) + .setOnlyAlertOnce(true) + .setOngoing(ongoing) + .setAutoCancel(!ongoing) + .setContentIntent(openDetailIntent()) + + when (state.phase) { + OnePlusWarmupState.Phase.PAIRING -> + builder.setContentText(context.getString(R.string.dexcom_oneplus_notif_pairing)) + .setProgress(0, 0, true) + .setShowWhen(false) + + OnePlusWarmupState.Phase.CONNECTING -> + builder.setContentText(context.getString(R.string.dexcom_oneplus_notif_connecting)) + .setProgress(0, 0, true) + .setShowWhen(false) + + OnePlusWarmupState.Phase.RECONNECTING -> { + // A reconnect that is really a long ADV silence must say so: the field case showed + // an unchanging "Reconnecting…" for 18 min while nothing was happening. + val silenceMinutes = state.advSilenceMinutes + when { + state.staleMacSuspected -> + builder.setContentTitle(context.getString(R.string.dexcom_oneplus_notif_stale_mac_title)) + .setContentText(context.getString(R.string.dexcom_oneplus_notif_stale_mac_text)) + .setStyle( + NotificationCompat.BigTextStyle() + .bigText(context.getString(R.string.dexcom_oneplus_notif_stale_mac_text)), + ) + + silenceMinutes != null && silenceMinutes > 0 -> + builder.setContentText( + context.getString( + R.string.dexcom_oneplus_notif_waiting_adv, + silenceMinutes.toInt(), + ), + ) + + else -> + builder.setContentText(context.getString(R.string.dexcom_oneplus_notif_reconnecting)) + } + builder.setProgress(0, 0, true).setShowWhen(false) + } + + OnePlusWarmupState.Phase.WARMING -> { + builder.setContentTitle(context.getString(R.string.dexcom_oneplus_notif_warming_title)) + .setContentText(context.getString(R.string.dexcom_oneplus_notif_warming_text)) + val remaining = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = state.toCgmWarmupInfo(), + nowEpochMs = System.currentTimeMillis(), + localFallbackEndsAtEpochMs = null, + ) + if (remaining != null && remaining > 0L) { + // Live status-bar countdown to end — no per-second updates needed. + val endsAt = state.endsAtEpochMs ?: (System.currentTimeMillis() + remaining) + builder.setWhen(endsAt) + .setShowWhen(true) + .setUsesChronometer(true) + .setChronometerCountDown(true) + } else { + builder.setProgress(0, 0, true).setShowWhen(false) + } + } + + OnePlusWarmupState.Phase.FAILED -> + builder.setContentTitle(context.getString(R.string.dexcom_oneplus_notif_failed_title)) + .setContentText(context.getString(R.string.dexcom_oneplus_notif_failed_text)) + .setShowWhen(false) + + else -> Unit + } + + try { + NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build()) + } catch (_: SecurityException) { + // POST_NOTIFICATIONS denied on Android 13+ — nothing to show, session continues. + } + } + + /** One-shot alert. Not ongoing: the user must be able to dismiss it after reading the action. */ + fun alert(text: String) { + val builder = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(CoreUiR.drawable.notif_icon) + .setContentTitle(context.getString(R.string.dexcom_oneplus_native)) + .setContentText(text) + .setStyle(NotificationCompat.BigTextStyle().bigText(text)) + .setAutoCancel(true) + .setOngoing(false) + try { + NotificationManagerCompat.from(context).notify(ALERT_ID, builder.build()) + } catch (_: SecurityException) { + // POST_NOTIFICATIONS denied — the promotion result on the status screen still says it. + } + } + + fun cancel() { + try { + NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID) + } catch (_: Throwable) { + } + } + + private fun openDetailIntent(): PendingIntent { + val intent = Intent(context, DexcomOnePlusWarmupActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP + } + return PendingIntent.getActivity( + context, + 0, + intent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun createChannel() { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return + val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager + val channel = NotificationChannel( + CHANNEL_ID, + context.getString(R.string.dexcom_oneplus_notif_channel_name), + DEXCOM_ONEPLUS_STATUS_CHANNEL_IMPORTANCE, + ).apply { + description = context.getString(R.string.dexcom_oneplus_notif_channel_desc) + enableVibration(false) + setSound(null, null) + } + nm.createNotificationChannel(channel) + } + + companion object { + private const val CHANNEL_ID = "DEXCOM_ONEPLUS_STATUS" + private const val NOTIFICATION_ID = 8931 + + /** Not 8931 (warm-up) and not 8932 (session foreground service): those replace each other. */ + private const val ALERT_ID = 8933 + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/OnePlusBlePermissionHelper.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/OnePlusBlePermissionHelper.kt new file mode 100644 index 000000000000..5d7e1dc1ff4b --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/OnePlusBlePermissionHelper.kt @@ -0,0 +1,45 @@ +package app.aaps.plugins.source + +import android.Manifest +import android.app.Activity +import android.content.pm.PackageManager +import android.os.Build +import androidx.core.app.ActivityCompat +import androidx.core.content.ContextCompat + +/** + * Runtime BLE permission helpers for the ONE+ start screen. + * The manifest declarations live in the app and driver modules; this only requests at runtime. + */ +object OnePlusBlePermissionHelper { + + const val REQUEST_CODE: Int = 44601 + + fun requiredPermissions(): Array { + return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + arrayOf( + Manifest.permission.BLUETOOTH_SCAN, + Manifest.permission.BLUETOOTH_CONNECT, + ) + } else { + arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) + } + } + + fun missingPermissions(activity: Activity): Array { + return requiredPermissions() + .filter { + ContextCompat.checkSelfPermission(activity, it) != PackageManager.PERMISSION_GRANTED + } + .toTypedArray() + } + + fun hasAll(activity: Activity): Boolean = missingPermissions(activity).isEmpty() + + fun requestMissing(activity: Activity) { + val missing = missingPermissions(activity) + if (missing.isNotEmpty()) { + ActivityCompat.requestPermissions(activity, missing, REQUEST_CODE) + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivity.kt new file mode 100644 index 000000000000..20dd7113f5ac --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivity.kt @@ -0,0 +1,226 @@ +package app.aaps.plugins.source.activities + +import android.content.Intent +import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Share +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.derivedStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +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.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.tooling.preview.Preview +import app.aaps.core.interfaces.logging.LoggerUtils +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.plugins.source.logs.DriverLogReader +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext +import dev.zacsweers.metro.Inject + +/** + * Shows what the Dexcom ONE+ / G7 driver has written, without leaving the app. + * + * The point is a user who has a sensor that does not work. Their lines are in `AndroidAPS.log` + * already, but reaching them means exporting the whole log folder and opening a five megabyte file + * on a phone. This screen reads the same file, keeps only the driver lines, and lets them be read + * or shared as they are. + * + * It is read only. Nothing here talks to a sensor. + */ +class CgmDriverLogActivity : MetroAppCompatActivity() { + + @Inject lateinit var preferences: Preferences + + @Inject lateinit var loggerUtils: LoggerUtils + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Other apps may not draw over this screen: an overlay could hide what a tap really does, here on a + // sensor (start, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. + window.setHideOverlayWindows(true) + setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + CgmDriverLogScreen( + logDirectory = loggerUtils.logDirectory, + onBack = { finish() }, + ) + } + } + } + } +} + +/** How much text a share may carry, so a long session cannot break the send. */ +private const val MAX_SHARED_CHARACTERS = 200_000 + +/** How often the screen goes back to the file while it is open. */ +private const val REFRESH_MILLIS = 5_000L + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +internal fun CgmDriverLogScreen( + logDirectory: String, + onBack: () -> Unit, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + var lines by remember { mutableStateOf(emptyList()) } + var reloads by remember { mutableIntStateOf(0) } + val listState = rememberLazyListState() + + LaunchedEffect(reloads) { + while (true) { + lines = withContext(Dispatchers.IO) { DriverLogReader.read(logDirectory) } + delay(REFRESH_MILLIS) + } + } + + // Follow the end of the log while the user is already there, and leave them alone once they + // have scrolled up to read something. + val atEnd by remember { + derivedStateOf { + val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: return@derivedStateOf true + last >= lines.size - 2 + } + } + LaunchedEffect(lines) { + if (atEnd && lines.isNotEmpty()) listState.scrollToItem(lines.lastIndex) + } + + Scaffold( + modifier = modifier, + topBar = { + AapsTopAppBar( + title = { Text(stringResource(R.string.cgm_driver_log_title)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.dexcom_oneplus_nav_back), + ) + } + }, + actions = { + IconButton(onClick = { reloads++ }) { + Icon( + imageVector = Icons.Filled.Refresh, + contentDescription = stringResource(R.string.cgm_driver_log_refresh), + ) + } + IconButton( + enabled = lines.isNotEmpty(), + onClick = { + val text = lines.joinToString("\n").takeLast(MAX_SHARED_CHARACTERS) + val send = Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, text) + context.startActivity( + Intent.createChooser(send, context.getString(R.string.cgm_driver_log_share)) + ) + }, + ) { + Icon( + imageVector = Icons.Filled.Share, + contentDescription = stringResource(R.string.cgm_driver_log_share), + ) + } + }, + ) + }, + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + .padding(horizontal = AapsSpacing.medium), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.small), + ) { + if (lines.isEmpty()) { + Text(stringResource(R.string.cgm_driver_log_empty)) + } else { + // How many lines, and whether the screen is still following the end of the file. + // "Is it still moving?" is the question this screen is opened to answer. + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = stringResource(R.string.cgm_driver_log_count, lines.size), + style = MaterialTheme.typography.labelMedium, + modifier = Modifier.weight(1f), + ) + if (atEnd) { + Text( + text = stringResource(R.string.cgm_driver_log_follow), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + } + SelectionContainer { + LazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + ) { + items(lines) { line -> + // Long lines wrap rather than run off the side. A phone is narrow and + // a driver line can be a whole hex frame; wrapping is the only way to + // read one without dragging it across the screen. + Text( + text = line, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + } + } +} + +@Preview +@Composable +private fun CgmDriverLogScreenPreview() { + MaterialTheme { + CgmDriverLogScreen(logDirectory = "", onBack = {}) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt new file mode 100644 index 000000000000..b4bf81648927 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt @@ -0,0 +1,119 @@ +package app.aaps.plugins.source.activities + +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.compose.runtime.CompositionLocalProvider +import app.aaps.core.data.plugin.PluginType +import app.aaps.core.interfaces.configuration.ConfigBuilder +import app.aaps.core.interfaces.source.SensorSlot +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.AapsTheme +import app.aaps.core.ui.compose.LocalPreferences +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.source.DexcomOnePlusHost +import app.aaps.plugins.source.DexcomOnePlusPlugin +import app.aaps.plugins.source.OnePlusBlePermissionHelper +import app.aaps.plugins.source.compose.DexcomOnePlusStartScreen +import app.aaps.plugins.source.compose.OnePlusBlePermissionGate +import dev.zacsweers.metro.Inject + +/** + * Android entry point of the sensor start screen. + * + * The screen itself is [DexcomOnePlusStartScreen]. What stays here is the Activity, the runtime + * Bluetooth permission, and the two Intents that carry the user on to the warm-up and status + * screens. + */ +class DexcomOnePlusStartActivity : MetroAppCompatActivity() { + + @Inject lateinit var dexcomOnePlusPlugin: DexcomOnePlusPlugin + @Inject lateinit var dexcomOnePlusHost: DexcomOnePlusHost + @Inject lateinit var configBuilder: ConfigBuilder + @Inject lateinit var preferences: Preferences + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Other apps may not draw over this screen: an overlay could hide what a tap really does, here on a + // sensor (start, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. + window.setHideOverlayWindows(true) + dexcomOnePlusPlugin.syncDriverFromPrefs() + dexcomOnePlusHost.attachPlatform(OnePlusCgmDrivers.default()) + setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + DexcomOnePlusStartScreen( + host = dexcomOnePlusHost, + permissions = ActivityBlePermissionGate(this), + onBack = { finish() }, + onEnsureDriver = { + dexcomOnePlusPlugin.syncDriverFromPrefs() + OnePlusCgmDrivers.default() + }, + onActivatePlugin = { + configBuilder.performPluginSwitch( + changedPlugin = dexcomOnePlusPlugin, + enabled = true, + type = PluginType.BGSOURCE, + ) + }, + onStarted = { startedSlot -> + // PRODUCTION: hand the user to the warm-up screen so the new sensor is + // visibly taken over (pairing → warm-up countdown). Returning straight to + // the overview gave no confirmation that Connect had done anything. + // STAGING: the warm-up screen tracks the production driver only, so keep + // the collect-only flow returning to the overview. + // The BLE session keeps running on the driver daemon either way; we do + // NOT disconnect/shutdown here, only finish this Activity. + if (startedSlot == SensorSlot.PRODUCTION) { + startActivity( + Intent(this, DexcomOnePlusWarmupActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), + ) + } + finish() + }, + onBeginStaging = { address -> dexcomOnePlusPlugin.beginStaging(address) }, + onIsStagingSensor = { address -> dexcomOnePlusPlugin.isStagingSensor(address) }, + onCancelStaging = { dexcomOnePlusPlugin.cancelStaging() }, + // Promotion has its own gates and its own confirmation, and they live on the + // status screen. Sending the user there is honest; re-implementing the gate + // here would be a second place to get a loop source switch wrong. + onOpenPromote = { + startActivity( + Intent(this, DexcomOnePlusStatusActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP), + ) + finish() + }, + // Straight from the driver registry, which is the same instance the + // plugin uses. The plugin hands out the OnePlusCgmDriver interface, while + // this screen needs the real driver's saveIdentity and its sighting-aware + // connect. + onStagingDriver = { OnePlusCgmDrivers.staging() }, + onSensorSessionStarted = { address, previousMac -> + dexcomOnePlusPlugin.onSensorSessionStarted(address, previousMac) + }, + ) + } + } + } + } +} + +/** + * The runtime Bluetooth permission of this phone, asked for from the Activity on top. + * + * With no Activity to ask from, the screen carries on as if the permission were there, and a scan + * that hears nothing is what the user sees. + */ +private class ActivityBlePermissionGate(private val activity: Activity?) : OnePlusBlePermissionGate { + + override fun granted(): Boolean = activity == null || OnePlusBlePermissionHelper.hasAll(activity) + + override fun request() { + activity?.let { OnePlusBlePermissionHelper.requestMissing(it) } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt new file mode 100644 index 000000000000..bd250baf5b47 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt @@ -0,0 +1,596 @@ +package app.aaps.plugins.source.activities + +import android.content.Intent +import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +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.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import app.aaps.core.data.model.GV +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.interfaces.source.CgmStagingEvidence +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.CoreUiStrings +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.AapsTheme +import app.aaps.core.ui.compose.LocalPreferences +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.core.ui.compose.dialogs.DatePickerModal +import app.aaps.core.ui.compose.dialogs.TimePickerModal +import app.aaps.core.ui.compose.stringResource as coreStringResource +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.source.DexcomOnePlusPlugin +import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection +import app.aaps.plugins.source.DexcomOnePlusStaging +import app.aaps.plugins.source.R +import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey +import app.aaps.plugins.source.compose.CgmCard +import app.aaps.plugins.source.compose.CgmCardHeader +import app.aaps.plugins.source.compose.CgmCardTone +import app.aaps.plugins.source.compose.CgmKeyValueRow +import app.aaps.plugins.source.compose.CgmLazyColumn +import app.aaps.plugins.source.compose.CgmScaffold +import app.aaps.plugins.source.compose.CgmStateChip +import app.aaps.plugins.source.compose.CgmStepTimeline +import app.aaps.plugins.source.compose.CgmUiState +import app.aaps.plugins.source.compose.DexcomOnePlusProductionCard +import app.aaps.plugins.source.compose.DexcomOnePlusUiLabels +import app.aaps.plugins.source.compose.formatSensorAge +import app.aaps.plugins.source.compose.toUiState +import dev.zacsweers.metro.Inject +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch +import java.util.Calendar +import java.util.TimeZone + +/** + * Daily status of the native Dexcom ONE+ / G7 source. + * + * The screen answers two questions that used to share one flat list of text lines: what is the + * sensor feeding the loop doing, and what is the pre-soak sensor doing. Each gets its own card, so + * a reading belongs to a visible subject. Everything sits in one scrolling list — the old + * non-scrolling column pushed the promote button, the one action that switches the loop's glucose + * source, past the bottom edge as soon as a staging sensor was present. + */ +class DexcomOnePlusStatusActivity : MetroAppCompatActivity() { + + @Inject lateinit var dexcomOnePlusPlugin: DexcomOnePlusPlugin + @Inject lateinit var preferences: Preferences + @Inject lateinit var profileUtil: ProfileUtil + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var rh: ResourceHelper + @Inject lateinit var persistenceLayer: PersistenceLayer + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Other apps may not draw over this screen: an overlay could hide what a tap really does, here on a + // sensor (start, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. + window.setHideOverlayWindows(true) + dexcomOnePlusPlugin.syncDriverFromPrefs() + setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + DexcomOnePlusStatusScreen( + onBack = { finish() }, + onOpenStart = { + startActivity(Intent(this, DexcomOnePlusStartActivity::class.java)) + }, + onOpenWarmup = { + startActivity(Intent(this, DexcomOnePlusWarmupActivity::class.java)) + }, + onOpenLog = { + startActivity( + Intent(this, CgmDriverLogActivity::class.java) + ) + }, + stagingStateFlow = dexcomOnePlusPlugin.stagingState, + stagingEvidenceFlow = dexcomOnePlusPlugin.stagingEvidence, + lifecycleFlow = dexcomOnePlusPlugin.lifecycle, + formatGlucose = { mgdl -> profileUtil.fromMgdlToStringWithUnits(mgdl) }, + formatTime = { epochMs -> dateUtil.timeString(epochMs) }, + formatAge = { millis -> formatSensorAge(millis, rh) }, + lastGlucose = { persistenceLayer.getLastGlucoseValue() }, + onCancelStaging = { dexcomOnePlusPlugin.cancelStaging() }, + onPromote = { allowEarly -> dexcomOnePlusPlugin.promoteStagingToProduction(allowEarly) }, + onCorrectSensorStart = { startMs -> dexcomOnePlusPlugin.correctProductionSensorStart(startMs) }, + ) + } + } + } + } +} + +/** How often the screen goes back to the database for the newest reading. */ +private const val GLUCOSE_REFRESH_MILLIS = 30_000L + +/** + * Text shown after Promote. Refusal means nothing was written. [PromotionResult.OkBoundFailed] + * means the exchange is kept and the calibration bound threw. [PromotionResult.OkFollowUpFailed] + * means a later step threw; the wording follows [PromotionResult.OkFollowUpFailed.productionIdentityPresent], + * which the plugin read from the production store. + */ +internal fun dexcomOnePlusPromotionMessage( + result: PromotionResult, + ok: String, + boundFailed: String, + followUpIdentityPresent: String, + followUpIdentityMissing: String, + rejectedAbsent: String, + rejectedNotSettled: String, + rejectedNoGlucose: String, + rejectedNoRecentGlucose: String, +): String = when (result) { + PromotionResult.Ok -> ok + PromotionResult.OkBoundFailed -> boundFailed + is PromotionResult.OkFollowUpFailed -> + if (result.productionIdentityPresent) followUpIdentityPresent else followUpIdentityMissing + is PromotionResult.Rejected -> when (result.reason) { + PromotionRejectReason.STAGING_ABSENT -> rejectedAbsent + PromotionRejectReason.STAGING_NOT_SETTLED -> rejectedNotSettled + PromotionRejectReason.STAGING_NO_VALID_GLUCOSE -> rejectedNoGlucose + PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE -> rejectedNoRecentGlucose + } +} + +@Composable +private fun DexcomOnePlusStatusScreen( + onBack: () -> Unit, + onOpenStart: () -> Unit, + onOpenWarmup: () -> Unit, + onOpenLog: () -> Unit, + stagingStateFlow: StateFlow, + stagingEvidenceFlow: StateFlow, + lifecycleFlow: StateFlow, + formatGlucose: (Double) -> String, + formatTime: (Long) -> String, + formatAge: (Long) -> String, + lastGlucose: suspend () -> GV?, + onCancelStaging: () -> Unit, + onPromote: suspend (Boolean) -> PromotionResult, + onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, +) { + // Not `remember`-ed: a promotion swaps which driver instance `default()` hands out (see + // OnePlusCgmDrivers.promoteStagingInstance), and a `remember`-ed reference kept polling the + // retired instance for the rest of this screen's life, showing a status stuck at whatever + // phase it had before the promotion. + var state by remember { mutableStateOf(OnePlusCgmDrivers.default().warmupState()) } + var sessionUp by remember { mutableStateOf(OnePlusCgmDrivers.default().isSessionUp()) } + var newestGlucose by remember { mutableStateOf(null) } + val preferences = LocalPreferences.current + val correctSensorStartEnabled = preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart) + val stagingState by stagingStateFlow.collectAsState() + val stagingEvidence by stagingEvidenceFlow.collectAsState() + val lifecycle by lifecycleFlow.collectAsState() + val scope = rememberCoroutineScope() + var showPromoteConfirm by remember { mutableStateOf(false) } + var promoteEarly by remember { mutableStateOf(false) } + var promoteResultText by remember { mutableStateOf(null) } + var now by remember { mutableStateOf(System.currentTimeMillis()) } + // Offer the early way out only while the sensor is proving itself right now — see canPromoteEarly. + val earlyPromoteOffered = stagingState != StagingState.ABSENT && DexcomOnePlusStaging.canPromoteEarly( + validEgvCount = stagingEvidence?.validCount ?: 0, + lastValueAtEpochMs = stagingEvidence?.lastValueAtEpochMs, + nowMs = now, + ) + + // Promotion result → user message (resolved here so the coroutine has no Composable context). + val promoteOk = stringResource(R.string.dexcom_oneplus_staging_promote_ok) + val promoteBoundFailed = stringResource(R.string.dexcom_oneplus_staging_promote_bound_failed) + val promoteFollowUpFailed = stringResource(R.string.dexcom_oneplus_staging_promote_follow_up_failed) + val promoteFollowUpNoIdentity = stringResource(R.string.dexcom_oneplus_staging_promote_follow_up_failed_no_identity) + val promoteRejectedAbsent = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_absent) + val promoteRejectedNotSettled = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_not_settled) + val promoteRejectedNoGlucose = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_no_glucose) + val promoteRejectedNoRecentGlucose = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_no_recent_glucose) + + LaunchedEffect(Unit) { + while (true) { + val driver = OnePlusCgmDrivers.default() + state = driver.warmupState() + sessionUp = driver.isSessionUp() + now = System.currentTimeMillis() + delay(1_000L) + } + } + // A reading arrives every five minutes, so the database is asked far less often than the driver + // state is polled. + LaunchedEffect(Unit) { + while (true) { + newestGlucose = lastGlucose() + delay(GLUCOSE_REFRESH_MILLIS) + } + } + + CgmScaffold( + title = stringResource(R.string.dexcom_oneplus_status_title), + onNavigate = onBack, + actions = { + IconButton(onClick = onOpenLog) { + Icon( + imageVector = Icons.AutoMirrored.Filled.List, + contentDescription = stringResource(R.string.cgm_driver_log_open), + ) + } + }, + ) { + CgmLazyColumn { + item(key = "production") { + ProductionCard( + phaseLabel = DexcomOnePlusUiLabels.phaseLabel(state.phase), + phaseState = state.phase.toUiState(), + sessionUp = sessionUp, + message = DexcomOnePlusUiLabels.userMessage(state.message), + lifecycle = lifecycle, + newestGlucose = newestGlucose, + formatGlucose = formatGlucose, + formatTime = formatTime, + formatAge = formatAge, + correctSensorStartEnabled = correctSensorStartEnabled, + onCorrectSensorStart = onCorrectSensorStart, + ) + } + // Prompt for a pre-soak exactly when it is useful: the sensor in use is near its end and + // no replacement is warming up yet. + if (lifecycle?.endOfLife == true && stagingState == StagingState.ABSENT) { + item(key = "endOfLife") { + CgmCard(tone = CgmCardTone.Warning) { + CgmCardHeader(stringResource(R.string.dexcom_oneplus_end_of_life_title)) + Text( + text = stringResource(R.string.dexcom_oneplus_end_of_life_text), + style = MaterialTheme.typography.bodyMedium, + ) + OutlinedButton(onClick = onOpenStart) { + Text(stringResource(R.string.dexcom_oneplus_start_presoak)) + } + } + } + } + item(key = "staging") { + StagingCard( + stagingState = stagingState, + stagingEvidence = stagingEvidence, + earlyPromoteOffered = earlyPromoteOffered, + formatGlucose = formatGlucose, + formatTime = formatTime, + onPromoteClick = { early -> + promoteEarly = early + showPromoteConfirm = true + }, + onCancelStaging = { + onCancelStaging() + promoteResultText = null + }, + onOpenStart = onOpenStart, + ) + } + promoteResultText?.let { message -> + item(key = "promoteResult") { + Text( + text = message, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + item(key = "actions") { + CgmCard { + CgmCardHeader(stringResource(R.string.cgm_actions_heading)) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + ) { + OutlinedButton(onClick = onOpenStart, modifier = Modifier.weight(1f)) { + Text(stringResource(R.string.dexcom_oneplus_start_action)) + } + OutlinedButton(onClick = onOpenWarmup, modifier = Modifier.weight(1f)) { + Text(stringResource(R.string.dexcom_oneplus_step_warmup)) + } + } + OutlinedButton(onClick = onOpenLog, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.cgm_driver_log_open)) + } + } + } + } + } + + if (showPromoteConfirm) { + AlertDialog( + onDismissRequest = { showPromoteConfirm = false }, + title = { + Text( + if (promoteEarly) stringResource(R.string.dexcom_oneplus_staging_promote_early_confirm_title) + else stringResource(R.string.dexcom_oneplus_staging_promote_confirm_title), + ) + }, + text = { + Text( + if (promoteEarly) stringResource(R.string.dexcom_oneplus_staging_promote_early_confirm_message) + else stringResource(R.string.dexcom_oneplus_staging_promote_confirm_message), + ) + }, + confirmButton = { + TextButton( + onClick = { + showPromoteConfirm = false + val allowEarly = promoteEarly + scope.launch { + promoteResultText = dexcomOnePlusPromotionMessage( + result = onPromote(allowEarly), + ok = promoteOk, + boundFailed = promoteBoundFailed, + followUpIdentityPresent = promoteFollowUpFailed, + followUpIdentityMissing = promoteFollowUpNoIdentity, + rejectedAbsent = promoteRejectedAbsent, + rejectedNotSettled = promoteRejectedNotSettled, + rejectedNoGlucose = promoteRejectedNoGlucose, + rejectedNoRecentGlucose = promoteRejectedNoRecentGlucose, + ) + } + }, + ) { + Text(stringResource(R.string.dexcom_oneplus_staging_promote_confirm)) + } + }, + dismissButton = { + TextButton(onClick = { showPromoteConfirm = false }) { + Text(stringResource(R.string.dexcom_oneplus_staging_promote_dismiss)) + } + }, + ) + } +} + +/** + * The sensor that feeds the loop: [DexcomOnePlusProductionCard], with the "correct insertion date" + * action under it. + */ +@Composable +private fun ProductionCard( + phaseLabel: String, + phaseState: CgmUiState, + sessionUp: Boolean, + message: String, + lifecycle: CgmSensorLifecycle?, + newestGlucose: GV?, + formatGlucose: (Double) -> String, + formatTime: (Long) -> String, + formatAge: (Long) -> String, + correctSensorStartEnabled: Boolean, + onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, +) { + DexcomOnePlusProductionCard( + phaseLabel = phaseLabel, + phaseState = phaseState, + sessionUp = sessionUp, + message = message, + lifecycle = lifecycle, + newestGlucose = newestGlucose, + formatGlucose = formatGlucose, + formatTime = formatTime, + formatAge = formatAge, + ) { + // Hidden while the setting is off. The function also refuses before any write. + if (correctSensorStartEnabled) { + lifecycle?.startedAtEpochMs?.let { startedAt -> + CorrectInsertionDateAction( + currentStartMs = startedAt, + formatTime = formatTime, + onCorrectSensorStart = onCorrectSensorStart, + ) + } + } + } +} + +/** + * "The sensor went in earlier than the app thinks." + * + * Shown only while [DexcomOnePlusBooleanKey.CorrectSensorStart] is on. + */ +@Composable +private fun CorrectInsertionDateAction( + currentStartMs: Long, + formatTime: (Long) -> String, + onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, +) { + val scope = rememberCoroutineScope() + var showDatePicker by remember { mutableStateOf(false) } + var pickedDateMs by remember { mutableStateOf(null) } + var refusal by remember { mutableStateOf(null) } + + OutlinedButton(onClick = { showDatePicker = true }) { + Text(stringResource(R.string.dexcom_oneplus_correct_insertion_date)) + } + + if (showDatePicker) { + DatePickerModal( + initialDateMillis = currentStartMs, + onDateSelected = { pickedDateMs = it }, + onDismiss = { showDatePicker = false }, + ) + } + pickedDateMs?.let { dayMs -> + val current = remember(currentStartMs) { Calendar.getInstance().apply { timeInMillis = currentStartMs } } + TimePickerModal( + initialHour = current.get(Calendar.HOUR_OF_DAY), + initialMinute = current.get(Calendar.MINUTE), + onTimeSelected = { hour, minute -> + val day = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { timeInMillis = dayMs } + val chosen = Calendar.getInstance().apply { + set(day.get(Calendar.YEAR), day.get(Calendar.MONTH), day.get(Calendar.DAY_OF_MONTH), hour, minute, 0) + set(Calendar.MILLISECOND, 0) + } + scope.launch { + val verdict = onCorrectSensorStart(chosen.timeInMillis) + if (verdict != DexcomOnePlusSensorStartCorrection.Verdict.Accepted) refusal = verdict + } + }, + onDismiss = { pickedDateMs = null }, + ) + } + refusal?.let { verdict -> + AlertDialog( + onDismissRequest = { refusal = null }, + title = { Text(stringResource(R.string.dexcom_oneplus_correct_insertion_date)) }, + text = { + Text( + stringResource( + when (verdict) { + DexcomOnePlusSensorStartCorrection.Verdict.InFuture -> + R.string.dexcom_oneplus_insertion_date_future + DexcomOnePlusSensorStartCorrection.Verdict.TooOld -> + R.string.dexcom_oneplus_insertion_date_too_old + DexcomOnePlusSensorStartCorrection.Verdict.Accepted, + DexcomOnePlusSensorStartCorrection.Verdict.NoSession, + DexcomOnePlusSensorStartCorrection.Verdict.Disabled, + -> R.string.dexcom_oneplus_insertion_date_no_session + }, + formatTime(currentStartMs), + ), + ) + }, + confirmButton = { + TextButton(onClick = { refusal = null }) { Text(coreStringResource(CoreUiStrings.ok)) } + }, + ) + } +} + +/** + * The collect-only second sensor. + * + * Promotion stays the only full width button in the card it belongs to, so it does not compete with + * the navigation buttons that used to sit above it at the same visual weight. + */ +@Composable +private fun StagingCard( + stagingState: StagingState, + stagingEvidence: CgmStagingEvidence?, + earlyPromoteOffered: Boolean, + formatGlucose: (Double) -> String, + formatTime: (Long) -> String, + onPromoteClick: (Boolean) -> Unit, + onCancelStaging: () -> Unit, + onOpenStart: () -> Unit, +) { + val stagingStateLabel = when (stagingState) { + StagingState.ABSENT -> stringResource(R.string.dexcom_oneplus_staging_state_absent) + StagingState.WARMUP -> stringResource(R.string.dexcom_oneplus_staging_state_warmup) + StagingState.SETTLING -> stringResource(R.string.dexcom_oneplus_staging_state_settling) + StagingState.READY -> stringResource(R.string.dexcom_oneplus_staging_state_ready) + } + CgmCard { + CgmCardHeader(stringResource(R.string.dexcom_oneplus_staging_heading_short)) { + CgmStateChip(state = stagingState.toUiState(), label = stagingStateLabel) + } + if (stagingState == StagingState.ABSENT) { + // An empty state that explains what the slot is for and offers the way in, instead of + // just reporting "None". + Text( + text = stringResource(R.string.dexcom_oneplus_staging_none_short), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton(onClick = onOpenStart) { + Text(stringResource(R.string.dexcom_oneplus_start_presoak)) + } + } else { + CgmStepTimeline( + labels = listOf( + stringResource(R.string.dexcom_oneplus_staging_state_warmup), + stringResource(R.string.dexcom_oneplus_staging_state_settling), + stringResource(R.string.dexcom_oneplus_staging_state_ready), + ), + reached = when (stagingState) { + StagingState.ABSENT -> -1 + StagingState.WARMUP -> 0 + StagingState.SETTLING -> 1 + StagingState.READY -> 2 + }, + ) + // Evidence the staging sensor is really alive: without it the user only sees a state + // label and cannot tell "settling with data" from "settling with a dead radio". + CgmKeyValueRow( + label = stringResource(R.string.dexcom_oneplus_staging_readings_label), + value = (stagingEvidence?.validCount ?: 0).toString(), + ) + val lastValue = stagingEvidence?.lastValueMgdl + val lastAt = stagingEvidence?.lastValueAtEpochMs + if (lastValue != null && lastAt != null) { + CgmKeyValueRow( + label = stringResource(R.string.dexcom_oneplus_staging_last_label), + value = stringResource( + R.string.dexcom_oneplus_staging_last_reading, + formatGlucose(lastValue), + formatTime(lastAt), + ), + ) + } else { + Text( + text = stringResource(R.string.dexcom_oneplus_staging_no_reading_yet), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (stagingState == StagingState.READY) { + Button( + onClick = { onPromoteClick(false) }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.dexcom_oneplus_staging_promote)) + } + } else if (earlyPromoteOffered) { + // Way out when the production sensor stops before the soak ends. Deliberately an + // outlined button with its own warning dialog: it gives up sensor quality, so it + // must never look like the normal path. + Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.small)) { + OutlinedButton( + onClick = { onPromoteClick(true) }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.dexcom_oneplus_staging_promote_early)) + } + Text( + text = stringResource(R.string.dexcom_oneplus_staging_promote_early_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + TextButton(onClick = onCancelStaging, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.dexcom_oneplus_staging_cancel)) + } + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusWarmupActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusWarmupActivity.kt new file mode 100644 index 000000000000..d18e4d6273e4 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusWarmupActivity.kt @@ -0,0 +1,74 @@ +package app.aaps.plugins.source.activities + +import android.content.Intent +import android.os.Bundle +import androidx.activity.compose.setContent +import androidx.compose.runtime.CompositionLocalProvider +import app.aaps.core.interfaces.source.SensorSlot +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.AapsTheme +import app.aaps.core.ui.compose.LocalPreferences +import app.aaps.core.ui.compose.MetroAppCompatActivity +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.setContext +import app.aaps.plugins.source.compose.DexcomOnePlusWarmupScreen +import dev.zacsweers.metro.Inject +import java.text.DateFormat +import java.util.Date + +/** + * The Android window around the warm-up screen, [DexcomOnePlusWarmupScreen]. + * + * What stays here is what needs Android: the driver log screen, the start and status Activities to + * open, the `Context` the driver and the slot store need, and the phone's own time format. + */ +class DexcomOnePlusWarmupActivity : MetroAppCompatActivity() { + + @Inject lateinit var preferences: Preferences + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Other apps may not draw over this screen: an overlay could hide what a tap really does, here on a + // sensor (start, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. + window.setHideOverlayWindows(true) + setContent { + CompositionLocalProvider(LocalPreferences provides preferences) { + AapsTheme { + DexcomOnePlusWarmupScreen( + storedSession = { + OnePlusSensorStore( + applicationContext, + OnePlusCgmDrivers.storeNamespace(SensorSlot.PRODUCTION), + ).load() + }, + onBack = { finish() }, + onRetry = { + val driver = OnePlusCgmDrivers.default() + driver.setContext(applicationContext) + (driver as? OnePlusCgmDriverReal)?.resumeStoredSession() + }, + onOpenLog = { + startActivity( + Intent(this, CgmDriverLogActivity::class.java) + ) + }, + onOpenStart = { + startActivity(Intent(this, DexcomOnePlusStartActivity::class.java)) + }, + onOpenStatus = { + // CLEAR_TOP so coming here from the status screen returns to that + // instance instead of stacking a second one on every round trip. + startActivity( + Intent(this, DexcomOnePlusStatusActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) + ) + }, + formatTime = { epochMs -> DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(epochMs)) }, + ) + } + } + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.android.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.android.kt new file mode 100644 index 000000000000..9e442bd093b9 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.android.kt @@ -0,0 +1,13 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp + +/** The device configuration, which is what these screens have always read. */ +@Composable +actual fun cgmWindowSizeDp(): DpSize { + val configuration = LocalConfiguration.current + return DpSize(configuration.screenWidthDp.dp, configuration.screenHeightDp.dp) +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt new file mode 100644 index 000000000000..299d74d3282d --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt @@ -0,0 +1,71 @@ +package app.aaps.plugins.source.compose + +import app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvCandidate +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanResult + +/** + * The decisions the sensor start screen makes, written as plain functions. + * + * They used to be expressions inside the composable, where nothing could run them. They are the + * same expressions, moved out, so a test can say what the screen shows for a given state. + */ +object DexcomOnePlusStartRules { + + /** Step 1 of the guided flow: let the app use Bluetooth. */ + const val STEP_PREPARE = 0 + + /** Step 2: type or scan the four digit pairing code from the applicator. */ + const val STEP_CODE = 1 + + /** Step 3: pick the sensor out of what the scan heard. */ + const val STEP_CONNECT = 2 + + /** Step 4: the sensor is adopted and warm-up starts. */ + const val STEP_WARMUP = 3 + + /** + * How far along the guided flow the user is. + * + * The order is what makes it a flow: a missing permission is shown even when a code has already + * been typed, because nothing can be scanned until it is granted. + */ + fun currentStep(hasPermissions: Boolean, hasCode: Boolean, hasDevice: Boolean): Int = when { + !hasPermissions -> STEP_PREPARE + !hasCode -> STEP_CODE + !hasDevice -> STEP_CONNECT + else -> STEP_WARMUP + } + + /** + * The scan list in the order the screen draws it: the sensor the code on screen points at + * first, then by how well each hit matches, then by signal. + */ + fun rank(devices: List, hint: OnePlusStoredSession?): List = + devices.sortedByDescending { OnePlusAdvCandidate.rankScore(it.name, it.address, it.rssi, hint) } + + /** + * Signal strength as bars. + * + * "−67 dBm" is a number the user cannot act on; four bars say "close enough" or "walk nearer" + * immediately. The dBm value stays in the driver log for anyone debugging a range problem. + * + * Zero bars is the stored sensor offered without a live sighting, which carries no rssi at all. + */ + fun signalBars(rssi: Int): Int = when { + rssi == 0 -> 0 + rssi >= -60 -> 4 + rssi >= -70 -> 3 + rssi >= -80 -> 2 + else -> 1 + } + + /** + * True when Connect would point the slot at a different transmitter than the one it holds. + * + * The pairing code is per sensor, so adopting another transmitter with the code of the previous + * one cannot work. The screen asks once before it overwrites the slot. + */ + fun adoptsAnotherSensor(storedMac: String?, address: String): Boolean = + storedMac != null && !storedMac.equals(address, ignoreCase = true) +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt new file mode 100644 index 000000000000..8b8482826d56 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt @@ -0,0 +1,896 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +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.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.State +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import app.aaps.core.interfaces.source.SensorSlot +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.clearFocusOnTap +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvCandidate +import app.aaps.plugins.dexcomoneplus.identity.OnePlusGs1ApplicatorParser +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanResult +import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanSelection +import app.aaps.plugins.dexcomoneplus.session.OnePlusSessionStart +import app.aaps.plugins.source.DexcomOnePlusHost +import app.aaps.plugins.source.SourceStrings +import kotlinx.coroutines.launch + +/** + * Sensor start: BLE permissions, LE scan (DX02/FEBC), applicator GS1 / PIN, connect → warm-up. + * + * Everything the phone itself owns - the key-value file of a slot, the LE scanner, the Bluetooth + * permission - arrives through [DexcomOnePlusHost] and [permissions], so the screen can be tested + * without an Activity. + * + * @param host the phone this screen runs on. + * @param permissions the Bluetooth permission gate of that phone. + * @param onStagingDriver the pre-soak driver, or **null** when there is no second sensor slot. + * Null is what makes the slot chooser absent rather than present and broken. + */ +@Composable +fun DexcomOnePlusStartScreen( + host: DexcomOnePlusHost, + permissions: OnePlusBlePermissionGate, + onBack: () -> Unit, + onEnsureDriver: () -> OnePlusCgmDriver, + onActivatePlugin: () -> Unit, + onStarted: (SensorSlot) -> Unit, + /** STAGING only: the user started this sensor now — anchors the pre-soak clock on its MAC. */ + onBeginStaging: (String) -> Boolean, + /** True when that address is the sensor the pre-soak slot holds. */ + onIsStagingSensor: (String) -> Boolean, + onCancelStaging: () -> Unit, + onOpenPromote: () -> Unit, + onStagingDriver: (() -> OnePlusCgmDriverReal)?, + /** + * PRODUCTION only: the user started this sensor now → anchor its age and log a sensor change. + * Called with (MAC of the started sensor, MAC stored before this start). + */ + onSensorSessionStarted: (String, String?) -> Unit, +) { + val window = rememberCgmWindow() + val scope = rememberCoroutineScope() + // Which slot the guided flow starts. PRODUCTION keeps the existing behaviour (activates the + // plugin + feeds the loop after warm-up). STAGING pre-soaks a second sensor collect-only — it + // never touches the AAPS active BG source until promoted from the status screen. + var slot by remember { mutableStateOf(SensorSlot.PRODUCTION) } + // EVERY store read below follows the selected slot. Reading the production store while starting a + // STAGING sensor pre-filled the old sensor's code and MAC and ranked the scan with the old + // sensor's fingerprint, so a pre-soak silently re-adopted the sensor already in use (seen in a + // field log: both slots connecting to the same MAC). + val sensorStore = remember(slot) { host.slotStore(OnePlusCgmDrivers.storeNamespace(slot)) } + val storedSession = remember(slot) { sensorStore.load() } + val scanner = remember { host.screenScanner() } + val focusManager = LocalFocusManager.current + + var applicatorInput by remember { mutableStateOf("") } + var parsedIdentity by remember { mutableStateOf(null) } + var errorText by remember { mutableStateOf(null) } + var scanning by remember { mutableStateOf(false) } + var selected by remember { mutableStateOf(null) } + /** The user tapped a sensor in the scan list — auto-select must not overrule that choice. */ + var deviceChosenByUser by remember { mutableStateOf(false) } + val devices = remember { mutableStateListOf() } + // The applicator field is pre-filled with the *stored* sensor's code. Picking a different MAC + // while leaving that code untouched pairs a NEW transmitter with the OLD sensor's PIN: auth + // fails and the slot keeps a session start that is not this sensor's. Warn once, then let the + // user proceed (a re-typed identical code is legitimate, if unlikely). + var newSensorConfirmPending by remember { mutableStateOf(false) } + /** Set when Connect targets the sensor the pre-soak slot is already running — see the dialog. */ + var slotConflictAddress by remember { mutableStateOf(null) } + + // Re-seed the whole form from the slot's own store, on first composition and on every slot + // switch, so what is shown always belongs to the sensor being started. + // + // The selection is not seeded here: it follows the code on screen, in the effect below. + LaunchedEffect(slot) { + applicatorInput = storedSession?.identity?.rawGs1 ?: storedSession?.identity?.pin.orEmpty() + parsedIdentity = storedSession?.identity ?: OnePlusGs1ApplicatorParser.parse(applicatorInput) + selected = null + deviceChosenByUser = false + devices.clear() + errorText = null + newSensorConfirmPending = false + } + + // Rank this scan from the identity ON SCREEN, not from the store. As soon as the code belongs to + // another sensor, the stored MAC and ADV name lose their boost — see OnePlusAdvCandidate. + val scanHint = remember(storedSession, parsedIdentity) { + OnePlusAdvCandidate.scanHintFor(storedSession, parsedIdentity) + } + // What the scan callback below has to read: the hint as it is NOW, not the one captured when the + // callback was built. The user may type another code while the scan runs. + val liveScanHint: State = rememberUpdatedState(scanHint) + // The selection follows the code: the stored sensor stays pre-selected while its own code is on + // screen (a reconnect needs no choosing), and the moment the code becomes another sensor's the + // pre-selection goes, because from there on only the user knows which transmitter is theirs. + LaunchedEffect(scanHint) { + scanner.updateSessionHint(scanHint) + if (!deviceChosenByUser) { + selected = OnePlusScanSelection.autoSelect(devices, scanHint) + } + } + + val codeRequired = stringResource(SourceStrings.dexcom_oneplus_pairing_code_required) + val codeInvalid = stringResource(SourceStrings.dexcom_oneplus_pairing_code_invalid) + val permissionsNeeded = stringResource(SourceStrings.dexcom_oneplus_permissions_needed) + val deviceRequired = stringResource(SourceStrings.dexcom_oneplus_device_required) + val serialNone = stringResource(SourceStrings.dexcom_oneplus_applicator_serial_none) + val newSensorCodeWarning = stringResource(SourceStrings.dexcom_oneplus_new_sensor_code_warning) + val stagingIsProduction = stringResource(SourceStrings.dexcom_oneplus_staging_is_production) + var connectRequested by remember { mutableStateOf(false) } + + // Guided-flow progress for the stepper: Prepare → Code → Connect → Warm-up. + val hasPermissions = permissions.granted() + val hasDevice = selected != null + val currentStep = DexcomOnePlusStartRules.currentStep( + hasPermissions = hasPermissions, + hasCode = parsedIdentity != null, + hasDevice = hasDevice, + ) + + DisposableEffect(Unit) { + onDispose { + // Do not stopScan after Connect — this screen's dispose races Warmup navigation and + // was killing the driver's pre-connect LE scan on the shared scanner (ADV miss). + if (!connectRequested) { + scanner.stopScan() + } + } + } + + // Connect is the step that actually adopts the selected sensor (writes its MAC/PIN into the slot + // store and starts the session). It is pinned in the Scaffold bottom bar: as a last child of a + // non-scrolling Column it was pushed off-screen as soon as the scan list filled up, leaving the + // user with a selected device and no way to validate it — and the slot store still holding the + // PREVIOUS sensor's MAC. + val onConnectClick: () -> Unit = onConnectClick@{ + val identity = parsedIdentity + ?: OnePlusGs1ApplicatorParser.parse(applicatorInput) + if (identity == null) { + errorText = codeRequired + return@onConnectClick + } + val code = OnePlusSessionStart.normalizePairingCode(identity.pin) + if (!OnePlusSessionStart.isValidPairingCode(code)) { + errorText = codeInvalid + return@onConnectClick + } + if (!permissions.granted()) { + errorText = permissionsNeeded + permissions.request() + return@onConnectClick + } + val address = selected?.address + if (address.isNullOrBlank()) { + errorText = deviceRequired + return@onConnectClick + } + scanner.stopScan() + scanning = false + connectRequested = true + // Hand off the freshest live sighting (carries seenElapsedMs) so the driver + // connects in-window instead of blindly re-scanning. + // + // Only a sighting that was really heard is handed over. The pre-selection may be a stored + // entry the scan never confirmed; passing that pretends an advertisement arrived, which both + // misses the driver's fast path anyway and talks it out of requiring an ADV. null is the + // honest answer, and the driver then scans for the sensor itself. + val sighting = devices.firstOrNull { it.address == address } + ?: selected?.takeIf { it.seenElapsedMs > 0L } + if (slot == SensorSlot.STAGING) { + // Staging: collect-only. Never write the production store, never activate the + // plugin, never switch the AAPS active BG source — just drive scan/connect on + // the dedicated staging driver and return to the overview. + // + // Soaking the sensor that already feeds the loop would put two KEKS handshakes on one + // link and break both. The plugin refuses it too; this is the message the user reads. + if (!onBeginStaging(address)) { + errorText = stagingIsProduction + return@onConnectClick + } + // Not null here: the STAGING slot can only be chosen when the chooser is drawn, and the + // chooser is drawn only when this phone has a pre-soak driver. + val stagingDriverFactory = checkNotNull(onStagingDriver) { "STAGING chosen on a one slot phone" } + val stagingDriver = stagingDriverFactory() + host.attachPlatform(stagingDriver) + stagingDriver.saveIdentity(identity.copy(pin = code)) + stagingDriver.connect( + deviceAddress = address, + pairingCode = code, + sighting = sighting, + ) + onStarted(SensorSlot.STAGING) + return@onConnectClick + } + // Production start on the sensor that is soaking in the other slot: the same collision, from + // the other side. Ask rather than act — cancelling the pre-soak silently would throw away a + // soak clock that is often many hours old, and promoting is usually what the user wants. + if (onIsStagingSensor(address)) { + slotConflictAddress = address + return@onConnectClick + } + // Production: adopting a different transmitter with the pre-filled code of the previous one + // cannot work (the PIN is per-sensor). Ask for confirmation once before overwriting the slot. + val storedMac = storedSession?.lastMac + val adoptingAnotherSensor = DexcomOnePlusStartRules.adoptsAnotherSensor(storedMac, address) + // The safe call is only for the compiler: a non-null storedMac means a non-null session, + // and adoptingAnotherSensor is false without one. + if (adoptingAnotherSensor && storedSession?.identity?.pin == code && !newSensorConfirmPending) { + newSensorConfirmPending = true + errorText = newSensorCodeWarning + return@onConnectClick + } + sensorStore.saveIdentity(identity.copy(pin = code)) + sensorStore.saveLastMac(address) + selected?.name?.let { sensorStore.saveLastDeviceName(it) } + // Anchor the sensor age on this explicit start (overview sensor age / SENSOR_CHANGE). After + // saveIdentity, which drops the stored start when the serial shows another sensor. storedMac + // is the MAC read at screen entry, so it still describes the sensor that was running. + onSensorSessionStarted(address, storedMac) + val activeDriver = onEnsureDriver() + host.attachPlatform(activeDriver) + (activeDriver as? OnePlusCgmDriverReal)?.saveIdentity(identity.copy(pin = code)) + if (activeDriver is OnePlusCgmDriverReal) { + activeDriver.connect( + deviceAddress = address, + pairingCode = code, + sighting = sighting, + ) + } else { + activeDriver.connect(deviceAddress = address, pairingCode = code) + } + onActivatePlugin() + onStarted(SensorSlot.PRODUCTION) + } + + val onStartScan: () -> Unit = onStartScan@{ + if (!permissions.granted()) { + errorText = permissionsNeeded + permissions.request() + return@onStartScan + } + devices.clear() + deviceChosenByUser = false + scanner.updateSessionHint(scanHint) + selected = OnePlusScanSelection.autoSelect(devices, scanHint) + scanner.startScan { hit -> + // The scanner answers on its own thread (a binder thread). This scope belongs to the + // composition, so the list below is only ever + // touched on the UI thread, and a hit that arrives after the screen is gone is dropped + // rather than written into a composition that no longer exists. + scope.launch { + val idx = devices.indexOfFirst { it.address == hit.address } + if (idx >= 0) devices[idx] = hit else devices.add(hit) + // The live hint, not the one captured when this lambda was built: the user may type + // another code while the scan runs. One sensor in range may be selected for them, + // two or more may not. This is an assignment on purpose — when a second sensor turns + // up, the single-hit suggestion has to go, and Connect goes with it. + if (!deviceChosenByUser) { + selected = OnePlusScanSelection.autoSelect(devices, liveScanHint.value) + } + } + } + scanning = true + errorText = null + } + + val onStopScan: () -> Unit = { + scanner.stopScan() + scanning = false + } + + val onDeviceClick: (OnePlusScanResult) -> Unit = { device -> + selected = device + deviceChosenByUser = true + errorText = null + newSensorConfirmPending = false + } + + val rankedDevices = DexcomOnePlusStartRules.rank(devices, scanHint) + val connectAction: @Composable ColumnScope.() -> Unit = { + ConnectAction( + slot = slot, + errorText = errorText, + selectedLabel = selected?.name ?: selected?.address, + enabled = hasDevice, + onConnectClick = onConnectClick, + ) + } + + CgmScaffold( + title = stringResource(SourceStrings.dexcom_oneplus_start_title), + onNavigate = onBack, + // A screen the user either commits (Connect) or abandons — see the AapsTopAppBar convention. + navIcon = CgmNavIcon.Close, + constrainWidth = !window.isTwoPane, + bottomBar = { + // In two panes the action lives at the foot of the form column, next to what it acts on. + if (!window.isTwoPane) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(AapsSpacing.extraLarge), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + content = connectAction, + ) + } + }, + ) { + if (window.isTwoPane) { + Row( + modifier = Modifier + .fillMaxSize() + .clearFocusOnTap(focusManager), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.extraLarge), + ) { + Column( + // Both panes share the width. A fixed 560 dp form would have left the sensor + // list about 250 dp at the 840 dp split point — narrower than one row needs. + modifier = Modifier + .weight(1f) + .widthIn(max = CgmSpacing.readableContentMaxWidth) + .fillMaxHeight() + .verticalScroll(rememberScrollState()) + .padding(AapsSpacing.extraLarge), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + ) { + FormPane( + window = window, + currentStep = currentStep, + slot = slot, + onSlotChange = { slot = it; errorText = null }, + slotChoiceOffered = onStagingDriver != null, + permissions = permissions, + applicatorInput = applicatorInput, + parsedIdentity = parsedIdentity, + errorText = errorText, + serialNone = serialNone, + storedMac = storedSession?.lastMac, + onApplicatorChange = { text -> + applicatorInput = text + parsedIdentity = OnePlusGs1ApplicatorParser.parse(text) + errorText = null + newSensorConfirmPending = false + }, + ) + connectAction() + } + Column( + modifier = Modifier + .weight(1f) + .fillMaxHeight() + .padding( + top = AapsSpacing.extraLarge, + end = AapsSpacing.extraLarge, + bottom = AapsSpacing.extraLarge, + ), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + ) { + ScanHeader( + scanning = scanning, + deviceCount = devices.size, + onStartScan = onStartScan, + onStopScan = onStopScan, + ) + // Its own pane, so the list gets the whole height instead of a fixed 216 dp box. + CgmLazyColumn( + modifier = Modifier.weight(1f), + contentPadding = PaddingValues(0.dp), + ) { + deviceItems( + devices = rankedDevices, + selectedAddress = selected?.address, + storedMac = storedSession?.lastMac, + onDeviceClick = onDeviceClick, + ) + } + } + } + } else { + CgmLazyColumn( + modifier = Modifier.clearFocusOnTap(focusManager), + ) { + item(key = "form") { + Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.large)) { + FormPane( + window = window, + currentStep = currentStep, + slot = slot, + onSlotChange = { slot = it; errorText = null }, + slotChoiceOffered = onStagingDriver != null, + permissions = permissions, + applicatorInput = applicatorInput, + parsedIdentity = parsedIdentity, + errorText = errorText, + serialNone = serialNone, + storedMac = storedSession?.lastMac, + onApplicatorChange = { text -> + applicatorInput = text + parsedIdentity = OnePlusGs1ApplicatorParser.parse(text) + errorText = null + newSensorConfirmPending = false + }, + ) + } + } + item(key = "scanHeader") { + ScanHeader( + scanning = scanning, + deviceCount = devices.size, + onStartScan = onStartScan, + onStopScan = onStopScan, + ) + } + // The scanned sensors are items of the screen's own list. Wrapping them in a list + // with its own bounded height was what pinned them to 216 dp on every screen size. + deviceItems( + devices = rankedDevices, + selectedAddress = selected?.address, + storedMac = storedSession?.lastMac, + onDeviceClick = onDeviceClick, + ) + item(key = "help") { + Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.large)) { + HelpSection(slot = slot, slotChoiceOffered = onStagingDriver != null) + } + } + } + } + } + + slotConflictAddress?.let { + SlotConflictDialog( + onPromote = { + slotConflictAddress = null + onOpenPromote() + }, + onCancelStagingAndStart = { + slotConflictAddress = null + // The soak is given up knowingly. Connect is not re-run for the user: the store has + // just changed under it, so they press it again on a screen that now tells the truth. + onCancelStaging() + errorText = null + }, + onDismiss = { slotConflictAddress = null }, + ) + } +} + +/** + * Asked when Connect targets the sensor that is soaking in the pre-soak slot. + * + * Promote is the primary action on purpose: it is what the user usually means, and it keeps the soak + * the sensor has already earned. Cancelling throws that away, so it is the quieter choice, and it + * says so. + */ +@Composable +private fun SlotConflictDialog( + onPromote: () -> Unit, + onCancelStagingAndStart: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(SourceStrings.dexcom_oneplus_slot_conflict_title)) }, + text = { Text(stringResource(SourceStrings.dexcom_oneplus_slot_conflict_message)) }, + confirmButton = { + TextButton(onClick = onPromote) { + Text(stringResource(SourceStrings.dexcom_oneplus_slot_conflict_promote)) + } + }, + dismissButton = { + Row { + TextButton(onClick = onDismiss) { + Text(stringResource(SourceStrings.dexcom_oneplus_slot_conflict_dismiss)) + } + TextButton(onClick = onCancelStagingAndStart) { + Text(stringResource(SourceStrings.dexcom_oneplus_slot_conflict_restart)) + } + } + }, + ) +} + +/** The stepper, slot choice, permission prompt, code field and help — everything but the scan. */ +@Composable +private fun ColumnScope.FormPane( + window: CgmWindow, + currentStep: Int, + slot: SensorSlot, + onSlotChange: (SensorSlot) -> Unit, + slotChoiceOffered: Boolean, + permissions: OnePlusBlePermissionGate, + applicatorInput: String, + parsedIdentity: OnePlusSensorIdentity?, + errorText: String?, + serialNone: String, + storedMac: String?, + onApplicatorChange: (String) -> Unit, +) { + CgmStepper( + currentStep = currentStep, + labels = listOf( + stringResource(SourceStrings.dexcom_oneplus_step_prepare), + stringResource(SourceStrings.dexcom_oneplus_step_code), + stringResource(SourceStrings.dexcom_oneplus_step_connect), + stringResource(SourceStrings.dexcom_oneplus_step_warmup), + ), + // Four labels never fit across a phone; the compact form shows one at a time instead of + // truncating all of them. + compact = window.width == CgmWidth.Compact, + ) + + // A real single-choice control: the selected side carries the selection state, so TalkBack + // announces a choice instead of two buttons, one of which used to do nothing at all. + // + // Left out entirely on a phone with one sensor slot. A disabled second button would read as + // "pre-soak is off just now"; absent reads as "this phone does not do that", which is the truth. + if (slotChoiceOffered) { + SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) { + SegmentedButton( + selected = slot == SensorSlot.PRODUCTION, + onClick = { onSlotChange(SensorSlot.PRODUCTION) }, + shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2), + ) { + Text(stringResource(SourceStrings.dexcom_oneplus_slot_production_short)) + } + SegmentedButton( + selected = slot == SensorSlot.STAGING, + onClick = { onSlotChange(SensorSlot.STAGING) }, + shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2), + ) { + Text(stringResource(SourceStrings.dexcom_oneplus_slot_staging_short)) + } + } + } + + if (!permissions.granted()) { + Button( + onClick = { permissions.request() }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(SourceStrings.dexcom_oneplus_request_permissions)) + } + } + + CgmCard { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_section_pairing_code)) + OutlinedTextField( + value = applicatorInput, + onValueChange = onApplicatorChange, + modifier = Modifier.fillMaxWidth(), + label = { Text(stringResource(SourceStrings.dexcom_oneplus_applicator_gs1_label)) }, + supportingText = { + if (parsedIdentity != null) { + Text( + stringResource( + SourceStrings.dexcom_oneplus_applicator_parsed, + parsedIdentity.pin, + parsedIdentity.serial ?: serialNone, + ), + ) + } else { + Text(stringResource(SourceStrings.dexcom_oneplus_applicator_gs1_hint)) + } + }, + singleLine = false, + minLines = 2, + isError = errorText != null && parsedIdentity == null, + ) + storedMac?.let { mac -> + Text( + text = stringResource(SourceStrings.dexcom_oneplus_last_mac_hint, mac), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + if (window.isTwoPane) HelpSection(slot = slot, slotChoiceOffered = slotChoiceOffered) +} + +/** + * The five help blocks that used to sit permanently open above the first control — about two + * screens of scrolling before the user could reach Scan. Folded away, but the one that warns about + * losing the Dexcom app keeps its warning colour while closed. + */ +@Composable +private fun ColumnScope.HelpSection(slot: SensorSlot, slotChoiceOffered: Boolean) { + CgmHelpCard(title = stringResource(SourceStrings.dexcom_oneplus_help_how_to_start)) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_start_steps), + style = MaterialTheme.typography.bodyMedium, + ) + } + CgmHelpCard( + title = stringResource(SourceStrings.dexcom_oneplus_help_before_pairing), + tone = CgmCardTone.Warning, + ) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_dexcom_recovery_warning), + style = MaterialTheme.typography.bodyMedium, + ) + } + CgmHelpCard(title = stringResource(SourceStrings.dexcom_oneplus_help_permissions)) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_permissions_hint), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = stringResource(SourceStrings.dexcom_oneplus_scan_hint), + style = MaterialTheme.typography.bodyMedium, + ) + } + // Nothing to explain about slots on a phone that has only one. + if (slotChoiceOffered) { + CgmHelpCard(title = stringResource(SourceStrings.dexcom_oneplus_help_slot)) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_slot_hint), + style = MaterialTheme.typography.bodyMedium, + ) + } + } +} + +@Composable +private fun ScanHeader( + scanning: Boolean, + deviceCount: Int, + onStartScan: () -> Unit, + onStopScan: () -> Unit, +) { + Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium)) { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_section_sensors_nearby)) { + CgmStateChip( + state = if (scanning) CgmUiState.Working else CgmUiState.Waiting, + label = if (scanning) { + stringResource(SourceStrings.dexcom_oneplus_scan_scanning) + } else { + stringResource(SourceStrings.dexcom_oneplus_scan_idle, deviceCount) + }, + ) + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + ) { + OutlinedButton( + onClick = onStartScan, + modifier = Modifier.weight(1f), + enabled = !scanning, + ) { + Text( + stringResource( + if (deviceCount > 0) { + SourceStrings.dexcom_oneplus_scan_rescan + } else { + SourceStrings.dexcom_oneplus_scan_start + }, + ), + ) + } + OutlinedButton( + onClick = onStopScan, + modifier = Modifier.weight(1f), + enabled = scanning, + ) { + Text(stringResource(SourceStrings.dexcom_oneplus_scan_stop)) + } + } + // Why every nearby sensor is listed, and why the app cannot choose for the user. + Text( + text = stringResource(SourceStrings.dexcom_oneplus_scan_pick_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** Scanned sensors as items of the caller's list — never a bounded list inside another scroll. */ +private fun LazyListScope.deviceItems( + devices: List, + selectedAddress: String?, + storedMac: String?, + onDeviceClick: (OnePlusScanResult) -> Unit, +) { + if (devices.isEmpty()) { + item(key = "scanEmpty") { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_scan_empty), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } else { + items(devices, key = { it.address }) { device -> + DeviceRow( + device = device, + selected = selectedAddress == device.address, + lastUsed = storedMac?.equals(device.address, ignoreCase = true) == true, + onClick = { onDeviceClick(device) }, + ) + } + } +} + +@Composable +private fun DeviceRow( + device: OnePlusScanResult, + selected: Boolean, + lastUsed: Boolean, + onClick: () -> Unit, +) { + val shape = RoundedCornerShape(AapsSpacing.large) + Row( + modifier = Modifier + .fillMaxWidth() + .heightIn(min = CgmSpacing.listRowMinHeight) + .background( + color = if (selected) { + MaterialTheme.colorScheme.secondaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerLow + }, + shape = shape, + ) + .border( + width = if (selected) 2.dp else 1.dp, + color = if (selected) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.outlineVariant + }, + shape = shape, + ) + .clickable(onClick = onClick) + .padding(horizontal = AapsSpacing.extraLarge, vertical = AapsSpacing.large), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = device.name ?: stringResource(SourceStrings.dexcom_oneplus_scan_unnamed), + style = MaterialTheme.typography.bodyLarge, + ) + Text( + text = device.address, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + if (lastUsed) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_scan_last_used), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary, + ) + } + } + SignalBars(rssi = device.rssi) + } +} + +/** Signal strength as bars - see [DexcomOnePlusStartRules.signalBars] for why bars and not dBm. */ +@Composable +private fun SignalBars(rssi: Int) { + val bars = DexcomOnePlusStartRules.signalBars(rssi) + // The bars are decorative; the dBm value they stand for is what gets read out, so nothing is + // lost for screen reader users. + val description = stringResource(SourceStrings.dexcom_oneplus_scan_signal, rssi) + Row( + modifier = Modifier.semantics { contentDescription = description }, + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.extraSmall), + verticalAlignment = Alignment.Bottom, + ) { + (1..4).forEach { index -> + Box( + modifier = Modifier + .width(AapsSpacing.small) + .height(AapsSpacing.small * (index + 1)) + .background( + color = if (index <= bars) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.surfaceVariant + }, + shape = RoundedCornerShape(AapsSpacing.extraSmall), + ), + ) + } + } +} + +@Composable +private fun ColumnScope.ConnectAction( + slot: SensorSlot, + errorText: String?, + selectedLabel: String?, + enabled: Boolean, + onConnectClick: () -> Unit, +) { + errorText?.let { msg -> + Text( + text = msg, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + ) + } + // Connect overwrites the slot's stored MAC, so the screen says which sensor it is about to + // adopt rather than leaving the user to check the highlighted row. + Text( + text = when { + slot == SensorSlot.STAGING -> stringResource(SourceStrings.dexcom_oneplus_staging_return_note) + selectedLabel != null -> stringResource(SourceStrings.dexcom_oneplus_connect_target, selectedLabel) + else -> stringResource(SourceStrings.dexcom_oneplus_start_return_warmup) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Button( + onClick = onConnectClick, + modifier = Modifier.fillMaxWidth(), + // Selecting a device is what the button acts on: disabled until there is one, so + // "nothing happens" is never mistaken for a broken button. + enabled = enabled, + ) { + Text( + if (slot == SensorSlot.STAGING) { + stringResource(SourceStrings.dexcom_oneplus_staging_connect) + } else { + stringResource(SourceStrings.dexcom_oneplus_connect_follow) + }, + ) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt new file mode 100644 index 000000000000..c00383454f5c --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt @@ -0,0 +1,75 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.SourceStrings + +/** + * The card for the sensor that feeds the loop. + * + * Accented so it is never confused with the pre-soak card. [extra] is for the actions below the + * facts - the "correct insertion date" action of the status screen. + */ +@Composable +fun DexcomOnePlusProductionCard( + phaseLabel: String, + phaseState: CgmUiState, + sessionUp: Boolean, + message: String, + lifecycle: CgmSensorLifecycle?, + newestGlucose: GV?, + formatGlucose: (Double) -> String, + formatTime: (Long) -> String, + formatAge: (Long) -> String, + extra: @Composable ColumnScope.() -> Unit = {}, +) { + CgmCard(accent = true) { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_production_heading)) { + CgmStateChip(state = phaseState, label = phaseLabel) + } + // Only this driver's own readings are shown here: the newest value in the database can come + // from another source, and labelling someone else's reading as this sensor's would be a lie. + val ownReading = newestGlucose?.takeIf { it.sourceSensor == SourceSensor.DEXCOM_ONEPLUS_NATIVE } + if (ownReading != null) { + Text( + text = stringResource( + SourceStrings.dexcom_oneplus_staging_last_reading, + formatGlucose(ownReading.value), + formatTime(ownReading.timestamp), + ), + style = MaterialTheme.typography.titleMedium, + ) + } else { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_production_no_reading), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + CgmKeyValueRow( + label = stringResource(SourceStrings.cgm_session_label), + value = stringResource( + if (sessionUp) SourceStrings.dexcom_oneplus_session_up else SourceStrings.dexcom_oneplus_session_down, + ), + ) + lifecycle?.ageMs?.let { age -> + Text( + text = stringResource(SourceStrings.dexcom_oneplus_sensor_age, formatAge(age)), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Text( + text = message, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + extra() + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt new file mode 100644 index 000000000000..3e664cba045f --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt @@ -0,0 +1,52 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.runtime.Composable +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.source.SourceStrings + +/** + * Localized labels for ONE+ Status / Warm-up screens. + * Driver [OnePlusWarmupState.message] codes stay English for logcat; UI maps them here. + */ +object DexcomOnePlusUiLabels { + + @Composable + fun phaseLabel(phase: OnePlusWarmupState.Phase): String = when (phase) { + OnePlusWarmupState.Phase.IDLE -> stringResource(SourceStrings.dexcom_oneplus_phase_idle) + OnePlusWarmupState.Phase.PAIRING -> stringResource(SourceStrings.dexcom_oneplus_phase_pairing) + OnePlusWarmupState.Phase.CONNECTING -> stringResource(SourceStrings.dexcom_oneplus_phase_connecting) + OnePlusWarmupState.Phase.RECONNECTING -> stringResource(SourceStrings.dexcom_oneplus_phase_reconnecting) + OnePlusWarmupState.Phase.WARMING -> stringResource(SourceStrings.dexcom_oneplus_phase_warming) + OnePlusWarmupState.Phase.READY -> stringResource(SourceStrings.dexcom_oneplus_phase_ready) + OnePlusWarmupState.Phase.FAILED -> stringResource(SourceStrings.dexcom_oneplus_phase_failed) + } + + /** + * Maps driver/log message codes to user-facing copy. Unknown technical codes are not shown raw. + */ + @Composable + fun userMessage(raw: String?): String { + if (raw.isNullOrBlank()) { + return stringResource(SourceStrings.dexcom_oneplus_status_message_none) + } + return when { + raw == "pairing" || raw.startsWith("pairing_attempt_") -> + stringResource(SourceStrings.dexcom_oneplus_msg_pairing) + raw == "auth_ok" -> + stringResource(SourceStrings.dexcom_oneplus_msg_auth_ok) + raw == "tx_time_session" -> + stringResource(SourceStrings.dexcom_oneplus_msg_tx_session) + raw == "egv_loop_exit" || raw == "disconnect" || raw == "shutdown" || raw == "cancelled" -> + stringResource(SourceStrings.dexcom_oneplus_msg_session_down) + raw.startsWith("ONEPLUS_AUTH") || raw.contains("bond", ignoreCase = true) -> + stringResource(SourceStrings.dexcom_oneplus_error_auth_bond) + raw.startsWith("ONEPLUS_GATT") || raw.startsWith("ONEPLUS_EGV") || + raw.startsWith("ONEPLUS_CONTROL") || raw.startsWith("ONEPLUS_SESSION") || + raw.startsWith("ONEPLUS_RECONNECT") || raw.startsWith("ONEPLUS_BACKFILL") || + raw.startsWith("ONEPLUS_TIME") || raw.startsWith("ONEPLUS_PAIR") -> + stringResource(SourceStrings.dexcom_oneplus_error_connection) + else -> stringResource(SourceStrings.dexcom_oneplus_status_message_generic) + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupScreen.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupScreen.kt new file mode 100644 index 000000000000..58a550d6d85a --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupScreen.kt @@ -0,0 +1,443 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +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.text.style.TextAlign +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.source.SourceStrings +import kotlinx.coroutines.delay +import kotlin.time.Clock + +/** + * Warm-up countdown screen bound to [OnePlusWarmupState]. + * + * Countdown source (see [DexcomOnePlusWarmupCountdown]): + * - Prefer protocol `remainingMs` / `endsAtEpochMs`. + * - Local ~30 min fallback timer ONLY when both are null and phase is WARMING. + * + * Layout follows the window: in portrait the ring is the subject of the screen and the details sit + * under it; on a short screen (phone in landscape) the ring moves beside the details, which is the + * only arrangement that fits about 360 dp of height without cutting anything off. + * + * The three ways to another screen are nullable. A phone that has no such screen passes null, and + * the button is not drawn, rather than drawn and doing nothing. + * + * @param storedSession reads the production slot's stored sensor once, for the sensor card. + * @param onRetry starts the stored session again after a failed warm-up. + * @param formatTime the time of day of an epoch millisecond value, in the phone's own format. + */ +@Composable +fun DexcomOnePlusWarmupScreen( + storedSession: () -> OnePlusStoredSession?, + onBack: () -> Unit, + onRetry: () -> Unit, + onOpenLog: (() -> Unit)?, + onOpenStart: (() -> Unit)?, + onOpenStatus: (() -> Unit)?, + formatTime: (Long) -> String, +) { + val window = rememberCgmWindow() + // Identity is read once: it only changes when a sensor is started, which leaves this screen. + val session = remember { storedSession() } + // Not `remember`-ed: a promotion swaps which driver instance `default()` hands out (see + // OnePlusCgmDrivers.promoteStagingInstance), and a `remember`-ed reference kept polling the + // retired instance for the rest of this screen's life. + var state by remember { mutableStateOf(OnePlusCgmDrivers.default().warmupState()) } + var sessionUp by remember { mutableStateOf(OnePlusCgmDrivers.default().isSessionUp()) } + var localFallbackEndsAt by remember { mutableStateOf(null) } + var remainingMs by remember { mutableStateOf(null) } + var usingLocalFallback by remember { mutableStateOf(false) } + + LaunchedEffect(Unit) { + while (true) { + val driver = OnePlusCgmDrivers.default() + val now = Clock.System.now().toEpochMilliseconds() + state = driver.warmupState() + val info = state.toCgmWarmupInfo() + sessionUp = driver.isSessionUp() + if (DexcomOnePlusWarmupCountdown.shouldStartLocalFallback(info) && localFallbackEndsAt == null) { + // Local fallback ONLY if remainingMs (and endsAt) are null — documented above. + localFallbackEndsAt = now + DexcomOnePlusWarmupCountdown.LOCAL_FALLBACK_DURATION_MS + } + if (DexcomOnePlusWarmupCountdown.shouldClearLocalFallback(info.phase)) { + localFallbackEndsAt = null + } + usingLocalFallback = + state.remainingMs == null && + state.endsAtEpochMs == null && + localFallbackEndsAt != null && + state.phase == OnePlusWarmupState.Phase.WARMING + remainingMs = DexcomOnePlusWarmupCountdown.resolveRemainingMs( + state = info, + nowEpochMs = now, + localFallbackEndsAtEpochMs = localFallbackEndsAt, + ) + delay(1_000L) + } + } + + val model = WarmupUiModel( + state = state, + sessionUp = sessionUp, + remainingMs = remainingMs, + localFallbackEndsAt = localFallbackEndsAt, + usingLocalFallback = usingLocalFallback, + ) + val links = WarmupLinks( + onRetry = onRetry, + onOpenLog = onOpenLog, + onOpenStart = onOpenStart, + onOpenStatus = onOpenStatus, + ) + + CgmScaffold( + title = stringResource(SourceStrings.dexcom_oneplus_warmup_title), + onNavigate = onBack, + actions = { + if (onOpenLog != null) { + IconButton(onClick = onOpenLog) { + Icon( + imageVector = Icons.AutoMirrored.Filled.List, + contentDescription = stringResource(SourceStrings.cgm_driver_log_open), + ) + } + } + }, + // The short layout places the ring beside the text and manages its own width. + constrainWidth = !window.isShort, + ) { + if (window.isShort) { + Row( + modifier = Modifier + .fillMaxSize() + .padding(AapsSpacing.extraLarge), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.xxLarge), + verticalAlignment = Alignment.CenterVertically, + ) { + CgmWarmupRing( + progress = ringProgress(model), + state = model.state.phase.toUiState(), + modifier = Modifier + .fillMaxHeight() + .aspectRatio(1f), + ) { + RingCenter(model) + } + Column( + modifier = Modifier + .weight(1f) + .fillMaxHeight() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + ) { + WarmupDetails( + model = model, + deviceName = session?.lastDeviceName, + deviceAddress = session?.lastMac, + compactHeadline = true, + links = links, + formatTime = formatTime, + ) + } + } + } else { + CgmLazyColumn { + item(key = "ring") { + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + ) { + StateChips(model) + // Width only: the box wraps the ring's own height, so the ring is not + // parked in the middle of a full width square of empty space. + CgmWarmupRing( + progress = ringProgress(model), + state = model.state.phase.toUiState(), + modifier = Modifier.fillMaxWidth(), + ) { + RingCenter(model) + } + } + } + item(key = "details") { + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + ) { + WarmupDetails( + model = model, + deviceName = session?.lastDeviceName, + deviceAddress = session?.lastMac, + compactHeadline = false, + links = links, + formatTime = formatTime, + ) + } + } + } + } + } +} + +/** Everything the screen shows, gathered once per tick so both layouts read the same values. */ +private data class WarmupUiModel( + val state: OnePlusWarmupState, + val sessionUp: Boolean, + val remainingMs: Long?, + val localFallbackEndsAt: Long?, + val usingLocalFallback: Boolean, +) + +/** The ways out of this screen. A null entry is a screen this phone does not have. */ +private class WarmupLinks( + val onRetry: () -> Unit, + val onOpenLog: (() -> Unit)?, + val onOpenStart: (() -> Unit)?, + val onOpenStatus: (() -> Unit)?, +) + +/** + * Determinate only when the local ~30 min fallback owns the clock, because only then is the total + * known. Otherwise a full ring signals honest, open-ended progress instead of inventing a fraction. + */ +private fun ringProgress(model: WarmupUiModel): Float? = + if (model.state.phase == OnePlusWarmupState.Phase.WARMING && model.usingLocalFallback) { + val remaining = model.remainingMs ?: 0L + (1f - remaining.toFloat() / DexcomOnePlusWarmupCountdown.LOCAL_FALLBACK_DURATION_MS) + .coerceIn(0f, 1f) + } else { + null + } + +@Composable +private fun RingCenter(model: WarmupUiModel) { + // Keep the mm:ss countdown while the link is being re-established: a normal duty-cycle + // disconnect during warm-up used to blank it until the next EGV packet. + val countdownText = model.remainingMs?.let { DexcomOnePlusWarmupCountdown.formatMmSs(it) } + val warmupClockPhase = model.state.phase == OnePlusWarmupState.Phase.WARMING || + model.state.phase == OnePlusWarmupState.Phase.IDLE || + model.state.phase == OnePlusWarmupState.Phase.PAIRING + val phase = model.state.phase.toCgmWarmupPhase() + val centerText = when { + DexcomOnePlusWarmupCountdown.showsCountdown(phase) && countdownText != null -> countdownText + warmupClockPhase -> + stringResource(SourceStrings.dexcom_oneplus_warmup_countdown_unknown) + + else -> + DexcomOnePlusUiLabels.phaseLabel(model.state.phase) + } + val showsRemainingLabel = countdownText != null && + DexcomOnePlusWarmupCountdown.showsCountdown(phase) + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(AapsSpacing.extraSmall), + ) { + Text( + text = centerText, + style = MaterialTheme.typography.headlineMedium, + color = if (model.state.phase == OnePlusWarmupState.Phase.FAILED) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurface + }, + textAlign = TextAlign.Center, + ) + if (showsRemainingLabel) { + Text( + text = stringResource(SourceStrings.cgm_warmup_remaining_label), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +@Composable +private fun StateChips(model: WarmupUiModel) { + Row(horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium)) { + CgmStateChip( + state = model.state.phase.toUiState(), + label = DexcomOnePlusUiLabels.phaseLabel(model.state.phase), + ) + CgmStateChip( + state = if (model.sessionUp) CgmUiState.Ready else CgmUiState.Waiting, + label = stringResource( + if (model.sessionUp) SourceStrings.dexcom_oneplus_session_up else SourceStrings.dexcom_oneplus_session_down, + ), + ) + } +} + +@Composable +private fun ColumnScope.WarmupDetails( + model: WarmupUiModel, + deviceName: String?, + deviceAddress: String?, + compactHeadline: Boolean, + links: WarmupLinks, + formatTime: (Long) -> String, +) { + if (compactHeadline) StateChips(model) + + // Honest end-of-warm-up annotation, from the protocol clock or the local fallback. Shown during + // the connection phases too, so the user keeps a landmark while the sensor's radio window is + // closed. + val endMs = model.state.endsAtEpochMs ?: model.localFallbackEndsAt + endMs?.let { + Text( + text = stringResource(SourceStrings.cgm_warmup_ends_at, formatTime(it)), + style = MaterialTheme.typography.titleMedium, + ) + } + + when (model.state.phase) { + OnePlusWarmupState.Phase.READY -> { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_warmup_done), + style = MaterialTheme.typography.titleMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + + OnePlusWarmupState.Phase.FAILED -> { + // An interrupted warm-up used to be a red line and nothing else. These are the three + // ways out that actually exist, in the order they are worth trying. + CgmCard(tone = CgmCardTone.Warning) { + CgmCardHeader(stringResource(SourceStrings.cgm_warmup_what_happened)) + Text( + text = DexcomOnePlusUiLabels.userMessage(model.state.message), + style = MaterialTheme.typography.bodyMedium, + ) + } + Button(onClick = links.onRetry, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(SourceStrings.dexcom_oneplus_warmup_retry)) + } + links.onOpenLog?.let { openLog -> + OutlinedButton(onClick = openLog, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(SourceStrings.cgm_driver_log_open)) + } + } + links.onOpenStart?.let { openStart -> + TextButton(onClick = openStart, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(SourceStrings.dexcom_oneplus_warmup_start_other)) + } + } + } + + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING -> { + // Link is being (re)established — reassure, don't show a fake countdown or the terminal + // red FAILED that used to flash between retries. + Text( + text = stringResource(SourceStrings.dexcom_oneplus_warmup_connecting_note), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + else -> { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_warmup_no_loop_bg), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + // Typed driver signals the old screen carried but never showed: how long the sensor has been + // silent, and whether the sensor answering nearby is not the paired one at all. + model.state.advSilenceMinutes?.let { minutes -> + Text( + text = stringResource(SourceStrings.dexcom_oneplus_notif_waiting_adv, minutes.toInt()), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (model.state.staleMacSuspected) { + CgmCard(tone = CgmCardTone.Warning) { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_notif_stale_mac_title)) + Text( + text = stringResource(SourceStrings.dexcom_oneplus_notif_stale_mac_text), + style = MaterialTheme.typography.bodyMedium, + ) + links.onOpenStart?.let { openStart -> + OutlinedButton(onClick = openStart) { + Text(stringResource(SourceStrings.dexcom_oneplus_warmup_start_other)) + } + } + } + } + + // Which sensor this countdown belongs to — a real question once a pre-soak sensor can be + // warming up at the same time. + if (deviceName != null || deviceAddress != null) { + CgmCard { + CgmCardHeader(stringResource(SourceStrings.cgm_sensor_heading)) + deviceName?.let { + CgmKeyValueRow(stringResource(SourceStrings.cgm_sensor_name), it) + } + deviceAddress?.let { + CgmKeyValueRow(stringResource(SourceStrings.cgm_sensor_address), it) + } + if (model.usingLocalFallback) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_warmup_local_fallback_note), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + + if (model.state.phase != OnePlusWarmupState.Phase.FAILED && + (links.onOpenLog != null || links.onOpenStatus != null) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + ) { + links.onOpenLog?.let { openLog -> + OutlinedButton(onClick = openLog, modifier = Modifier.weight(1f)) { + Text(stringResource(SourceStrings.cgm_driver_log_open)) + } + } + links.onOpenStatus?.let { openStatus -> + OutlinedButton(onClick = openStatus, modifier = Modifier.weight(1f)) { + Text(stringResource(SourceStrings.dexcom_oneplus_open_status)) + } + } + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusBlePermissionGate.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusBlePermissionGate.kt new file mode 100644 index 000000000000..71adb720da19 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusBlePermissionGate.kt @@ -0,0 +1,22 @@ +package app.aaps.plugins.source.compose + +/** + * Whether the phone lets this app scan for Bluetooth sensors, and how to ask. + * + * Android has a runtime permission the user grants before a scan can hear anything, and it has to + * be asked for from the Activity that is on top. The sensor start screen has no way to reach that + * Activity, so the Activity hands it one of these. + */ +interface OnePlusBlePermissionGate { + + /** True when a scan may start now. */ + fun granted(): Boolean + + /** + * Ask the user for what is still missing. + * + * The screen only calls this when [granted] said no, so an implementation never has to decide + * whether asking is needed. + */ + fun request() +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMapping.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMapping.kt new file mode 100644 index 000000000000..b55bb0863dc0 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusWarmupMapping.kt @@ -0,0 +1,27 @@ +package app.aaps.plugins.source.compose + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState + +// Maps the Dexcom ONE+ driver warm-up state onto the vendor-neutral CgmWarmupInfo. The mapping is +// one to one on every phase, so the screens and the notifications see exactly what the driver said. + +/** Dexcom ONE+ driver phase as the vendor-neutral phase. */ +fun OnePlusWarmupState.Phase.toCgmWarmupPhase(): CgmWarmupPhase = when (this) { + OnePlusWarmupState.Phase.IDLE -> CgmWarmupPhase.IDLE + OnePlusWarmupState.Phase.PAIRING -> CgmWarmupPhase.PAIRING + OnePlusWarmupState.Phase.CONNECTING -> CgmWarmupPhase.CONNECTING + OnePlusWarmupState.Phase.RECONNECTING -> CgmWarmupPhase.RECONNECTING + OnePlusWarmupState.Phase.WARMING -> CgmWarmupPhase.WARMING + OnePlusWarmupState.Phase.READY -> CgmWarmupPhase.READY + OnePlusWarmupState.Phase.FAILED -> CgmWarmupPhase.FAILED +} + +/** Dexcom ONE+ driver state as the three facts the countdown rules read. */ +fun OnePlusWarmupState.toCgmWarmupInfo(): CgmWarmupInfo = CgmWarmupInfo( + phase = phase.toCgmWarmupPhase(), + remainingMs = remainingMs, + endsAtEpochMs = endsAtEpochMs, +) + +/** Short form for the screens: a Dexcom ONE+ phase straight to what it means for the user. */ +fun OnePlusWarmupState.Phase.toUiState(): CgmUiState = toCgmWarmupPhase().toUiState() diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMemberInjectors.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMemberInjectors.kt new file mode 100644 index 000000000000..047bc0b8aca2 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/SourceMemberInjectors.kt @@ -0,0 +1,57 @@ +package app.aaps.plugins.source.di + +import app.aaps.core.interfaces.di.FeatureMemberInjectors +import app.aaps.plugins.source.activities.CgmDriverLogActivity +import app.aaps.plugins.source.activities.DexcomOnePlusStartActivity +import app.aaps.plugins.source.activities.DexcomOnePlusStatusActivity +import app.aaps.plugins.source.activities.DexcomOnePlusWarmupActivity +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ClassKey +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.IntoMap +import dev.zacsweers.metro.MembersInjector +import dev.zacsweers.metro.Provides + +/** + * Member injectors for the Dexcom ONE+ / G7 screens and the driver log screen. + * + * Android constructs an activity, so it cannot take its dependencies in a constructor. + * [app.aaps.core.ui.compose.MetroAppCompatActivity] fills the fields from this map. + */ +@ContributesTo(AppScope::class) +@BindingContainer +object SourceMemberInjectors { + + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(DexcomOnePlusStartActivity::class) + fun bindDexcomOnePlusStartActivity( + injector: MembersInjector + ): MembersInjector<*> = injector + + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(DexcomOnePlusStatusActivity::class) + fun bindDexcomOnePlusStatusActivity( + injector: MembersInjector + ): MembersInjector<*> = injector + + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(DexcomOnePlusWarmupActivity::class) + fun bindDexcomOnePlusWarmupActivity( + injector: MembersInjector + ): MembersInjector<*> = injector + + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(CgmDriverLogActivity::class) + fun bindCgmDriverLogActivity( + injector: MembersInjector + ): MembersInjector<*> = injector +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/logs/DriverLogReader.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/logs/DriverLogReader.kt new file mode 100644 index 000000000000..87017d73261c --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/logs/DriverLogReader.kt @@ -0,0 +1,90 @@ +package app.aaps.plugins.source.logs + +import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import java.io.File +import java.io.RandomAccessFile + +/** + * Reads the driver lines back out of the AAPS log file. + * + * AAPS writes one rolling file, `AndroidAPS.log`, in the folder that `logback.xml` names. Each + * line looks like `10:23:45.123 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_SESSION: …`, so the driver a + * line belongs to is the name between the level and the colon. + * + * Two rules shape this class: + * + * - The file can be five megabytes. It is never read whole. Only the last [TAIL_BYTES] are read, + * and only the last [MAX_LINES] kept lines are handed back, so the screen stays cheap to open + * even while a session is writing. + * - A failure line written with a cause carries its stack trace on the lines that follow, and + * those lines have no prefix of their own. They are kept with the line they belong to, because + * a stack trace with its first line missing is the one thing nobody can read. + */ +object DriverLogReader { + + /** The name of the file that is being written right now. Older ones are zipped. */ + const val CURRENT_FILE = "AndroidAPS.log" + + /** How much of the end of the file to read. */ + const val TAIL_BYTES = 512L * 1024L + + /** How many lines to keep, newest last. */ + const val MAX_LINES = 1000 + + /** The logger names of the Dexcom ONE+ / G7 driver lines. */ + val DRIVER_LOGGERS: Set = setOf(OnePlusLogMarkers.TAG) + + private val LINE_START = Regex("""^\d{2}:\d{2}:\d{2}\.\d{3} \[[^]]*] [A-Z]/([^:]+): """) + + /** + * @param directory the folder `logback.xml` writes to, from `LoggerUtils.logDirectory`. + * @return the kept lines, oldest first. An empty list when the file is not there yet, which is + * the normal answer on a build that has just started. + */ + fun read(directory: String): List { + val file = File(directory, CURRENT_FILE) + if (!file.isFile) return emptyList() + return keep(tail(file, TAIL_BYTES), DRIVER_LOGGERS, MAX_LINES) + } + + /** + * Reads the last bytes of a file as lines. + * + * The first line of the block is dropped, because reading from a byte offset almost always + * lands in the middle of a line and half a line is worse than no line. Nothing is dropped when + * the whole file fits in the block. + */ + fun tail(file: File, maxBytes: Long): List { + val length = file.length() + val from = if (length > maxBytes) length - maxBytes else 0L + val block = RandomAccessFile(file, "r").use { handle -> + handle.seek(from) + val bytes = ByteArray((length - from).toInt()) + handle.readFully(bytes) + String(bytes, Charsets.UTF_8) + } + val lines = block.split("\n") + return if (from > 0L) lines.drop(1) else lines + } + + /** + * Keeps the lines of the wanted drivers, and the lines that carry on from them. + * + * @param loggerNames the logger names to keep, for example `DEXCOM_ONEPLUS`. + * @param maxLines how many lines to hand back at most, counted from the end. + */ + fun keep(lines: List, loggerNames: Set, maxLines: Int): List { + val kept = ArrayList() + var carrying = false + for (line in lines) { + val match = LINE_START.find(line) + if (match != null) { + carrying = match.groupValues[1] in loggerNames + if (carrying) kept.add(line) + } else if (carrying && line.isNotBlank()) { + kept.add(line) + } + } + return if (kept.size > maxLines) kept.subList(kept.size - maxLines, kept.size).toList() else kept + } +} diff --git a/plugins/source/src/androidMain/res/values/strings.xml b/plugins/source/src/androidMain/res/values/strings.xml index 49cf66020a55..0634bdd98d7e 100644 --- a/plugins/source/src/androidMain/res/values/strings.xml +++ b/plugins/source/src/androidMain/res/values/strings.xml @@ -59,4 +59,172 @@ Sensor signal lost, please check the connection duplicate reading + + Dexcom ONE+ / G7 + Native Dexcom ONE+ and G7 Bluetooth in AAPS. Apply the sensor, enter the pairing code immediately, then wait ~30 min warm-up before loop glucose. + Status, connect with pairing code, and warm-up + ONE+ / G7 status + Session phase and connection status + Start sensor + Apply sensor → enter code now → connect → ~30 min warm-up + How to start:\n1. Apply the sensor on your body.\n2. Paste the applicator Data Matrix (GS1) or enter the 4-digit pairing code — do not wait until after warm-up.\n3. Stop Dexcom, xDrip, and Juggluco Direct (only one Bluetooth master).\n4. Allow Bluetooth, Scan, select the highlighted sensor, then Connect / follow.\n5. Accept the Android Bluetooth pairing prompt if shown.\n6. Warm-up ~30 min for a new sensor; attaching to a running sensor can deliver EGVs sooner. + Prepare + Code + Connect + Warm-up + Connect adopts the selected sensor and opens the warm-up screen. The countdown also shows on the overview and in the ongoing notification — you do not have to stay on that screen. + Applicator Data Matrix (GS1) or 4-digit PIN + Paste the full Data Matrix text from a QR scanner, or type the 4-digit PIN. Serial is stored for reconnect matching. + Parsed PIN %1$s · serial %2$s + — + Last successful MAC: %1$s + Sensor warm-up + ~30 minute warm-up countdown + Back + Before pairing: allow nearby Bluetooth devices (and notifications if prompted). Keep the phone near the sensor during start and warm-up. + Scan for nearby ONE+ / G7-family sensors. Stop other Dexcom / xDrip / Juggluco Direct apps first. + Every ONE+ / G7 sensor in range is listed. The 4-digit code is not sent in the Bluetooth signal, so the app cannot use it to find your sensor. Pick the one you have just applied. The code is checked when you press Connect. + Scan + Stop + Scanning… + Devices found: %1$d + Unnamed Dexcom device + Select a sensor from the scan list + This is a different sensor from the paired one, but the pairing code has not changed. Paste the new applicator code — or press Connect again to keep the current one. + Stop the Dexcom app and xDrip first, because only one app can use the sensor over Bluetooth. This source attaches to a running sensor session and does not end it. It is not certain that the Dexcom app can use the sensor again afterwards. + Connect / follow sensor + Enter the sensor pairing code + Enter a valid 4-digit sensor pairing code + Allow Bluetooth + Bluetooth permission is required before starting the sensor + Repair a missing sensor change + On by default. When "Create sensor change" is also on, a missing sensor change for the running sensor is written once, so the sensor age is right. An event you delete after that write is not written again. + Use a sensor change you logged as the start + On by default. When off, a new ONE+ session keeps the time of the start or of the first reading, and a sensor change logged earlier is not used to move that time back. When on, a sensor change from the last 24 hours that is earlier than that automatic time becomes the session start. + Allow correcting the insertion date + On by default. When on, the Status screen can move the insertion time of the sensor in use. Sensor change events between the old and the new time are invalidated. Calibration entries are not deleted. + Correct insertion date + A sensor cannot be inserted in the future. The sensor still starts at %1$s. + That date is older than a full sensor life, so it belongs to another sensor. The sensor still starts at %1$s. + No sensor session is running, so there is no date to correct. + Start / new sensor + (none) + Up + Down + Idle + Pairing + Connecting + Reconnecting + Warming up + Active + Failed + — + Showing a local ~30 min timer because the sensor did not provide remaining time yet. + Establishing the Bluetooth link — keep the app open and stay close to the sensor. This can take up to a minute. + No loop glucose yet — wait until warm-up finishes. + Pairing with sensor… + Authenticated — starting glucose session… + Sensor session detected on transmitter. + Session ended or disconnected. + Authentication or Bluetooth pairing failed. Accept the system pairing prompt and retry. + Connection or sensor session error. Check the Bluetooth connection and try again. + If the problem continues, open the driver log on this screen. + Warm-up complete — source active + Dexcom ONE+ / G7 + Dexcom ONE+ / G7 status + Ongoing sensor connection and warm-up status. + Keeping the sensor connected + This sensor is already soaking + It is running as your pre-soak sensor. One sensor cannot be paired twice at the same time: both sessions would talk over each other and the pairing fails for both.\n\nIf it is ready, promote it — that keeps everything it has collected. Otherwise cancel the pre-soak, which throws that away, and start it here instead. + Promote it instead + Cancel pre-soak and start here + Leave it soaking + This sensor already feeds the loop. Start it from Production, not as a pre-soak. + Pairing… + Connecting to sensor… + Reconnecting… + No signal from the sensor for %1$d min — keep the phone close + Wrong sensor? + Another Dexcom ONE+ / G7 sensor is nearby but the paired one stays silent. Start the sensor again to pair the new one. + Sensor warming up + Keep the phone near the sensor + Warm-up interrupted + Open the app to retry + Production feeds the loop after warm-up. Staging (pre-soak) warms a second sensor alongside the one you are currently using — it is collect-only and never feeds the loop until you promote it from the status screen. + Start staging sensor + The staging sensor collects readings in the background and does not feed the loop. Return to the overview; promote it later from the ONE+ / G7 status screen once it is ready. + None + Warming up + Settling + Ready to promote + Last reading: %1$s at %2$s + No reading yet. The staging sensor is still warming up or out of range. + Cancel staging + Promote to production + Promote staging sensor? + This switches the loop\'s glucose source to the staging sensor and retires the sensor currently in use. This cannot be undone. + Switch to it now (not settled) + Use this only if the sensor in use has stopped or has to be replaced now. The new sensor is reading, but it has not finished its 12 hour settling time. + Switch to a sensor that is not settled? + The new sensor is sending readings, but it has not finished its 12 hour settling time. Its readings can be less accurate for the first hours, so the loop may dose on values that are too high or too low. Only do this if the sensor in use has stopped or must be replaced now. This switches the loop\'s glucose source and cannot be undone. + Promote + Cancel + Staging sensor promoted — it now feeds the loop. + Sensor promoted, but older calibration entries could not be ignored. Remove fingerstick calibrations taken before this switch, then calibrate again if needed. + Sensor promoted, but reconnecting it failed. The production sensor is the one just promoted. Open the ONE+ status screen and bring the sensor back in range. This is not a complete success. + A step after the exchange failed, and the production sensor identity is missing. This is not a complete success. Open the ONE+ status screen and check which sensor is in use. + No staging sensor to promote. + Staging sensor has not settled long enough to promote yet. + Staging sensor has not produced enough valid glucose yet. + Staging sensor has not sent a reading in the last minutes. Wait until it reads again before switching to it. + Close + Show more + Show less + Step %1$d of %2$d + Production + Pre-soak + How to start — 6 steps + Before you pair — read this first + Bluetooth permission and range + Production or pre-soak? + Pairing code + Sensors nearby + Rescan + last used + Signal %1$d dBm + No sensor found yet. Press Scan and keep the phone right next to the sensor. + Connect adopts %1$s and opens warm-up. + remaining + Ends at %1$s + What happened + Try connecting again + Start another sensor + Sensor + Name + Address + Status + Production sensor + Pre-soak sensor + Actions + Bluetooth session + Started %1$s ago + No reading received yet. + Readings collected + Last reading + Sensor is near its end + Starting a pre-soak sensor now means the next one is already warm when this one stops. + Start a pre-soak sensor + A pre-soak sensor collects readings alongside the one in use. It never feeds the loop until you promote it here. + Sensor driver log + Refresh + Share the log + Nothing yet. Lines appear here as soon as the driver starts working. + %1$d lines + Driver log + Follow + Switch to the pre-soak sensor automatically + After the set number of hours, the pre-soak sensor feeds the loop if its recent readings are good. The sensor in use is stopped. The promote button still works. + Hours before the automatic switch + The pre-soak sensor now feeds the loop. Automatic switch after %1$s. + \ No newline at end of file diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchor.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchor.kt new file mode 100644 index 000000000000..6cf7fe707cde --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorChangeAnchor.kt @@ -0,0 +1,34 @@ +package app.aaps.plugins.source + +/** + * Pure decision behind the ONE+ SENSOR_CHANGE anchor: should the plugin's own auto timestamp + * (pairing moment, or first accepted reading) be replaced by a SENSOR_CHANGE the user already + * logged by hand — e.g. in Careportal, right after physically inserting the sensor and before + * pairing it in the app? + * + * Without this, a sensor inserted hours before pairing always got dated at the pairing moment: + * `OnePlusSensorStore.startSessionForSensor` and `saveSessionStartIfAbsent` only ever saw + * `System.currentTimeMillis()` / the first reading's timestamp, so a manual, earlier, more + * accurate entry was silently outrun by the later auto one becoming "the most recent SENSOR_CHANGE" + * that `LinearCalibrationPlugin` reads. + */ +internal object DexcomOnePlusSensorChangeAnchor { + + /** How far back a manually logged SENSOR_CHANGE can still plausibly belong to this insertion. */ + private const val MANUAL_LOOKBACK_MS = 24L * 60L * 60L * 1000L + + /** + * @param autoStartMs the timestamp this plugin would stamp on its own (pairing moment, or first + * accepted reading) + * @param lastSensorChangeMs the most recent existing SENSOR_CHANGE therapy event, if any + * @param now current wall-clock time, used to bound how far back a manual entry can be + * @return [lastSensorChangeMs] when it is an earlier, recent-enough manual entry; [autoStartMs] + * otherwise + */ + fun resolve(autoStartMs: Long, lastSensorChangeMs: Long?, now: Long): Long { + if (lastSensorChangeMs == null) return autoStartMs + if (lastSensorChangeMs >= autoStartMs) return autoStartMs + if (now - lastSensorChangeMs > MANUAL_LOOKBACK_MS) return autoStartMs + return lastSensorChangeMs + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrection.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrection.kt new file mode 100644 index 000000000000..1c75c0a8d3df --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorStartCorrection.kt @@ -0,0 +1,90 @@ +package app.aaps.plugins.source + +/** + * Pure rules behind "correct the insertion date" on the ONE+ Status screen. + * + * The sensor age of this source comes from the driver's own stored session start, not from the + * `SENSOR_CHANGE` therapy event, and that clock is written once — at pairing, or at the first + * reading. A sensor inserted hours before it was paired therefore carried a wrong age for its whole + * life, and nothing in the app could move it: adding a `SENSOR_CHANGE` by hand does not reach this + * clock, and an added event that is EARLIER than the one the plugin already wrote is not even the + * "last sensor change" any more, so the overview ignores it too. + * + * [Verdict.Disabled]: the user switched the correction off in the settings, so nothing is read or + * written. + */ +object DexcomOnePlusSensorStartCorrection { + + /** Verdict of [validate] — the screen turns each case into its own message. */ + sealed interface Verdict { + + data object Accepted : Verdict + + /** A sensor cannot have been inserted in the future. */ + data object InFuture : Verdict + + /** Older than a full sensor life plus its grace: this would be a different sensor. */ + data object TooOld : Verdict + + /** No sensor session is stored, so there is no age to correct. */ + data object NoSession : Verdict + + /** The setting is off. Nothing was read and nothing was written. */ + data object Disabled : Verdict + } + + /** + * @param newStartMs insertion time the user picked + * @param currentStartMs session start stored today (0 when none) + * @param nowMs current wall-clock time + * @param maxAgeMs oldest insertion still plausible for the running sensor + */ + fun validate( + newStartMs: Long, + currentStartMs: Long, + nowMs: Long, + maxAgeMs: Long = DexcomOnePlusStaging.SENSOR_LIFE_MS + DexcomOnePlusStaging.SENSOR_GRACE_MS, + ): Verdict = when { + currentStartMs <= 0L -> Verdict.NoSession + newStartMs > nowMs -> Verdict.InFuture + nowMs - newStartMs > maxAgeMs -> Verdict.TooOld + else -> Verdict.Accepted + } + + /** + * Oldest moment whose `SENSOR_CHANGE` events belong to the session being corrected. + * + * Both the events the plugin wrote by itself and anything the user logged in between have to go, + * or the newest of them keeps winning the overview's "last sensor change" lookup and the + * corrected date stays invisible. Moving the date **earlier** has to reach back to the new date; + * moving it **later** has to reach back to the old one. + */ + fun cleanupFrom(newStartMs: Long, currentStartMs: Long): Long = minOf(newStartMs, currentStartMs) + + /** Steps used to walk away from an occupied moment, and how far the walk may go. */ + private const val FREE_STEP_MS = 1_000L + private const val FREE_MAX_STEPS = 60 + + /** + * A moment no `SENSOR_CHANGE` occupies yet, at or just after [desiredMs]. + * + * The database refuses a second sensor change at a timestamp it already holds — and it looks for + * that duplicate **without checking whether the existing row is still valid**. So the event this + * correction had just invalidated one line earlier still blocked the new one: nothing was + * inserted, the refusal was silent, and the display was left with no valid sensor change at all, + * falling back to the previous sensor or to nothing. The user then saw the corrected date on the + * plugin screen and the old one everywhere else. + * + * Moving by one second is invisible in an age shown in hours, and it is the only thing that has + * to give. The picker zeroes seconds and milliseconds, so two corrections to the same minute + * collide exactly; without this they would collide for good. + */ + fun freeTimestamp(desiredMs: Long, takenMs: Set): Long { + var candidate = desiredMs + repeat(FREE_MAX_STEPS) { + if (candidate !in takenMs) return candidate + candidate += FREE_STEP_MS + } + return candidate + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusStaging.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusStaging.kt new file mode 100644 index 000000000000..742e01ccabb0 --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusStaging.kt @@ -0,0 +1,144 @@ +package app.aaps.plugins.source + +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.interfaces.source.StagingState + +/** + * Pure helpers + tunable constants for the Dexcom ONE+ dual-sensor (pre-soak / staging) feature. + * Kept out of [DexcomOnePlusPlugin] so the lifecycle / staging state machine is unit-testable without + * the DI graph or Android. + * + * ⚠️ The time constants below are tunable and kept on the safe side. + */ +internal object DexcomOnePlusStaging { + + private const val HOUR_MS = 60L * 60L * 1000L + + /** + * Whether a slot's stored MAC describes the transmitter at [deviceAddress]. + * + * The rule the cross-slot guard rests on. One sensor must never be paired in both slots at once: + * the two GATT clients share a single ACL link, both subscribe to the same Auth and ExtraData + * characteristics, and the transmitter sees one interleaved stream of two KEKS handshakes. A + * field log showed both sides dying inside libkeks 1.6 s after the second connect. + * + * Case-insensitive because a MAC reaches the stores from several places — a live scan hit, an + * applicator parse, a restored session — and only some of them upper-case it. + */ + fun isSameTransmitter(storedMac: String?, deviceAddress: String): Boolean { + val stored = storedMac?.trim()?.takeIf { it.isNotEmpty() } ?: return false + val target = deviceAddress.trim().takeIf { it.isNotEmpty() } ?: return false + return stored.equals(target, ignoreCase = true) + } + + /** Nominal ONE+/G7 sensor life. */ + const val SENSOR_LIFE_MS = 10L * 24L * HOUR_MS + + /** End-of-life grace extension. */ + const val SENSOR_GRACE_MS = 12L * HOUR_MS + + /** End-of-life window: prompt the user to start a new sensor. */ + const val END_OF_LIFE_MS = 12L * HOUR_MS + + /** Minimum staging duration before promotion is allowed. */ + const val STAGING_MIN_SETTLE_MS = 12L * HOUR_MS + + /** Minimum count of valid staging EGVs before promotion is allowed. */ + const val STAGING_MIN_VALID_EGV = 6 + + /** + * How recent the staging sensor's last reading must be for an EARLY promotion (4 missed readings + * on a 5-minute sensor). The normal path already proves the sensor lives through a 12 h soak; an + * early promotion has no such proof, so the loop must not be handed a sensor that went silent. + */ + const val STAGING_MAX_EGV_AGE_MS = 20L * 60L * 1000L + + /** + * Derive a [CgmSensorLifecycle] from a sensor session start. Returns null when the start is + * unknown (0) so the status screen simply shows nothing special. + */ + fun computeLifecycle(sessionStartMs: Long, nowMs: Long): CgmSensorLifecycle? { + if (sessionStartMs <= 0L) return null + val age = (nowMs - sessionStartMs).coerceAtLeast(0L) + val remaining = sessionStartMs + SENSOR_LIFE_MS + SENSOR_GRACE_MS - nowMs + return CgmSensorLifecycle( + startedAtEpochMs = sessionStartMs, + ageMs = age, + endOfLife = remaining < END_OF_LIFE_MS, + ) + } + + /** + * Coarse staging slot state for the status screen card + promote gating. + * + * @param present a staging sensor session exists. + * @param warming the staging sensor is warming up / (re)connecting (no glucose yet). + * @param sessionStartMs staging session start (0 = unknown). + * @param validEgvCount valid staging EGVs collected so far. + */ + fun computeStagingState( + present: Boolean, + warming: Boolean, + sessionStartMs: Long, + validEgvCount: Int, + nowMs: Long, + ): StagingState { + if (!present) return StagingState.ABSENT + if (warming) return StagingState.WARMUP + val settledLongEnough = sessionStartMs > 0L && (nowMs - sessionStartMs) >= STAGING_MIN_SETTLE_MS + return if (settledLongEnough && validEgvCount >= STAGING_MIN_VALID_EGV) StagingState.READY + else StagingState.SETTLING + } + + /** + * Milliseconds left before the staging sensor has soaked [STAGING_MIN_SETTLE_MS]. + * + * Null when there is no staging sensor, when its start is unknown, or when the wait is over, so + * a caller cannot show a stale "ready in". It says nothing about the valid-reading count: + * [computeStagingState] still decides when promotion is allowed. + */ + fun settleRemainingMs(present: Boolean, sessionStartMs: Long, nowMs: Long): Long? { + if (!present || sessionStartMs <= 0L) return null + return (STAGING_MIN_SETTLE_MS - (nowMs - sessionStartMs)).takeIf { it > 0L } + } + + /** What the staging slot knows about its warm-up after one driver phase — see [applyWarmupPhase]. */ + data class StagingWarmupDecision(val warmupDone: Boolean, val warming: Boolean) + + /** + * May the user be OFFERED an early promotion — promoting the staging sensor before its soak ends, + * because the production sensor stopped early or has to be replaced now? + * + * This is only about showing the button and about the matching guard in the promote path. It never + * relaxes the evidence: the sensor must have produced [STAGING_MIN_VALID_EGV] valid readings and a + * reading no older than [STAGING_MAX_EGV_AGE_MS], so a silent or dead sensor can never take over + * the loop. What it does drop is the 12 h soak, which is a quality gate, not a safety one — the + * user is told the readings will be less reliable for the first hours. + */ + fun canPromoteEarly(validEgvCount: Int, lastValueAtEpochMs: Long?, nowMs: Long): Boolean { + if (validEgvCount < STAGING_MIN_VALID_EGV) return false + if (lastValueAtEpochMs == null || lastValueAtEpochMs <= 0L) return false + val age = nowMs - lastValueAtEpochMs + return age in 0L..STAGING_MAX_EGV_AGE_MS + } + + /** + * Feed one driver warm-up phase into the staging warm-up latch. + * + * Leaving warm-up is an EVENT that is latched once, never re-derived from the live phase: a + * healthy sensor re-connects on every radio cycle (~5 min) for its whole life, so reading + * CONNECTING / RECONNECTING as "still warming up" kept the slot in [StagingState.WARMUP] forever — + * the settling countdown was never shown and the promote button (READY only) stayed unreachable. + * + * A slot that has not passed warm-up yet counts as warming whatever the driver is doing right now, + * including a failed or idle radio: a sensor that never warmed up must not be shown as settling, + * which would display a 12 h stabilisation countdown for a sensor that has produced nothing. + * + * @param warmupDoneBefore the latch as it stands (restored from the store across restarts). + * @param readyPhase the driver reports the sensor has finished warm-up. + */ + fun applyWarmupPhase(warmupDoneBefore: Boolean, readyPhase: Boolean): StagingWarmupDecision { + val done = warmupDoneBefore || readyPhase + return StagingWarmupDecision(warmupDone = done, warming = !done) + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt new file mode 100644 index 000000000000..fc67d40afc9d --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt @@ -0,0 +1,88 @@ +package app.aaps.plugins.source + +/** + * Decides when a pre-soak sensor may take over the loop by itself, without the user pressing the + * promote button. + * + * Used by the Dexcom ONE+ / G7 plugin. It is checked on every reading of the + * pre-soak sensor, so it needs no timer, it survives an app restart, and a sensor that sends nothing + * is never switched to. + * + * It only says "yes" or "not yet". The switch itself is the same function the button calls, with + * all of its own checks. This class adds checks on top of them, it never removes one. + */ +object StagingAutoPromotion { + + private const val MINUTE_MS = 60L * 1000L + private const val HOUR_MS = 60L * MINUTE_MS + + /** Readings older than this do not count as "recent". */ + const val RECENT_WINDOW_MS = 30L * MINUTE_MS + + /** The newest reading must be at most this old. */ + const val MAX_LAST_READING_AGE_MS = 15L * MINUTE_MS + + /** + * After an automatic switch was tried and refused, wait at least this long before the next try. + * Keeps the log readable when a reading arrives every minute. + */ + const val RETRY_INTERVAL_MS = 30L * MINUTE_MS + + /** A value at or below this is the sensor's low limit, not a real glucose. */ + const val RAIL_LOW_MGDL = 39.0 + + /** A value at or above this is the sensor's high limit, not a real glucose. */ + const val RAIL_HIGH_MGDL = 400.0 + + enum class Decision { + + /** The setting is off. */ + DISABLED, + + /** The pre-soak start time is not known. */ + NO_START, + + /** The set number of hours has not passed yet. */ + TOO_EARLY, + + /** Not enough readings in the last [RECENT_WINDOW_MS]. */ + TOO_FEW_RECENT, + + /** The newest reading is older than [MAX_LAST_READING_AGE_MS]. */ + STALE, + + /** A recent reading is at the sensor's low or high limit. */ + RAILED, + + /** All checks passed: switch now. */ + PROMOTE, + } + + /** + * @param enabled the user's switch for the automatic promotion + * @param delayHours hours after the pre-soak start before the switch may happen + * @param startMs pre-soak start (epoch ms), 0 or less when not known + * @param readings pre-soak readings as (timestamp ms, mg/dL), any order + * @param minRecentReadings how many readings the last [RECENT_WINDOW_MS] must hold; it depends on + * the sensor cadence (5 min for ONE+ / G7) + * @param nowMs current time (epoch ms) + */ + fun decide( + enabled: Boolean, + delayHours: Int, + startMs: Long, + readings: List>, + minRecentReadings: Int, + nowMs: Long, + ): Decision { + if (!enabled) return Decision.DISABLED + if (startMs <= 0L) return Decision.NO_START + if (nowMs - startMs < delayHours * HOUR_MS) return Decision.TOO_EARLY + val recent = readings.filter { (ts, _) -> ts in (nowMs - RECENT_WINDOW_MS)..nowMs } + if (recent.size < minRecentReadings) return Decision.TOO_FEW_RECENT + val newestMs = recent.maxOf { it.first } + if (nowMs - newestMs > MAX_LAST_READING_AGE_MS) return Decision.STALE + if (recent.any { (_, mgdl) -> mgdl <= RAIL_LOW_MGDL || mgdl >= RAIL_HIGH_MGDL }) return Decision.RAILED + return Decision.PROMOTE + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmCardParts.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmCardParts.kt new file mode 100644 index 000000000000..fb3519e76d4b --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmCardParts.kt @@ -0,0 +1,381 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +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.RowScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ExpandLess +import androidx.compose.material.icons.filled.ExpandMore +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ElevatedCard +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +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.graphics.Color +import androidx.compose.ui.text.style.TextAlign +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.SourceStrings + +/** + * A block of related information, with its own surface. + * + * The original screens were a flat run of `Text` lines, so "which sensor does this line describe?" + * had no visual answer once there were two sensors on screen. A card gives each subject a boundary. + * + * @param accent true for the card that describes the sensor currently feeding the loop, so it can + * be told apart from the pre-soak sensor without reading either heading. + */ +@Composable +fun CgmCard( + modifier: Modifier = Modifier, + accent: Boolean = false, + tone: CgmCardTone = CgmCardTone.Neutral, + content: @Composable ColumnScope.() -> Unit, +) { + val container = when { + tone == CgmCardTone.Warning -> MaterialTheme.colorScheme.errorContainer + accent -> MaterialTheme.colorScheme.secondaryContainer + else -> MaterialTheme.colorScheme.surfaceContainerLow + } + ElevatedCard( + modifier = modifier.fillMaxWidth(), + colors = CardDefaults.elevatedCardColors(containerColor = container), + ) { + Column( + modifier = Modifier.padding(AapsSpacing.extraLarge), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + content = content, + ) + } +} + +/** Whether a card carries ordinary information or something the user has to act on. */ +enum class CgmCardTone { Neutral, Warning } + +/** + * Card heading: an uppercase label on the left, room for a state chip on the right. + */ +@Composable +fun CgmCardHeader( + title: String, + modifier: Modifier = Modifier, + trailing: @Composable RowScope.() -> Unit = {}, +) { + Row( + modifier = modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = title, + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.weight(1f), + ) + trailing() + } +} + +/** + * One fact: its name on the left, its value on the right. + * + * The value is aligned right so a column of them lines up, which is what makes a card of readings + * scannable rather than a paragraph. + */ +@Composable +fun CgmKeyValueRow( + label: String, + value: String, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = label, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.weight(1f), + ) + Text( + text = value, + style = MaterialTheme.typography.bodyMedium, + textAlign = TextAlign.End, + ) + } +} + +/** + * Long help text, folded away until asked for. + * + * The start screen carried five permanently expanded help blocks — about two screens of scrolling + * before the first control. They are worth reading once and in the way once the user knows the + * flow, so they keep their place but start closed. [tone] lets a warning stay recognisable while + * closed, because an unread warning that looks like ordinary help is not a warning. + */ +@Composable +fun CgmHelpCard( + title: String, + modifier: Modifier = Modifier, + tone: CgmCardTone = CgmCardTone.Neutral, + expandedByDefault: Boolean = false, + content: @Composable ColumnScope.() -> Unit, +) { + var expanded by remember { mutableStateOf(expandedByDefault) } + val titleColor = when (tone) { + CgmCardTone.Neutral -> MaterialTheme.colorScheme.onSurface + CgmCardTone.Warning -> MaterialTheme.colorScheme.error + } + CgmCard(modifier = modifier) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { expanded = !expanded }, + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = title, + style = MaterialTheme.typography.bodyMedium, + color = titleColor, + modifier = Modifier.weight(1f), + ) + Icon( + imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, + contentDescription = stringResource( + if (expanded) SourceStrings.cgm_help_collapse else SourceStrings.cgm_help_expand, + ), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + AnimatedVisibility(visible = expanded) { + Column( + verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + content = content, + ) + } + } +} + +/** + * How far along a sequence of named steps something is — nodes on a line, with their labels. + * + * A state label alone ("Settling") says where a thing is but not how far through it is, nor what + * comes next. The nodes say both without a sentence. + * + * @param reached index of the current step; -1 when the sequence has not started. + */ +@Composable +fun CgmStepTimeline( + labels: List, + reached: Int, + modifier: Modifier = Modifier, +) { + val done = MaterialTheme.colorScheme.primary + val todo = MaterialTheme.colorScheme.surfaceVariant + Column( + modifier = modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.small), + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + labels.indices.forEach { index -> + if (index > 0) { + Box( + modifier = Modifier + .weight(1f) + .height(AapsSpacing.extraSmall) + .background(if (index <= reached) done else todo), + ) + } + TimelineNode(reached = index <= reached, current = index == reached, done = done, todo = todo) + } + } + Row(modifier = Modifier.fillMaxWidth()) { + labels.forEachIndexed { index, label -> + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + color = if (index <= reached) { + MaterialTheme.colorScheme.onSurface + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + textAlign = when (index) { + 0 -> TextAlign.Start + labels.lastIndex -> TextAlign.End + else -> TextAlign.Center + }, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +@Composable +private fun TimelineNode( + reached: Boolean, + current: Boolean, + done: Color, + todo: Color, +) { + Box( + modifier = Modifier.size(AapsSpacing.extraLarge), + contentAlignment = Alignment.Center, + ) { + if (current) { + Box( + modifier = Modifier + .size(AapsSpacing.extraLarge) + .background(color = done.copy(alpha = 0.25f), shape = CircleShape), + ) + } + Box( + modifier = Modifier + .size(AapsSpacing.large) + .background(color = if (reached) done else todo, shape = CircleShape), + ) + } +} + +/** + * The guided-flow progress of the start screen, in the form the window can afford. + * + * Wide: the four labelled steps side by side. Compact: "Step 2 of 4" plus the step name and a + * four-segment bar — no label is ever squeezed into 82 dp, so nothing truncates on a narrow phone + * or when the theme scales type up on a tablet. + */ +@Composable +fun CgmStepper( + currentStep: Int, + labels: List, + compact: Boolean, + modifier: Modifier = Modifier, +) { + if (compact) { + Column( + modifier = modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.small), + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + verticalAlignment = Alignment.Bottom, + ) { + Text( + text = stringResource( + SourceStrings.cgm_step_counter, + (currentStep + 1).coerceAtMost(labels.size), + labels.size, + ), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = labels.getOrElse(currentStep) { labels.last() }, + style = MaterialTheme.typography.titleSmall, + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(AapsSpacing.small)) { + labels.indices.forEach { index -> + Box( + modifier = Modifier + .weight(1f) + .height(AapsSpacing.chipProgressHeight) + .background( + color = if (index <= currentStep) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.surfaceVariant + }, + shape = RoundedCornerShape(AapsSpacing.extraSmall), + ), + ) + } + } + } + } else { + Row( + modifier = modifier.fillMaxWidth(), + verticalAlignment = Alignment.Top, + ) { + labels.forEachIndexed { index, label -> + if (index > 0) { + Box( + modifier = Modifier + .weight(1f) + .padding(top = AapsSpacing.large) + .height(AapsSpacing.extraSmall) + .background( + if (index <= currentStep) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.surfaceVariant + }, + ), + ) + } + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(AapsSpacing.small), + modifier = Modifier.width(AapsSpacing.xxLarge * 3), + ) { + Box( + modifier = Modifier + .size(AapsSpacing.chipIconSize) + .background( + color = if (index <= currentStep) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.surfaceVariant + }, + shape = CircleShape, + ), + contentAlignment = Alignment.Center, + ) { + Text( + text = "${index + 1}", + style = MaterialTheme.typography.labelMedium, + color = if (index <= currentStep) { + MaterialTheme.colorScheme.onPrimary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + Text( + text = label, + style = MaterialTheme.typography.labelSmall, + textAlign = TextAlign.Center, + color = if (index <= currentStep) { + MaterialTheme.colorScheme.onSurface + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + } + } + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt new file mode 100644 index 000000000000..64eddb007c8b --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt @@ -0,0 +1,136 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.RowScope +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.AapsTopAppBar +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.SourceStrings + +/** + * Which job the navigation icon of a ONE+ screen does — see the convention documented on + * [app.aaps.core.ui.compose.AapsTopAppBar]. + */ +enum class CgmNavIcon { + + /** Pure navigation (status, warm-up, log): back arrow. */ + Back, + + /** A task the user either commits or abandons (sensor start): close cross. */ + Close, +} + +/** + * Shared frame for every ONE+ / G7 screen. + * + * Three things are settled here once, instead of being re-decided per screen: + * + * - **The screen scrolls.** Content is given by [content] and the screens put a single scrolling + * container inside it. The original screens used a plain non-scrolling `Column`, so in landscape, + * on a tablet (where the theme scales type by 1.5) or with a staging sensor present, whatever sat + * at the bottom — including the promote button — was drawn past the edge and could not be reached. + * - **Running text stops at a readable width.** On a wide window the content column is centred at + * [CgmSpacing.readableContentMaxWidth] instead of stretching to the screen edge. Pass + * `constrainWidth = false` for a screen that lays out its own panes. + * - **The bar is the same everywhere**, with the navigation icon picked by screen role. + */ +@Composable +fun CgmScaffold( + title: String, + onNavigate: () -> Unit, + modifier: Modifier = Modifier, + navIcon: CgmNavIcon = CgmNavIcon.Back, + actions: @Composable RowScope.() -> Unit = {}, + bottomBar: @Composable () -> Unit = {}, + constrainWidth: Boolean = true, + content: @Composable BoxScope.() -> Unit, +) { + Scaffold( + modifier = modifier, + topBar = { + AapsTopAppBar( + title = { Text(title) }, + navigationIcon = { + IconButton(onClick = onNavigate) { + when (navIcon) { + CgmNavIcon.Back -> Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(SourceStrings.dexcom_oneplus_nav_back), + ) + + CgmNavIcon.Close -> Icon( + imageVector = Icons.Filled.Close, + contentDescription = stringResource(SourceStrings.cgm_nav_close), + ) + } + } + }, + actions = actions, + ) + }, + bottomBar = bottomBar, + ) { innerPadding -> + Box( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding), + ) { + Box( + modifier = Modifier + .align(Alignment.TopCenter) + .then( + if (constrainWidth) { + Modifier.widthIn(max = CgmSpacing.readableContentMaxWidth) + } else { + Modifier + }, + ) + .fillMaxSize(), + content = content, + ) + } + } +} + +/** + * The one scrolling container of a screen (or of one pane of it). + * + * Every list of unknown length — scanned sensors, log lines — belongs here as `items()`. A list with + * its own bounded height nested inside another scroll was what pinned the sensor list of the start + * screen to 216 dp whatever the screen could offer. + */ +@Composable +fun CgmLazyColumn( + modifier: Modifier = Modifier, + state: LazyListState = rememberLazyListState(), + contentPadding: PaddingValues = PaddingValues(AapsSpacing.extraLarge), + content: LazyListScope.() -> Unit, +) { + LazyColumn( + modifier = modifier.fillMaxSize(), + state = state, + contentPadding = contentPadding, + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + content = content, + ) +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmSpacing.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmSpacing.kt new file mode 100644 index 000000000000..02a7ec0e4e50 --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmSpacing.kt @@ -0,0 +1,21 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.ui.unit.dp + +/** + * Sizes used only by the CGM screens of this module. The shared sizes are in `AapsSpacing`. + */ +internal object CgmSpacing { + + /** Widest column a form or status screen should occupy on a tablet. */ + val readableContentMaxWidth = 560.dp + + /** Shortest height of a tappable list row (sensor scan result, etc.). */ + val listRowMinHeight = 56.dp + + /** Smallest usable CGM warm-up ring. */ + val warmupRingMin = 120.dp + + /** Largest CGM warm-up ring, so it does not swallow a tablet pane. */ + val warmupRingMax = 240.dp +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmStateChip.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmStateChip.kt new file mode 100644 index 000000000000..bd5088f3bf83 --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmStateChip.kt @@ -0,0 +1,123 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.ui.compose.AapsSpacing + +/** + * What a state means for the user, stripped of protocol detail. + * + * The driver has seven phases and the staging slot four states; the user only needs to know whether + * something works, is busy, is waiting, or has stopped. Colour then carries that meaning, so the + * screen can be read at a glance instead of word by word. + */ +enum class CgmUiState { + + /** Doing its job — session up, warm-up done, staging ready to promote. */ + Ready, + + /** Busy and progressing normally — pairing, connecting, warming up. */ + Working, + + /** Nothing wrong, nothing happening yet — idle, no staging sensor. */ + Waiting, + + /** Stopped and needs the user. */ + Failed, +} + +/** + * Maps a warm-up phase to what it means for the user. + * + * The driver maps its phases onto [CgmWarmupPhase] first, so this one function keeps the chip and + * the ring driver-agnostic. + */ +fun CgmWarmupPhase.toUiState(): CgmUiState = when (this) { + CgmWarmupPhase.READY -> CgmUiState.Ready + CgmWarmupPhase.FAILED -> CgmUiState.Failed + CgmWarmupPhase.IDLE -> CgmUiState.Waiting + CgmWarmupPhase.PAIRING, + CgmWarmupPhase.CONNECTING, + CgmWarmupPhase.RECONNECTING, + CgmWarmupPhase.WARMING -> CgmUiState.Working +} + +/** Maps a staging slot state to what it means for the user. */ +fun StagingState.toUiState(): CgmUiState = when (this) { + StagingState.ABSENT -> CgmUiState.Waiting + StagingState.WARMUP, + StagingState.SETTLING -> CgmUiState.Working + StagingState.READY -> CgmUiState.Ready +} + +/** + * Small state badge: a coloured dot plus its label. + * + * Deliberately not an `AssistChip` — this shows state, it is not a control, so it must not look or + * behave like something that can be pressed. The dot and the label are read as one phrase by + * TalkBack rather than as two separate items. + */ +@Composable +fun CgmStateChip( + state: CgmUiState, + label: String, + modifier: Modifier = Modifier, +) { + val container: Color + val content: Color + when (state) { + CgmUiState.Ready -> { + container = MaterialTheme.colorScheme.primaryContainer + content = MaterialTheme.colorScheme.onPrimaryContainer + } + + CgmUiState.Working -> { + container = MaterialTheme.colorScheme.tertiaryContainer + content = MaterialTheme.colorScheme.onTertiaryContainer + } + + CgmUiState.Waiting -> { + container = MaterialTheme.colorScheme.surfaceVariant + content = MaterialTheme.colorScheme.onSurfaceVariant + } + + CgmUiState.Failed -> { + container = MaterialTheme.colorScheme.errorContainer + content = MaterialTheme.colorScheme.onErrorContainer + } + } + Row( + modifier = modifier + .clearAndSetSemantics { contentDescription = label } + .background(color = container, shape = RoundedCornerShape(AapsSpacing.chipCornerRadius)) + .padding(horizontal = AapsSpacing.medium, vertical = AapsSpacing.small), + horizontalArrangement = Arrangement.spacedBy(AapsSpacing.small), + verticalAlignment = Alignment.CenterVertically, + ) { + Box( + modifier = Modifier + .size(AapsSpacing.medium) + .background(color = content, shape = CircleShape), + ) + Text( + text = label, + style = MaterialTheme.typography.labelMedium, + color = content, + ) + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmup.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmup.kt new file mode 100644 index 000000000000..e1dc59e28d0b --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmup.kt @@ -0,0 +1,51 @@ +package app.aaps.plugins.source.compose + +/** + * Warm-up phase of a CGM sensor, with no vendor name on it. + * + * The native driver maps its own phases onto these seven, so the screens work with this one enum. + * + * The generic [app.aaps.core.interfaces.source.CgmWarmupStatus] cannot carry this: by contract it + * is null once the wait is over, so it has no IDLE, READY or FAILED, and these screens have to tell + * those three apart - they pick the colour of the chip, they stop the countdown, and they clear the + * local fallback timer. + */ +enum class CgmWarmupPhase { + + /** Nothing running. */ + IDLE, + + /** The BLE handshake is running. */ + PAIRING, + + /** GATT connect and service discovery, first attempt. */ + CONNECTING, + + /** Link was lost and the retry loop is working. Not a final state. */ + RECONNECTING, + + /** Sensor is warming up. Glucose must not be sent to AAPS in this phase. */ + WARMING, + + /** Session is up and glucose is usable. */ + READY, + + /** Final failure. The user has to act. */ + FAILED, +} + +/** + * The warm-up facts the shared countdown rules read. + * + * A driver state stripped down to the three fields those rules use, so the rules can live in shared + * code while the driver classes stay on Android. + * + * @param phase where the warm-up is right now. + * @param remainingMs time left in ms if the protocol says so, else null. + * @param endsAtEpochMs wall-clock end in epoch ms if known, else null. + */ +data class CgmWarmupInfo( + val phase: CgmWarmupPhase, + val remainingMs: Long? = null, + val endsAtEpochMs: Long? = null, +) diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmupRing.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmupRing.kt new file mode 100644 index 000000000000..567b860b82ad --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWarmupRing.kt @@ -0,0 +1,90 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.Canvas +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.size +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.graphics.StrokeCap +import androidx.compose.ui.graphics.drawscope.Stroke +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp + +/** Share of the smaller side of the available box the ring takes. */ +private const val RING_SIZE_FRACTION = 0.62f + +/** Ring thickness as a share of its diameter, so a big ring does not look like a hairline. */ +private const val RING_STROKE_FRACTION = 0.065f + +/** + * Warm-up ring, sized from the space it is given instead of from a constant. + * + * The ring used to be pinned to `AapsSpacing.bgCircleSize` (126 dp): lost in the middle of a tablet, + * and in landscape tall enough to push the rest of the screen past the bottom edge. Here the + * diameter follows the smaller side of the box the caller hands it, clamped between + * [CgmSpacing.warmupRingMin] and [CgmSpacing.warmupRingMax] so it stays readable at one end and + * does not become a poster at the other. + * + * @param progress 0f..1f for a determinate sweep, or null for a full ring — used when the remaining + * time is known but the total is not, so no fraction can honestly be drawn. + * @param state colours the ring by what it means: working, done, or stopped. + * @param content drawn in the centre, normally the mm:ss countdown. + */ +@Composable +fun CgmWarmupRing( + progress: Float?, + state: CgmUiState, + modifier: Modifier = Modifier, + content: @Composable () -> Unit, +) { + val ringColor = when (state) { + CgmUiState.Ready -> MaterialTheme.colorScheme.primary + CgmUiState.Failed -> MaterialTheme.colorScheme.error + CgmUiState.Working -> MaterialTheme.colorScheme.tertiary + CgmUiState.Waiting -> MaterialTheme.colorScheme.onSurfaceVariant + } + val trackColor = MaterialTheme.colorScheme.surfaceVariant + BoxWithConstraints(modifier = modifier, contentAlignment = Alignment.Center) { + // In a LazyColumn item maxHeight is unbounded, so the width is what limits the ring there. + val available = minOf(maxWidth, maxHeight) + val diameter = (available * RING_SIZE_FRACTION) + .coerceIn(CgmSpacing.warmupRingMin, CgmSpacing.warmupRingMax) + val strokeWidth = (diameter * RING_STROKE_FRACTION).coerceIn(6.dp, 14.dp) + val strokePx = with(LocalDensity.current) { strokeWidth.toPx() } + Box( + modifier = Modifier.size(diameter), + contentAlignment = Alignment.Center, + ) { + Canvas(modifier = Modifier.fillMaxSize()) { + val ringDiameter = size.minDimension - strokePx + val topLeft = Offset((size.width - ringDiameter) / 2f, (size.height - ringDiameter) / 2f) + val arcSize = Size(ringDiameter, ringDiameter) + drawArc( + color = trackColor, + startAngle = 0f, + sweepAngle = 360f, + useCenter = false, + topLeft = topLeft, + size = arcSize, + style = Stroke(width = strokePx, cap = StrokeCap.Round), + ) + drawArc( + color = ringColor, + startAngle = -90f, + sweepAngle = if (progress == null) 360f else 360f * progress.coerceIn(0f, 1f), + useCenter = false, + topLeft = topLeft, + size = arcSize, + style = Stroke(width = strokePx, cap = StrokeCap.Round), + ) + } + content() + } + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt new file mode 100644 index 000000000000..9cc238711f91 --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt @@ -0,0 +1,73 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.Immutable +import androidx.compose.runtime.remember +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import app.aaps.core.ui.compose.TABLET_MIN_SW_DP + +/** How much width the screen has to work with. */ +enum class CgmWidth { + + /** Phone in portrait. One column, compact controls. */ + Compact, + + /** Small tablet, or a phone in landscape on a wide device. One centred column. */ + Medium, + + /** Tablet or desktop-sized window. Two panes side by side. */ + Expanded, +} + +/** + * Size of the window a ONE+ screen is drawn in. + * + * The width classes follow the same 600 dp step as [TABLET_MIN_SW_DP], which the theme already uses + * to scale typography, so a screen never disagrees with the theme about what a tablet is. + * + * [isShort] is the case the original screens missed: a phone in landscape has plenty of width but + * only about 360 dp of height, so anything tall (the warm-up ring, a stack of full width buttons) + * has to be laid out sideways instead. + */ +@Immutable +data class CgmWindow( + val width: CgmWidth, + val isShort: Boolean, +) { + + /** True when there is enough width to show two panes next to each other. */ + val isTwoPane: Boolean get() = width == CgmWidth.Expanded +} + +/** Width in dp at which a screen may split into two panes. */ +private const val EXPANDED_MIN_WIDTH_DP = 840 + +/** Height in dp below which a screen is treated as short (phone in landscape). */ +private const val SHORT_MAX_HEIGHT_DP = 480 + +/** + * Current width and height in dp of the window the screen is drawn in. + * + * Platform specific for the same reason as `smallestScreenWidthDp` in `:core:ui`: Android answers + * from the device configuration, which is what these screens have always read, and taking the + * numbers from anywhere else would change how they lay out. The other platforms have no such + * configuration, so there the window itself is the answer. + */ +@Composable +expect fun cgmWindowSizeDp(): DpSize + +@Composable +fun rememberCgmWindow(): CgmWindow { + val size = cgmWindowSizeDp() + return remember(size) { + CgmWindow( + width = when { + size.width >= EXPANDED_MIN_WIDTH_DP.dp -> CgmWidth.Expanded + size.width >= TABLET_MIN_SW_DP.dp -> CgmWidth.Medium + else -> CgmWidth.Compact + }, + isShort = size.height < SHORT_MAX_HEIGHT_DP.dp, + ) + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdown.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdown.kt new file mode 100644 index 000000000000..c13b55206e2a --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusWarmupCountdown.kt @@ -0,0 +1,78 @@ +package app.aaps.plugins.source.compose + +/** + * Warm-up countdown resolution for the Dexcom ONE+ UI. + * + * Priority: + * 1. Protocol [CgmWarmupInfo.remainingMs] when non-null (preferred). + * 2. Else [CgmWarmupInfo.endsAtEpochMs] → remaining = endsAt − now. + * 3. Else a **local fallback** timer (`localFallbackEndsAtEpochMs`) — used ONLY when the + * protocol does not expose remaining/end. Do not invent a second clock when remainingMs + * is already provided by the driver. + * + * The driver state is mapped onto [CgmWarmupInfo] first, so this rule does not need the driver. + */ +object DexcomOnePlusWarmupCountdown { + + /** Nominal warm-up length used only for the local fallback path (~30 min). */ + const val LOCAL_FALLBACK_DURATION_MS: Long = 30L * 60L * 1000L + + /** + * @param state current driver warm-up state + * @param nowEpochMs wall clock now + * @param localFallbackEndsAtEpochMs end time for the local-only timer; null if not started + * @return remaining ms to show, or null when no countdown applies + */ + fun resolveRemainingMs( + state: CgmWarmupInfo, + nowEpochMs: Long, + localFallbackEndsAtEpochMs: Long?, + ): Long? { + state.remainingMs?.let { return it.coerceAtLeast(0L) } + state.endsAtEpochMs?.let { return (it - nowEpochMs).coerceAtLeast(0L) } + // Local fallback ONLY when protocol remaining/end are both null. + localFallbackEndsAtEpochMs?.let { return (it - nowEpochMs).coerceAtLeast(0L) } + return null + } + + fun shouldStartLocalFallback(state: CgmWarmupInfo): Boolean = + state.phase == CgmWarmupPhase.WARMING && + state.remainingMs == null && + state.endsAtEpochMs == null + + /** + * The local fallback deadline belongs to the whole warm-up, not to a single phase: a duty-cycle + * disconnect moves the phase to CONNECTING / RECONNECTING and must keep the clock. Dropping it + * there blanked the countdown and restarted a fresh ~30 min timer on the next WARMING packet. + * Only a finished / stopped / failed warm-up clears it. + */ + fun shouldClearLocalFallback(phase: CgmWarmupPhase): Boolean = when (phase) { + CgmWarmupPhase.READY, + CgmWarmupPhase.IDLE, + CgmWarmupPhase.FAILED -> true + + CgmWarmupPhase.WARMING, + CgmWarmupPhase.PAIRING, + CgmWarmupPhase.CONNECTING, + CgmWarmupPhase.RECONNECTING -> false + } + + /** Phases that show the mm:ss countdown when one is known (the link may be re-establishing). */ + fun showsCountdown(phase: CgmWarmupPhase): Boolean = when (phase) { + CgmWarmupPhase.WARMING, + CgmWarmupPhase.IDLE, + CgmWarmupPhase.PAIRING, + CgmWarmupPhase.CONNECTING, + CgmWarmupPhase.RECONNECTING -> true + + CgmWarmupPhase.READY, + CgmWarmupPhase.FAILED -> false + } + + fun formatMmSs(remainingMs: Long): String { + val totalSec = (remainingMs / 1000L).coerceAtLeast(0L) + val minutes = totalSec / 60L + val seconds = totalSec % 60L + return "$minutes:${seconds.toString().padStart(2, '0')}" + } +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt new file mode 100644 index 000000000000..0fe150aae80f --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.source.compose + +import app.aaps.core.interfaces.InterfacesStrings +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.keys.interfaces.TextRef +import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds + +/** + * The age of a CGM sensor, as shown in "Started %1$s ago" on the ONE+ screens. + * + * It keeps the two largest units, like the old `DateUtil.age(millis, false, rh)` did: + * "2 days, 5 hours", "3 hours, 10 minutes", "7 minutes". Every piece comes from a translated + * template (`time_value_with_unit`, `values_with_comma`), so the translator controls the order and + * the separator. A negative age (clock moved back) is shown as 0 minutes. + */ +fun formatSensorAge(millis: Long, rh: TextResolver): String { + val duration = millis.coerceAtLeast(0L).milliseconds + val days = duration.inWholeDays + val hours = (duration - days.days).inWholeHours + val minutes = (duration - days.days - hours.hours).inWholeMinutes + return when { + days > 0 -> rh.gs( + InterfacesStrings.values_with_comma, + valueWithUnit(days, InterfacesStrings.unit_day, InterfacesStrings.unit_days, rh), + valueWithUnit(hours, InterfacesStrings.unit_hour, InterfacesStrings.unit_hours, rh) + ) + + hours > 0 -> rh.gs( + InterfacesStrings.values_with_comma, + valueWithUnit(hours, InterfacesStrings.unit_hour, InterfacesStrings.unit_hours, rh), + valueWithUnit(minutes, InterfacesStrings.unit_minute, InterfacesStrings.unit_minutes, rh) + ) + + else -> valueWithUnit(minutes, InterfacesStrings.unit_minute, InterfacesStrings.unit_minutes, rh) + } +} + +private fun valueWithUnit(value: Long, one: TextRef, many: TextRef, rh: TextResolver): String = + rh.gs(InterfacesStrings.time_value_with_unit, value.toString(), rh.gs(if (value == 1L) one else many)) diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt new file mode 100644 index 000000000000..6eb3f2d88ac7 --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt @@ -0,0 +1,80 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.source.SourceStrings + +enum class DexcomOnePlusBooleanKey( + override val key: String, + override val defaultValue: Boolean, + override val title: TextRef, + override val summary: TextRef? = null, + override val defaultedBySM: Boolean = false, + override val calculatedDefaultValue: Boolean = false, + override val engineeringModeOnly: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = true, + override val exportable: Boolean = false, +) : BooleanPreferenceKey { + + /** + * Put a missing SENSOR_CHANGE back for the running ONE+ session. + * + * On by default: without the event, the overview and the calibration plugin fall back to the + * previous sensor's age. Nothing is written while "create sensor change" is off. + */ + RepairMissingSensorChange( + key = "dexcom_oneplus_repair_missing_sensor_change", + defaultValue = true, + title = SourceStrings.dexcom_oneplus_repair_missing_sensor_change, + summary = SourceStrings.dexcom_oneplus_repair_missing_sensor_change_summary, + exportable = false, + ), + + /** + * Let the Status screen move the insertion time of the sensor that feeds the loop. + * + * On by default: the action is only offered on the Status screen and asks for a date first. + * Invalidating SENSOR_CHANGE events rewrites the sensor start; calibration rows are never + * removed. + */ + CorrectSensorStart( + key = "dexcom_oneplus_correct_sensor_start", + defaultValue = true, + title = SourceStrings.dexcom_oneplus_correct_sensor_start, + summary = SourceStrings.dexcom_oneplus_correct_sensor_start_summary, + exportable = false, + ), + + /** + * Replace the automatic session start with a SENSOR_CHANGE the user already logged. + * + * Done on every start and on the first accepted reading. That rolls the stored start back by + * up to 24 hours. On by default: a sensor inserted (and logged) before it is paired, or soaked + * before it is promoted, keeps its real age. Off: the plain automatic time is used. + */ + AnchorSessionToManualSensorChange( + key = "dexcom_oneplus_anchor_session_to_manual_sensor_change", + defaultValue = true, + title = SourceStrings.dexcom_oneplus_anchor_session_to_manual_sensor_change, + summary = SourceStrings.dexcom_oneplus_anchor_session_to_manual_sensor_change_summary, + exportable = false, + ), + + /** + * Switches the pre-soak sensor to production by itself, [DexcomOnePlusIntKey.AutoPromoteHours] + * after the pre-soak start, when its readings are recent and real. The promote button still works. + * + * Off by default: the switch stops the sensor in use, and the rest of its life is lost. + */ + AutoPromote( + key = "dexcom_oneplus_staging_auto_promote", + defaultValue = false, + title = SourceStrings.staging_auto_promote_title, + summary = SourceStrings.staging_auto_promote_summary, + ), +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntKey.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntKey.kt new file mode 100644 index 000000000000..410d32cf8807 --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntKey.kt @@ -0,0 +1,35 @@ +package app.aaps.plugins.source.keys + +import app.aaps.core.keys.UnitType +import app.aaps.core.keys.interfaces.BooleanPreferenceKey +import app.aaps.core.keys.interfaces.IntPreferenceKey +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.source.SourceStrings + +enum class DexcomOnePlusIntKey( + override val key: String, + override val defaultValue: Int, + override val min: Int, + override val max: Int, + override val title: TextRef, + override val dependency: BooleanPreferenceKey? = null, + override val unitType: UnitType = UnitType.NONE, + override val exportable: Boolean = true, +) : IntPreferenceKey { + + /** + * Hours after the pre-soak start before [DexcomOnePlusBooleanKey.AutoPromote] switches the sensor. + * + * 12 by default, the same settling time the promote button asks for. Below 12 the switch uses + * the "not settled" path of the button, with its own checks on recent readings. + */ + AutoPromoteHours( + key = "dexcom_oneplus_staging_auto_promote_hours", + defaultValue = 12, + min = 6, + max = 24, + title = SourceStrings.staging_auto_promote_hours_title, + dependency = DexcomOnePlusBooleanKey.AutoPromote, + unitType = UnitType.HOURS, + ), +} diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt new file mode 100644 index 000000000000..a57c366bfb5e --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt @@ -0,0 +1,39 @@ +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.core.keys.interfaces.TextRef +import app.aaps.plugins.source.SourceStrings + +enum class DexcomOnePlusIntentKey( + override val key: String, + override val title: TextRef, + override val summary: TextRef? = null, + override val preferenceType: PreferenceType = PreferenceType.CLICK, + 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 negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false +) : IntentPreferenceKey { + + Status( + key = "dexcom_oneplus_status", + title = SourceStrings.dexcom_oneplus_status_title, + summary = SourceStrings.dexcom_oneplus_status_summary + ), + Start( + key = "dexcom_oneplus_start", + title = SourceStrings.dexcom_oneplus_start_title, + summary = SourceStrings.dexcom_oneplus_start_summary + ), + Warmup( + key = "dexcom_oneplus_warmup", + title = SourceStrings.dexcom_oneplus_warmup_title, + summary = SourceStrings.dexcom_oneplus_warmup_summary + ) +} diff --git a/plugins/source/src/iosMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.ios.kt b/plugins/source/src/iosMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.ios.kt new file mode 100644 index 000000000000..1adf88e9e424 --- /dev/null +++ b/plugins/source/src/iosMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.ios.kt @@ -0,0 +1,16 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.DpSize + +/** + * Taken from the window rather than the device, which is the closest iOS equivalent. An iPad in + * split view therefore reports the pane it actually has, which is the number a layout wants anyway. + */ +@Composable +actual fun cgmWindowSizeDp(): DpSize { + val size = LocalWindowInfo.current.containerSize + return with(LocalDensity.current) { DpSize(size.width.toDp(), size.height.toDp()) } +} diff --git a/plugins/source/src/jvmMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.jvm.kt b/plugins/source/src/jvmMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.jvm.kt new file mode 100644 index 000000000000..deccb70f37b4 --- /dev/null +++ b/plugins/source/src/jvmMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.jvm.kt @@ -0,0 +1,16 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.runtime.Composable +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.unit.DpSize + +/** + * Taken from the window rather than the display, which is the right number on desktop: the layout + * cares about the space the app actually has, and the user can resize it to anything. + */ +@Composable +actual fun cgmWindowSizeDp(): DpSize { + val size = LocalWindowInfo.current.containerSize + return with(LocalDensity.current) { DpSize(size.width.toDp(), size.height.toDp()) } +} From 12be718140a5e7c2467a36cf69600018e82c6d2f Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Wed, 28 Oct 2026 19:14:11 +0100 Subject: [PATCH 05/27] Overview: show CGM warm-up and the second sensor in the status card A sensor that warms up, or a second sensor that warms up next to the one in use, could only be seen in the plugin's own screen. The Overview status card now shows two more rows, right below the sensor row. Both come from the generic CgmWarmupProvider / CgmSensorStatusProvider interfaces, so no vendor is named in the UI. For every other BG source both rows are null and the card is unchanged. Warm-up row - Minutes left and a bar that fills up. The time left comes from the wall-clock end time when the source gives one. The stored countdown is only used without it, because it goes stale between two radio windows. - Minutes are rounded up, so it never reads "0 min" while warming. With no time known it reads "Waiting". - A connection phase without a warm-up end time ahead is a radio reconnect, not a warm-up, so no row is shown for it. A reconnect during the warm-up keeps the end time and keeps the row. Second sensor row ("New sensor") - "Warming up", then "Ready in n h" while it settles, then "Ready to switch". The hours come from stagingSettleRemainingMs, rounded up. The rule for when a sensor may be used stays in the source; the UI has no copy of it. With no time left but not yet ready it reads "Waiting for readings", never "ready". - The level column shows the valid readings of the new sensor, the only sign that a sensor whose values do not go to the loop is working. - A Switch button only when the source says READY and commands are allowed. These two checks are in the UI only; the source checks its own rules again. It asks for confirmation, calls promoteStagingToProduction(allowEarly = false) off the main thread, and shows the result in a dialog. Each PromotionResult and each refusal reason has its own text, including OkBoundFailed (old calibrations could not be set aside) and OkFollowUpFailed (connection not started / sensor in use could not be read back). An exception is logged and the user is told to check which sensor is in use. A second tap while a switch runs does nothing. An early switch is not offered here; it stays on the source's own screen with its warning. Refresh - A 10 s tick, only while the card is on screen, rebuilds just these two rows from the source's StateFlows (no database read). It does nothing while no source reports either row and no such row is shown, and it removes a row on the next tick once the source stops reporting it. StatusViewModel gets an AAPSLogger. 19 English strings in ui, with comments where there are placeholders. Tests (androidHostTest): 20 new StatusViewModelTest cases (end time wins over the stored countdown, stored countdown without end time, rounding, reconnect is not a warm-up, row disappears after warm-up, hour ceiling, waiting for readings, READY state, switch only when READY, one wording per result, switch is never early, a throw is shown, the tick changes nothing for a plain source, a row goes away on the next tick, a second tap starts no second switch, row and button gone after a switch), 2 new StatusSectionContentTest cases and a new OverviewStatusSectionSwitchTest (5 cases: no button when not ready or commands not allowed, confirm before switching, cancel, result dialog). These are unit tests only; no test on a real phone is claimed for this branch. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../OverviewStatusSectionSwitchTest.kt | 125 +++++ .../statusLights/StatusSectionContentTest.kt | 67 +++ .../statusLights/StatusViewModelTest.kt | 465 +++++++++++++++++- .../testing/OverviewViewModelFixture.kt | 2 +- ui/src/androidMain/res/values/strings.xml | 21 + .../compose/overview/OverviewScreenSplit.kt | 6 + .../compose/overview/OverviewScreenStacked.kt | 6 + .../compose/overview/OverviewScreenTablet.kt | 6 + .../compose/overview/OverviewStatusSection.kt | 48 +- .../overview/OverviewStatusSectionPreviews.kt | 37 ++ .../overview/statusLights/StatusComponents.kt | 30 +- .../statusLights/StatusComponentsPreviews.kt | 46 ++ .../overview/statusLights/StatusUiState.kt | 15 +- .../overview/statusLights/StatusViewModel.kt | 211 +++++++- 14 files changed, 1074 insertions(+), 11 deletions(-) create mode 100644 ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionSwitchTest.kt diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionSwitchTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionSwitchTest.kt new file mode 100644 index 000000000000..c3dd4452b456 --- /dev/null +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionSwitchTest.kt @@ -0,0 +1,125 @@ +package app.aaps.ui.compose.overview + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Circle +import androidx.compose.material3.MaterialTheme +import androidx.compose.ui.test.assertCountEquals +import androidx.compose.ui.test.assertIsDisplayed +import androidx.compose.ui.test.hasText +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.core.ui.compose.StatusLevel +import app.aaps.core.ui.compose.preference.PreferenceSubScreenDef +import app.aaps.ui.UiStringIds +import app.aaps.ui.compose.overview.statusLights.StatusItem +import com.google.common.truth.Truth.assertThat +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import org.robolectric.annotation.GraphicsMode + +/** + * The Switch button of the second sensor row in [OverviewStatusSection]: when it is shown, that it + * asks before it switches, and that the result is shown. + */ +@RunWith(RobolectricTestRunner::class) +@GraphicsMode(GraphicsMode.Mode.NATIVE) +@Config(sdk = [35]) +class OverviewStatusSectionSwitchTest { + + @get:Rule + val compose = createComposeRule() + + // What MainApp does at startup. Without it the ui strings render as their raw names, and this + // class passed only when another test class had registered them first. + @Before + fun setUp() { + TextRefIdRegistry.register("ui") { name -> UiStringIds.idOf(name) } + } + + private var promoted = 0 + private var dismissed = 0 + + private fun setSection(canPromote: Boolean, commandsAllowed: Boolean, promotionMessage: String? = null) { + compose.setContent { + MaterialTheme { + OverviewStatusSection( + sensorStatus = StatusItem(label = "Sensor", age = "9d4h", icon = Icons.Default.Circle), + insulinStatus = null, + cannulaStatus = null, + batteryStatus = null, + secondSensorStatus = StatusItem( + label = "New sensor", age = "Ready to switch", ageStatus = StatusLevel.NORMAL, + level = "Readings: 72", icon = Icons.Default.Circle, compactLevel = false + ), + canPromoteSecondSensor = canPromote, + onPromoteSecondSensor = { promoted++ }, + promotionMessage = promotionMessage, + onDismissPromotionMessage = { dismissed++ }, + showFill = false, + showPumpBatteryChange = false, + commandsAllowed = commandsAllowed, + onNavigate = {}, + statusLightsDef = PreferenceSubScreenDef(key = "test", titleResId = 0), + expanded = true, + onExpandedChange = {} + ) + } + } + } + + @Test + fun noSwitchWhileTheSecondSensorIsNotReady() { + setSection(canPromote = false, commandsAllowed = true) + + compose.onNodeWithText("Ready to switch").assertIsDisplayed() + compose.onAllNodes(hasText("Switch")).assertCountEquals(0) + } + + @Test + fun noSwitchWhenCommandsAreNotAllowed() { + setSection(canPromote = true, commandsAllowed = false) + + compose.onNodeWithText("Ready to switch").assertIsDisplayed() + compose.onAllNodes(hasText("Switch")).assertCountEquals(0) + } + + @Test + fun theSwitchIsConfirmedBeforeItIsDone() { + setSection(canPromote = true, commandsAllowed = true) + + compose.onNodeWithText("Switch").performClick() + // Nothing happens before the user confirms. + assertThat(promoted).isEqualTo(0) + compose.onNodeWithText("Use the new sensor for the loop from now on?", substring = true).assertIsDisplayed() + + compose.onNodeWithText("OK").performClick() + assertThat(promoted).isEqualTo(1) + } + + @Test + fun cancelDoesNotSwitch() { + setSection(canPromote = true, commandsAllowed = true) + + compose.onNodeWithText("Switch").performClick() + compose.onNodeWithText("Cancel").performClick() + + assertThat(promoted).isEqualTo(0) + compose.onAllNodes(hasText("Use the new sensor for the loop from now on?", substring = true)).assertCountEquals(0) + } + + @Test + fun theResultIsShownUntilTheUserClosesIt() { + setSection(canPromote = false, commandsAllowed = true, promotionMessage = "The loop is busy right now.") + + compose.onNodeWithText("The loop is busy right now.").assertIsDisplayed() + compose.onNodeWithText("OK").performClick() + + assertThat(dismissed).isEqualTo(1) + } +} diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusSectionContentTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusSectionContentTest.kt index f94eca5ca20f..1597c34044ca 100644 --- a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusSectionContentTest.kt +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusSectionContentTest.kt @@ -11,11 +11,17 @@ import androidx.compose.ui.test.hasContentDescription import androidx.compose.ui.test.hasText 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.core.ui.compose.StatusLevel import app.aaps.core.ui.compose.icons.IcCannulaChange import app.aaps.core.ui.compose.icons.IcCgmInsert +import app.aaps.core.ui.compose.icons.IcGenericCgm import app.aaps.core.ui.compose.icons.IcPumpBattery import app.aaps.core.ui.compose.icons.IcPumpCartridge +import app.aaps.ui.UiStringIds +import com.google.common.truth.Truth.assertThat +import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -32,6 +38,13 @@ class StatusSectionContentTest { @get:Rule val compose = createComposeRule() + // What MainApp does at startup. Without it the ui strings render as their raw names, and this + // class passed only when another test class had registered them first. + @Before + fun setUp() { + TextRefIdRegistry.register("ui") { name -> UiStringIds.idOf(name) } + } + @Test fun rendersAllStatusItems() { compose.setContent { @@ -120,4 +133,58 @@ class StatusSectionContentTest { compose.onAllNodes(SemanticsMatcher.keyIsDefined(SemanticsProperties.ProgressBarRangeInfo)) .assertCountEquals(0) } + + @Test + fun rendersWarmUpAndSecondSensorRows() { + compose.setContent { + MaterialTheme { + StatusSectionContent( + sensorStatus = StatusItem( + label = "Sensor", age = "9d4h", ageStatus = StatusLevel.WARNING, agePercent = 0.9f, icon = IcCgmInsert + ), + insulinStatus = null, + cannulaStatus = null, + batteryStatus = null, + warmUpStatus = StatusItem( + label = "Warm-up", age = "23 min", agePercent = 0.24f, icon = IcCgmInsert, compactLevel = false + ), + secondSensorStatus = StatusItem( + label = "New sensor", age = "Ready in 8 h", agePercent = 0.33f, level = "Readings: 12", + icon = IcGenericCgm, compactLevel = false + ) + ) + } + } + compose.onNodeWithText("Warm-up").assertIsDisplayed() + compose.onNodeWithText("23 min").assertIsDisplayed() + compose.onNodeWithText("New sensor").assertIsDisplayed() + compose.onNodeWithText("Ready in 8 h").assertIsDisplayed() + compose.onNodeWithText("Readings: 12").assertIsDisplayed() + // Not ready: no Switch button at all. + compose.onAllNodes(hasText("Switch")).assertCountEquals(0) + } + + @Test + fun theSwitchButtonIsShownOnlyWithACallbackAndCallsIt() { + var clicks = 0 + compose.setContent { + MaterialTheme { + StatusSectionContent( + sensorStatus = null, + insulinStatus = null, + cannulaStatus = null, + batteryStatus = null, + secondSensorStatus = StatusItem( + label = "New sensor", age = "Ready to switch", ageStatus = StatusLevel.NORMAL, + level = "Readings: 72", icon = IcGenericCgm, compactLevel = false + ), + onPromoteSecondSensorClick = { clicks++ } + ) + } + } + // Named after its row, like the other row buttons. + compose.onNode(hasContentDescription("New sensor") and hasClickAction()).assertIsDisplayed() + compose.onNodeWithText("Switch").performClick() + assertThat(clicks).isEqualTo(1) + } } diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModelTest.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModelTest.kt index 3d7063cf1a37..a93fd98164bf 100644 --- a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModelTest.kt +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/overview/statusLights/StatusViewModelTest.kt @@ -5,17 +5,27 @@ import app.aaps.core.data.model.TE import app.aaps.core.data.pump.defs.PumpDescription import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.pump.PumpInsulin import app.aaps.core.interfaces.pump.PumpWithConcentration import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.resources.TextResolver 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.BgSource +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.interfaces.source.CgmSensorStatusProvider +import app.aaps.core.interfaces.source.CgmStagingEvidence +import app.aaps.core.interfaces.source.CgmWarmupProvider +import app.aaps.core.interfaces.source.CgmWarmupStatus +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.StagingState import app.aaps.core.interfaces.stats.TddCalculator import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter @@ -23,12 +33,14 @@ import app.aaps.core.interfaces.utils.TimeDiff import app.aaps.core.keys.interfaces.Preferences import app.aaps.core.keys.interfaces.TextRef import app.aaps.core.ui.CoreUiStrings +import app.aaps.core.ui.compose.StatusLevel import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job +import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow @@ -37,7 +49,11 @@ import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestCoroutineScheduler import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import kotlinx.coroutines.withTimeout @@ -68,6 +84,7 @@ internal class StatusViewModelTest { @Mock private lateinit var tddCalculator: TddCalculator @Mock private lateinit var decimalFormatter: DecimalFormatter @Mock private lateinit var processedDeviceStatusData: ProcessedDeviceStatusData + @Mock private lateinit var aapsLogger: AAPSLogger private val teChanges = MutableSharedFlow>() private val reservoir = MutableStateFlow(PumpInsulin(10.0)) @@ -92,9 +109,9 @@ internal class StatusViewModelTest { @AfterEach fun tearDown() = Dispatchers.resetMain() - private fun newViewModel() = StatusViewModel( - rh, activePlugin, profileFunction, config, persistenceLayer, dateUtil, rxBus, preferences, - tddCalculator, decimalFormatter, processedDeviceStatusData + private fun newViewModel(textResolver: TextResolver = rh) = StatusViewModel( + textResolver, activePlugin, profileFunction, config, persistenceLayer, dateUtil, rxBus, preferences, + tddCalculator, decimalFormatter, processedDeviceStatusData, aapsLogger ) @Test @@ -207,6 +224,441 @@ internal class StatusViewModelTest { screen.cancelAndJoin() } + // ---- CGM warm-up and second sensor rows ---- + + @Test + fun `a source that reports neither warm-up nor a second sensor gets no extra row`() { + whenever(activePlugin.activeBgSource).thenReturn(PlainBgSource()) + val viewModel = newViewModel(NameText) + + assertThat(viewModel.buildWarmUpStatus()).isNull() + assertThat(viewModel.buildSecondSensorStatus()).isNull() + assertThat(viewModel.canPromoteSecondSensor()).isFalse() + viewModel.refreshCgmRows() + assertThat(viewModel.uiState.value).isEqualTo(StatusUiState()) + } + + @Test + fun `warm-up row counts down from the wall-clock end time, not from the stored countdown`() { + val source = givenCgmSource() + source.warmupStatus.value = warming( + // Stale on purpose: it was stored at the last radio window. The end time must win. + remainingMs = 5 * MINUTE_MS, + endsAtEpochMs = NOW + 23 * MINUTE_MS, + totalMs = 30 * MINUTE_MS + ) + + val item = newViewModel(NameText).buildWarmUpStatus() + + assertThat(item).isNotNull() + assertThat(item!!.label).isEqualTo("overview_cgm_warmup_label") + assertThat(item.age).isEqualTo("format_mins(23)") + // 7 of the 30 minutes are done. + assertThat(item.agePercent).isWithin(0.001f).of(7f / 30f) + } + + @Test + fun `warm-up row uses the stored countdown when there is no end time`() { + val source = givenCgmSource() + source.warmupStatus.value = warming(remainingMs = 12 * MINUTE_MS, endsAtEpochMs = null, totalMs = null) + + val item = newViewModel(NameText).buildWarmUpStatus() + + assertThat(item!!.age).isEqualTo("format_mins(12)") + // No total length known: no bar. + assertThat(item.agePercent).isEqualTo(-1f) + } + + @Test + fun `warm-up minutes are rounded up and never read 0 while warming`() { + val source = givenCgmSource() + val viewModel = newViewModel(NameText) + + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = NOW + 22 * MINUTE_MS + 1_000L) + assertThat(viewModel.buildWarmUpStatus()!!.age).isEqualTo("format_mins(23)") + + // The end time has passed but the source still says warming: no "0 min", it waits. + source.warmupStatus.value = warming(remainingMs = 3 * MINUTE_MS, endsAtEpochMs = NOW - 1_000L) + assertThat(viewModel.buildWarmUpStatus()!!.age).isEqualTo("overview_cgm_warmup_waiting") + + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = null) + assertThat(viewModel.buildWarmUpStatus()!!.age).isEqualTo("overview_cgm_warmup_waiting") + } + + @Test + fun `a reconnect without a warm-up end time ahead is not shown as a warm-up`() { + val source = givenCgmSource() + val viewModel = newViewModel(NameText) + + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = null).copy(phase = CgmWarmupStatus.Phase.RECONNECTING) + assertThat(viewModel.buildWarmUpStatus()).isNull() + + // A reconnect during the warm-up keeps the warm-up deadline, and then the row stays. + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = NOW + 10 * MINUTE_MS) + .copy(phase = CgmWarmupStatus.Phase.RECONNECTING) + assertThat(viewModel.buildWarmUpStatus()!!.age).isEqualTo("format_mins(10)") + } + + @Test + fun `warm-up row disappears once the warm-up is over`() { + val source = givenCgmSource() + val viewModel = newViewModel(NameText) + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = NOW + MINUTE_MS) + viewModel.refreshCgmRows() + assertThat(viewModel.uiState.value.warmUpStatus).isNotNull() + + // The source reports nothing any more once the sensor is ready. + source.warmupStatus.value = null + viewModel.refreshCgmRows() + assertThat(viewModel.uiState.value.warmUpStatus).isNull() + + // An inactive status is the same as none. + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = NOW + MINUTE_MS).copy(active = false) + viewModel.refreshCgmRows() + assertThat(viewModel.uiState.value.warmUpStatus).isNull() + } + + @Test + fun `second sensor row is absent while no second sensor is staged`() { + givenCgmSource() + + assertThat(newViewModel(NameText).buildSecondSensorStatus()).isNull() + } + + @Test + fun `second sensor in warm-up says so and shows its readings`() { + val source = givenCgmSource() + source.stagingState.value = StagingState.WARMUP + source.stagingEvidence.value = CgmStagingEvidence(validCount = 0, lastValueMgdl = null, lastValueAtEpochMs = null) + + val item = newViewModel(NameText).buildSecondSensorStatus()!! + + assertThat(item.label).isEqualTo("overview_second_sensor_label") + assertThat(item.age).isEqualTo("overview_second_sensor_warmup") + assertThat(item.level).isEqualTo("overview_second_sensor_readings(0)") + assertThat(item.agePercent).isEqualTo(-1f) + } + + @Test + fun `settling second sensor shows whole hours left, rounded up, from the time the source publishes`() { + val source = givenCgmSource() + val viewModel = newViewModel(NameText) + source.stagingState.value = StagingState.SETTLING + source.stagingLifecycle.value = stagingLifecycle(ageMs = 4 * HOUR_MS) + source.stagingEvidence.value = CgmStagingEvidence(validCount = 12, lastValueMgdl = 118.0, lastValueAtEpochMs = NOW) + + // 8 h 5 min left reads 9 h: the wait is not over until it is over. + source.stagingSettleRemainingMs.value = 8 * HOUR_MS + 5 * MINUTE_MS + val item = viewModel.buildSecondSensorStatus()!! + assertThat(item.age).isEqualTo("overview_second_sensor_ready_in(units_format_hours(9))") + assertThat(item.level).isEqualTo("overview_second_sensor_readings(12)") + assertThat(item.agePercent).isWithin(0.001f).of(4f / (4f + 8f + 5f / 60f)) + + source.stagingSettleRemainingMs.value = 8 * HOUR_MS + assertThat(viewModel.buildSecondSensorStatus()!!.age).isEqualTo("overview_second_sensor_ready_in(units_format_hours(8))") + + // One minute left still reads 1 h, never 0 h. + source.stagingSettleRemainingMs.value = MINUTE_MS + assertThat(viewModel.buildSecondSensorStatus()!!.age).isEqualTo("overview_second_sensor_ready_in(units_format_hours(1))") + + // A different rule in the source gives a different time here: this screen has no copy of it. + source.stagingSettleRemainingMs.value = 20 * HOUR_MS + assertThat(viewModel.buildSecondSensorStatus()!!.age).isEqualTo("overview_second_sensor_ready_in(units_format_hours(20))") + } + + @Test + fun `settling second sensor with no time left waits for readings and does not say ready`() { + val source = givenCgmSource() + source.stagingState.value = StagingState.SETTLING + source.stagingSettleRemainingMs.value = null + + val viewModel = newViewModel(NameText) + + assertThat(viewModel.buildSecondSensorStatus()!!.age).isEqualTo("overview_second_sensor_waiting_readings") + assertThat(viewModel.canPromoteSecondSensor()).isFalse() + } + + @Test + fun `ready second sensor is marked normal, drops the countdown and offers the switch`() { + val source = givenCgmSource() + source.stagingState.value = StagingState.READY + source.stagingLifecycle.value = stagingLifecycle(ageMs = 13 * HOUR_MS) + source.stagingEvidence.value = CgmStagingEvidence(validCount = 72, lastValueMgdl = 110.0, lastValueAtEpochMs = NOW) + val viewModel = newViewModel(NameText) + + viewModel.refreshCgmRows() + + val state = viewModel.uiState.value + assertThat(state.secondSensorStatus!!.age).isEqualTo("overview_second_sensor_ready") + assertThat(state.secondSensorStatus.ageStatus).isEqualTo(StatusLevel.NORMAL) + assertThat(state.secondSensorStatus.agePercent).isEqualTo(-1f) + assertThat(state.secondSensorStatus.level).isEqualTo("overview_second_sensor_readings(72)") + assertThat(state.canPromoteSecondSensor).isTrue() + } + + @Test + fun `the switch is offered only once the second sensor is ready`() { + val source = givenCgmSource() + val viewModel = newViewModel(NameText) + + for (state in StagingState.entries) { + source.stagingState.value = state + viewModel.refreshCgmRows() + assertThat(viewModel.canPromoteSecondSensor()).isEqualTo(state == StagingState.READY) + assertThat(viewModel.uiState.value.canPromoteSecondSensor).isEqualTo(state == StagingState.READY) + } + } + + @Test + fun `a source with only a warm-up never offers the switch`() { + val source = WarmupOnlyBgSource() + whenever(activePlugin.activeBgSource).thenReturn(source) + whenever(dateUtil.now()).thenReturn(NOW) + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = NOW + MINUTE_MS) + val viewModel = newViewModel(NameText) + + viewModel.refreshCgmRows() + + assertThat(viewModel.uiState.value.warmUpStatus).isNotNull() + assertThat(viewModel.uiState.value.secondSensorStatus).isNull() + assertThat(viewModel.uiState.value.canPromoteSecondSensor).isFalse() + } + + @Test + fun `every switch result has its own wording`() { + val viewModel = newViewModel(NameText) + val results = listOf( + PromotionResult.Ok, + PromotionResult.OkBoundFailed, + PromotionResult.OkFollowUpFailed(productionIdentityPresent = true), + PromotionResult.OkFollowUpFailed(productionIdentityPresent = false) + ) + PromotionRejectReason.entries.map { PromotionResult.Rejected(it) } + + val messages = results.map { viewModel.promotionMessage(it) } + + // One text per result: a user who is refused, or whose switch only half worked, must know why. + assertThat(messages).containsNoDuplicates() + assertThat(messages).hasSize(8) + assertThat(viewModel.promotionMessage(PromotionResult.Ok)).isEqualTo("overview_second_sensor_switch_ok") + assertThat(viewModel.promotionMessage(PromotionResult.OkBoundFailed)) + .isEqualTo("overview_second_sensor_switch_ok_calibration_failed") + } + + @Test + fun `the switch asks the source for a normal switch, never an early one, and shows the result`() = runBlocking { + Dispatchers.setMain(UnconfinedTestDispatcher()) + val source = givenCgmSource() + source.stagingState.value = StagingState.READY + source.result = PromotionResult.Rejected(PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE) + val viewModel = newViewModel(NameText) + + viewModel.promoteSecondSensor() + val message = withTimeoutOrNull(20_000) { + while (viewModel.uiState.value.promotionMessage == null) delay(10) + viewModel.uiState.value.promotionMessage + } + + assertThat(message).isEqualTo("overview_second_sensor_switch_refused_no_recent_reading") + assertThat(source.calls).containsExactly(false) + viewModel.clearPromotionMessage() + assertThat(viewModel.uiState.value.promotionMessage).isNull() + } + + @Test + fun `a switch that throws tells the user to check which sensor is in use`() = runBlocking { + Dispatchers.setMain(UnconfinedTestDispatcher()) + val source = givenCgmSource() + source.stagingState.value = StagingState.READY + source.failure = IllegalStateException("boom") + val viewModel = newViewModel(NameText) + + viewModel.promoteSecondSensor() + val message = withTimeoutOrNull(20_000) { + while (viewModel.uiState.value.promotionMessage == null) delay(10) + viewModel.uiState.value.promotionMessage + } + + assertThat(message).isEqualTo("overview_second_sensor_switch_error") + } + + /** + * The 10 s tick runs while the card is shown. For a source with no warm-up and no second sensor + * it must not change anything. Virtual time, and a bounded window: the ticker re-arms itself, + * so it never goes idle. + */ + @Test + fun `the cgm tick leaves the state alone for a source with neither row`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val reads = AtomicInteger(0) + val plain = PlainBgSource() + whenever(activePlugin.activeBgSource).thenAnswer { reads.incrementAndGet(); plain } + givenFullRefreshNeverEnds() + val viewModel = newViewModel(NameText) + val emitted = mutableListOf() + backgroundScope.launch { viewModel.uiState.collect { emitted += it } } + runCurrent() + val before = viewModel.uiState.value + val readsBefore = reads.get() + + // Four more ticks (10, 20, 30, 40 s), and still before the 60 s full refresh. + advanceTimeBy(4 * CGM_TICK_MS) + runCurrent() + + assertThat(reads.get() - readsBefore).isAtLeast(4) + assertThat(viewModel.uiState.value).isSameInstanceAs(before) + assertThat(emitted).containsExactly(StatusUiState()) + } + + @Test + fun `a warm-up row goes away on the next tick once the source stops reporting it`() = runTest { + Dispatchers.setMain(StandardTestDispatcher(testScheduler)) + val source = givenCgmSource() + givenFullRefreshNeverEnds() + source.warmupStatus.value = warming(remainingMs = null, endsAtEpochMs = NOW + 10 * MINUTE_MS) + val viewModel = newViewModel(NameText) + backgroundScope.launch { viewModel.uiState.collect { } } + runCurrent() + assertThat(viewModel.uiState.value.warmUpStatus).isNotNull() + + source.warmupStatus.value = null + advanceTimeBy(CGM_TICK_MS) + runCurrent() + + assertThat(viewModel.uiState.value.warmUpStatus).isNull() + } + + @Test + fun `a second tap while the switch is running does not start another switch`() = runBlocking { + // Not Unconfined: the first switch must really be waiting when the second tap comes. + val scheduler = TestCoroutineScheduler() + Dispatchers.setMain(StandardTestDispatcher(scheduler)) + val source = givenCgmSource() + source.stagingState.value = StagingState.READY + val gate = CompletableDeferred() + source.gate = gate + val viewModel = newViewModel(NameText) + + viewModel.promoteSecondSensor() + scheduler.runCurrent() + withTimeout(20_000) { while (synchronized(source.calls) { source.calls.size } < 1) delay(10) } + viewModel.promoteSecondSensor() + scheduler.runCurrent() + gate.complete(Unit) + val message = withTimeoutOrNull(20_000) { + while (viewModel.uiState.value.promotionMessage == null) { + scheduler.runCurrent() + delay(10) + } + viewModel.uiState.value.promotionMessage + } + + assertThat(message).isEqualTo("overview_second_sensor_switch_ok") + assertThat(source.calls).containsExactly(false) + } + + @Test + fun `after a successful switch the second sensor row and its button are gone`() = runBlocking { + Dispatchers.setMain(UnconfinedTestDispatcher()) + val source = givenCgmSource() + source.stagingState.value = StagingState.READY + source.stagingEvidence.value = CgmStagingEvidence(validCount = 72, lastValueMgdl = 110.0, lastValueAtEpochMs = NOW) + val viewModel = newViewModel(NameText) + viewModel.refreshCgmRows() + assertThat(viewModel.uiState.value.secondSensorStatus).isNotNull() + assertThat(viewModel.uiState.value.canPromoteSecondSensor).isTrue() + + viewModel.promoteSecondSensor() + val message = withTimeoutOrNull(20_000) { + while (viewModel.uiState.value.promotionMessage == null) delay(10) + viewModel.uiState.value.promotionMessage + } + + assertThat(message).isEqualTo("overview_second_sensor_switch_ok") + assertThat(viewModel.uiState.value.secondSensorStatus).isNull() + assertThat(viewModel.uiState.value.canPromoteSecondSensor).isFalse() + } + + /** + * The full refresh reads the pump, then the database. Here that read never returns, so the full + * refresh never writes the state, and only the CGM tick can change it. + */ + private suspend fun givenFullRefreshNeverEnds() { + val pump = mock() + whenever(activePlugin.activePump).thenReturn(pump) + whenever(pump.pumpDescription).thenReturn(PumpDescription()) + whenever(pump.batteryLevel).thenReturn(MutableStateFlow(null)) + whenever(pump.reservoirLevel).thenReturn(reservoir) + whenever(persistenceLayer.getLastTherapyRecordUpToNow(any())).doSuspendableAnswer { awaitCancellation() } + } + + private fun givenCgmSource(): FakeStagingBgSource { + val source = FakeStagingBgSource() + whenever(activePlugin.activeBgSource).thenReturn(source) + whenever(dateUtil.now()).thenReturn(NOW) + return source + } + + private fun warming(remainingMs: Long?, endsAtEpochMs: Long?, totalMs: Long? = null) = CgmWarmupStatus( + active = true, + phase = CgmWarmupStatus.Phase.WARMING, + remainingMs = remainingMs, + endsAtEpochMs = endsAtEpochMs, + totalMs = totalMs + ) + + private fun stagingLifecycle(ageMs: Long) = CgmSensorLifecycle( + startedAtEpochMs = NOW - ageMs, + ageMs = ageMs, + endOfLife = false + ) + + /** Gives each string its resource name, and the arguments in brackets, so a test reads what was chosen. */ + private object NameText : TextResolver { + + override fun gs(ref: TextRef): String = (ref as TextRef.Named).name + override fun gs(ref: TextRef, vararg args: Any?): String = gs(ref) + args.joinToString(",", "(", ")") + override fun gsNotLocalised(ref: TextRef): String = gs(ref) + } + + private class PlainBgSource : BgSource { + + override val sensorBatteryLevel = -1 + } + + private class WarmupOnlyBgSource : BgSource, CgmWarmupProvider { + + override val sensorBatteryLevel = -1 + override val warmupStatus = MutableStateFlow(null) + } + + /** BG source with a warm-up and a second sensor slot, so both rows can be built. */ + private class FakeStagingBgSource : BgSource, CgmSensorStatusProvider { + + override val sensorBatteryLevel = -1 + override val warmupStatus = MutableStateFlow(null) + override val lifecycle = MutableStateFlow(null) + override val stagingLifecycle = MutableStateFlow(null) + override val stagingState = MutableStateFlow(StagingState.ABSENT) + override val stagingEvidence = MutableStateFlow(null) + override val stagingSettleRemainingMs = MutableStateFlow(null) + + var result: PromotionResult = PromotionResult.Ok + var failure: Exception? = null + val calls = mutableListOf() + + /** When set, the switch waits here, so a test can tap again while it is still running. */ + var gate: CompletableDeferred? = null + + override suspend fun promoteStagingToProduction(allowEarly: Boolean): PromotionResult { + synchronized(calls) { calls.add(allowEarly) } + gate?.await() + failure?.let { throw it } + // Like the real source: after a switch there is no second sensor any more. + if (result == PromotionResult.Ok) stagingState.value = StagingState.ABSENT + return result + } + } + /** Collects the state the way a screen does. */ private fun CoroutineScope.show(viewModel: StatusViewModel): Job = launch(Dispatchers.Unconfined) { viewModel.uiState.collect { } } @@ -261,5 +713,12 @@ internal class StatusViewModelTest { /** How long a test waits to be sure that something did NOT happen. */ const val QUIET_MS = 300L + + const val MINUTE_MS = 60_000L + const val HOUR_MS = 60 * MINUTE_MS + + /** Same period as the CGM tick in [StatusViewModel]. */ + const val CGM_TICK_MS = 10_000L + const val NOW = 1_700_000_000_000L } } diff --git a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/testing/OverviewViewModelFixture.kt b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/testing/OverviewViewModelFixture.kt index eba9ed74fd71..593800b74ae9 100644 --- a/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/testing/OverviewViewModelFixture.kt +++ b/ui/src/androidHostTest/kotlin/app/aaps/ui/compose/testing/OverviewViewModelFixture.kt @@ -197,7 +197,7 @@ internal class OverviewViewModelFixture(private val screen: AapsScreenFixture) { val statusViewModel: StatusViewModel by lazy { StatusViewModel( rh, activePlugin, profileFunction, screen.config, persistenceLayer, screen.dateUtil, rxBus, - screen.preferences, tddCalculator, decimalFormatter, processedDeviceStatusData + screen.preferences, tddCalculator, decimalFormatter, processedDeviceStatusData, aapsLogger ) } diff --git a/ui/src/androidMain/res/values/strings.xml b/ui/src/androidMain/res/values/strings.xml index 30044494a0be..30b1d0268d3b 100644 --- a/ui/src/androidMain/res/values/strings.xml +++ b/ui/src/androidMain/res/values/strings.xml @@ -383,4 +383,25 @@ Mark sensor change %1$s, %2$s + + Warm-up + Waiting + New sensor + Warming up + Ready in %1$s + Waiting for readings + Ready to switch + Readings: %1$d + Switch + Use the new sensor for the loop from now on? The loop stops using the sensor it uses now. + The loop now uses the new sensor. + Calibrations you entered for the old sensor could not be removed, so they may still be used for the new sensor. Check your calibrations. + The loop now uses the new sensor, but the connection to it could not be started. Keep the phone near the sensor and open the sensor status screen to check that readings come in. + The switch was made, but a step after it failed and the sensor in use could not be read back. Open the sensor status screen and check which sensor is in use. + There is no new sensor to switch to. Nothing was changed. + The new sensor has not settled long enough yet. Nothing was changed. + The new sensor has not sent enough valid readings yet. Nothing was changed. + The new sensor has not sent a reading in the last minutes. Nothing was changed. Wait for its next reading and try again. + Something went wrong during the switch. Open the sensor status screen and check which sensor is in use. + diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenSplit.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenSplit.kt index 1360c93de14f..1a7677a5077b 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenSplit.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenSplit.kt @@ -180,6 +180,12 @@ fun OverviewScreenSplit( insulinStatus = statusState.insulinStatus, cannulaStatus = statusState.cannulaStatus, batteryStatus = statusState.batteryStatus, + warmUpStatus = statusState.warmUpStatus, + secondSensorStatus = statusState.secondSensorStatus, + canPromoteSecondSensor = statusState.canPromoteSecondSensor, + onPromoteSecondSensor = { statusViewModel.promoteSecondSensor() }, + promotionMessage = statusState.promotionMessage, + onDismissPromotionMessage = { statusViewModel.clearPromotionMessage() }, showFill = statusState.showFill, showPumpBatteryChange = statusState.showPumpBatteryChange, commandsAllowed = commandsAllowed, diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenStacked.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenStacked.kt index b6dcea3ce936..40cc21bc977d 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenStacked.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenStacked.kt @@ -152,6 +152,12 @@ fun OverviewScreenStacked( insulinStatus = statusState.insulinStatus, cannulaStatus = statusState.cannulaStatus, batteryStatus = statusState.batteryStatus, + warmUpStatus = statusState.warmUpStatus, + secondSensorStatus = statusState.secondSensorStatus, + canPromoteSecondSensor = statusState.canPromoteSecondSensor, + onPromoteSecondSensor = { statusViewModel.promoteSecondSensor() }, + promotionMessage = statusState.promotionMessage, + onDismissPromotionMessage = { statusViewModel.clearPromotionMessage() }, showFill = statusState.showFill, showPumpBatteryChange = statusState.showPumpBatteryChange, commandsAllowed = commandsAllowed, diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenTablet.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenTablet.kt index 24f8beacab20..2cc8dc524937 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenTablet.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewScreenTablet.kt @@ -185,6 +185,12 @@ fun OverviewScreenTablet( insulinStatus = statusState.insulinStatus, cannulaStatus = statusState.cannulaStatus, batteryStatus = statusState.batteryStatus, + warmUpStatus = statusState.warmUpStatus, + secondSensorStatus = statusState.secondSensorStatus, + canPromoteSecondSensor = statusState.canPromoteSecondSensor, + onPromoteSecondSensor = { statusViewModel.promoteSecondSensor() }, + promotionMessage = statusState.promotionMessage, + onDismissPromotionMessage = { statusViewModel.clearPromotionMessage() }, showFill = statusState.showFill, showPumpBatteryChange = statusState.showPumpBatteryChange, commandsAllowed = commandsAllowed, diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSection.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSection.kt index 5ccbf6fb8442..fd23737e490f 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSection.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSection.kt @@ -48,6 +48,8 @@ import app.aaps.core.ui.CoreUiStrings import app.aaps.core.ui.compose.AapsCard import app.aaps.core.ui.compose.LocalClientRole import app.aaps.core.ui.compose.StatusLevel +import app.aaps.core.ui.compose.dialogs.OkCancelDialog +import app.aaps.core.ui.compose.dialogs.OkDialog import app.aaps.core.ui.compose.navigation.NavigationRequest import app.aaps.core.ui.compose.preference.PreferenceSheetContent import app.aaps.core.ui.compose.preference.PreferenceSubScreenDef @@ -55,12 +57,14 @@ import app.aaps.core.ui.compose.statusLevelToColor import app.aaps.core.ui.compose.statusLevelToDescription import app.aaps.core.ui.compose.stringResource import app.aaps.core.ui.compose.stringResourceOrNull +import app.aaps.ui.UiStrings import app.aaps.ui.compose.overview.statusLights.StatusItem import app.aaps.ui.compose.overview.statusLights.StatusSectionContent /** * @see OverviewStatusSectionCollapsedPreview * @see OverviewStatusSectionExpandedPreview + * @see OverviewStatusSectionCgmRowsPreview */ @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -69,6 +73,18 @@ fun OverviewStatusSection( insulinStatus: StatusItem?, cannulaStatus: StatusItem?, batteryStatus: StatusItem?, + // Only set while a CGM source reports a warm-up, or a second sensor that warms up next to the one + // in use. Null for every other source, so nothing changes for them. + warmUpStatus: StatusItem? = null, + secondSensorStatus: StatusItem? = null, + // The second sensor is ready, so its row offers the Switch button. False until then, so the + // button is missing rather than shown and refused. + canPromoteSecondSensor: Boolean = false, + // Switches the loop to the second sensor, after the user has confirmed it. + onPromoteSecondSensor: () -> Unit = {}, + // Result of the last switch, shown in a dialog until the user closes it. + promotionMessage: String? = null, + onDismissPromotionMessage: () -> Unit = {}, showFill: Boolean, showPumpBatteryChange: Boolean, // The status-row action buttons (fill / sensor insert / battery change) open mutating screens — hidden on an @@ -80,11 +96,12 @@ fun OverviewStatusSection( onExpandedChange: (Boolean) -> Unit, modifier: Modifier = Modifier ) { - val items = listOfNotNull(cannulaStatus, insulinStatus, sensorStatus, batteryStatus) + val items = listOfNotNull(cannulaStatus, insulinStatus, sensorStatus, warmUpStatus, secondSensorStatus, batteryStatus) if (items.isEmpty()) return val compactItems = items.filter { it.compactAge || (it.compactLevel && it.level != null) } var showSettingsSheet by rememberSaveable { mutableStateOf(false) } + var showPromoteDialog by rememberSaveable { mutableStateOf(false) } val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true) AapsCard( @@ -158,6 +175,8 @@ fun OverviewStatusSection( insulinStatus = insulinStatus, cannulaStatus = cannulaStatus, batteryStatus = batteryStatus, + warmUpStatus = warmUpStatus, + secondSensorStatus = secondSensorStatus, onSensorInsertClick = if (commandsAllowed && role.allows(ElementType.SENSOR_INSERT.role)) { { onNavigate(NavigationRequest.Element(ElementType.SENSOR_INSERT)) } } else null, @@ -169,6 +188,9 @@ fun OverviewStatusSection( } else null, onBatteryChangeClick = if (showPumpBatteryChange && commandsAllowed && role.allows(ElementType.BATTERY_CHANGE.role)) { { onNavigate(NavigationRequest.Element(ElementType.BATTERY_CHANGE)) } + } else null, + onPromoteSecondSensorClick = if (canPromoteSecondSensor && commandsAllowed) { + { showPromoteDialog = true } } else null ) } @@ -176,6 +198,30 @@ fun OverviewStatusSection( } } + // The switch changes where the loop gets its glucose from, so it is confirmed first. The result is + // shown in a dialog and not in a message that goes away by itself: a refusal has a reason to read. + if (showPromoteDialog) { + OkCancelDialog( + title = stringResource(UiStrings.overview_second_sensor_label), + message = stringResource(UiStrings.overview_second_sensor_switch_confirm), + onConfirm = { + showPromoteDialog = false + // Called even if the sensor stopped being ready while the dialog was open: the source + // checks its own rules again, and a refusal is then shown with its reason. + onPromoteSecondSensor() + }, + onDismiss = { showPromoteDialog = false } + ) + } + + promotionMessage?.let { message -> + OkDialog( + title = stringResource(UiStrings.overview_second_sensor_label), + message = message, + onDismiss = onDismissPromotionMessage + ) + } + if (showSettingsSheet) { StatusLightsSettingsBottomSheet( settingsDef = statusLightsDef, diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionPreviews.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionPreviews.kt index d599dcc9050b..9e69caaa8952 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionPreviews.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/OverviewStatusSectionPreviews.kt @@ -88,3 +88,40 @@ internal fun OverviewStatusSectionExpandedPreview() { ) } } + +/** Expanded card with a sensor that still warms up and a second sensor that is ready to switch to. */ +@Preview(showBackground = true, widthDp = 400) +@Composable +internal fun OverviewStatusSectionCgmRowsPreview() { + MaterialTheme { + val (cannula, insulin, sensor) = previewStatusItems + OverviewStatusSection( + sensorStatus = sensor, + insulinStatus = insulin, + cannulaStatus = cannula, + batteryStatus = previewBatteryItem, + warmUpStatus = StatusItem( + label = "Warm-up", + age = "23 min", + agePercent = 0.24f, + icon = Icons.Default.Circle, + compactLevel = false + ), + secondSensorStatus = StatusItem( + label = "New sensor", + age = "Ready to switch", + ageStatus = StatusLevel.NORMAL, + level = "Readings: 72", + icon = Icons.Default.Circle, + compactLevel = false + ), + canPromoteSecondSensor = true, + showFill = true, + showPumpBatteryChange = true, + onNavigate = {}, + statusLightsDef = previewStatusLightsDef, + expanded = true, + onExpandedChange = {} + ) + } +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponents.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponents.kt index 0c27afb77ed2..46ca0f888a11 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponents.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponents.kt @@ -31,12 +31,19 @@ import app.aaps.core.ui.compose.statusLevelToColor import app.aaps.core.ui.compose.statusLevelToDescription import app.aaps.core.ui.compose.stringResource import app.aaps.core.ui.compose.stringResourceOrNull +import app.aaps.ui.UiStrings /** * Status rows content — sensor/insulin/cannula/battery with optional action buttons. * Does not include a card wrapper — caller provides the container. * + * [warmUpStatus] and [secondSensorStatus] are shown right below the sensor. They are null for every + * CGM source that does not report them, and then the section is unchanged. + * [onPromoteSecondSensorClick] is null until the second sensor is ready, so the Switch button is + * missing rather than shown and refused. + * * @see StatusSectionContentPreview + * @see StatusSectionContentCgmRowsPreview */ @Composable internal fun StatusSectionContent( @@ -44,14 +51,18 @@ internal fun StatusSectionContent( insulinStatus: StatusItem?, cannulaStatus: StatusItem?, batteryStatus: StatusItem?, + warmUpStatus: StatusItem? = null, + secondSensorStatus: StatusItem? = null, onSensorInsertClick: (() -> Unit)? = null, onFillClick: (() -> Unit)? = null, onInsulinChangeClick: (() -> Unit)? = null, - onBatteryChangeClick: (() -> Unit)? = null + onBatteryChangeClick: (() -> Unit)? = null, + onPromoteSecondSensorClick: (() -> Unit)? = null ) { val addLabel = stringResource(CoreUiStrings.add) val cannulaChangeLabel = stringResource(CoreUiStrings.btn_status_cannula_change) val insulinFillLabel = stringResource(CoreUiStrings.btn_status_insulin_fill) + val switchLabel = stringResource(UiStrings.overview_second_sensor_switch) cannulaStatus?.let { StatusRow(item = it, actionLabel = cannulaChangeLabel, onActionClick = onFillClick) @@ -68,7 +79,22 @@ internal fun StatusSectionContent( sensorStatus?.let { StatusRow(item = it, actionLabel = addLabel, onActionClick = onSensorInsertClick) } - if (sensorStatus != null && batteryStatus != null) { + // True once any row is shown, so each CGM row knows if it needs a divider above it. + var anythingAbove = cannulaStatus != null || insulinStatus != null || sensorStatus != null + warmUpStatus?.let { + if (anythingAbove) { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + StatusRow(item = it) + anythingAbove = true + } + secondSensorStatus?.let { + if (anythingAbove) { + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + } + StatusRow(item = it, actionLabel = switchLabel, onActionClick = onPromoteSecondSensorClick) + } + if ((sensorStatus != null || warmUpStatus != null || secondSensorStatus != null) && batteryStatus != null) { HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) } batteryStatus?.let { diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponentsPreviews.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponentsPreviews.kt index 4e675cd8b07c..d59f00fa0767 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponentsPreviews.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusComponentsPreviews.kt @@ -2,6 +2,8 @@ package app.aaps.ui.compose.overview.statusLights import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.HourglassTop import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview @@ -9,6 +11,7 @@ import androidx.compose.ui.unit.dp import app.aaps.core.ui.compose.StatusLevel import app.aaps.core.ui.compose.icons.IcCannulaChange import app.aaps.core.ui.compose.icons.IcCgmInsert +import app.aaps.core.ui.compose.icons.IcGenericCgm import app.aaps.core.ui.compose.icons.IcPumpBattery import app.aaps.core.ui.compose.icons.IcPumpCartridge @@ -63,3 +66,46 @@ internal fun StatusSectionContentPreview() { } } } + +/** + * The two CGM rows: a sensor that still warms up, and a second sensor that is ready to be used by the + * loop. Only sources that report them get these rows. + */ +@Preview(showBackground = true) +@Composable +internal fun StatusSectionContentCgmRowsPreview() { + MaterialTheme { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + StatusSectionContent( + sensorStatus = StatusItem( + label = "Sensor", + age = "9d4h", + ageStatus = StatusLevel.WARNING, + agePercent = 0.9f, + icon = IcCgmInsert, + compactLevel = false + ), + insulinStatus = null, + cannulaStatus = null, + batteryStatus = null, + warmUpStatus = StatusItem( + label = "Warm-up", + age = "23 min", + agePercent = 0.24f, + icon = Icons.Filled.HourglassTop, + compactLevel = false + ), + secondSensorStatus = StatusItem( + label = "New sensor", + age = "Ready to switch", + ageStatus = StatusLevel.NORMAL, + level = "Readings: 72", + icon = IcGenericCgm, + compactLevel = false + ), + onSensorInsertClick = {}, + onPromoteSecondSensorClick = {} + ) + } + } +} diff --git a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusUiState.kt b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusUiState.kt index f9db7866f727..ff3f25dfae64 100644 --- a/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusUiState.kt +++ b/ui/src/commonMain/kotlin/app/aaps/ui/compose/overview/statusLights/StatusUiState.kt @@ -3,11 +3,24 @@ package app.aaps.ui.compose.overview.statusLights import androidx.compose.runtime.Immutable /** - * UI state for Overview status section (sensor/insulin/cannula/battery) + * UI state for Overview status section (sensor/insulin/cannula/battery). + * + * [warmUpStatus] and [secondSensorStatus] only exist while a CGM source reports a warm-up, or a + * second sensor that warms up next to the one in use. Both stay null for every other source, so the + * section looks exactly as before. + * + * @param canPromoteSecondSensor the second sensor is ready and the loop may switch to it, so its row + * offers the switch. False while it still warms up or settles: the source would refuse anyway. + * @param promotionMessage result of the last switch (done, done with a problem, or why it was + * refused). Shown once, then cleared by [StatusViewModel.clearPromotionMessage]. */ @Immutable data class StatusUiState( val sensorStatus: StatusItem? = null, + val warmUpStatus: StatusItem? = null, + val secondSensorStatus: StatusItem? = null, + val canPromoteSecondSensor: Boolean = false, + val promotionMessage: String? = null, val insulinStatus: StatusItem? = null, val cannulaStatus: StatusItem? = null, val batteryStatus: StatusItem? = null, 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..0c1b1f93a956 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 @@ -1,5 +1,7 @@ package app.aaps.ui.compose.overview.statusLights +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.HourglassTop import androidx.compose.runtime.Stable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -8,6 +10,8 @@ import app.aaps.core.data.pump.defs.PumpType import app.aaps.core.interfaces.concurrent.aapsIoDispatcher import app.aaps.core.interfaces.configuration.Config import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag import app.aaps.core.interfaces.nsclient.ProcessedDeviceStatusData import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction @@ -16,17 +20,25 @@ 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.CgmSensorStatusProvider +import app.aaps.core.interfaces.source.CgmWarmupProvider +import app.aaps.core.interfaces.source.CgmWarmupStatus +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.StagingState import app.aaps.core.interfaces.stats.TddCalculator import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.interfaces.utils.DecimalFormatter import app.aaps.core.keys.IntKey import app.aaps.core.keys.interfaces.IntPreferenceKey import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.TextRef import app.aaps.core.ui.CoreUiStrings import app.aaps.ui.UiStrings import app.aaps.core.ui.compose.StatusLevel import app.aaps.core.ui.compose.icons.IcCannulaChange import app.aaps.core.ui.compose.icons.IcCgmInsert +import app.aaps.core.ui.compose.icons.IcGenericCgm import app.aaps.core.ui.compose.icons.IcPatchPump import app.aaps.core.ui.compose.icons.IcPumpBattery import app.aaps.core.ui.compose.icons.IcPumpCartridge @@ -36,6 +48,7 @@ import dev.zacsweers.metro.ContributesIntoMap import dev.zacsweers.metro.Inject import dev.zacsweers.metro.binding import dev.zacsweers.metrox.viewmodel.ViewModelKey +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow @@ -73,7 +86,8 @@ class StatusViewModel( private val preferences: Preferences, private val tddCalculator: TddCalculator, private val decimalFormatter: DecimalFormatter, - private val processedDeviceStatusData: ProcessedDeviceStatusData + private val processedDeviceStatusData: ProcessedDeviceStatusData, + private val aapsLogger: AAPSLogger ) : ViewModel() { private val _uiState = MutableStateFlow(StatusUiState()) @@ -83,12 +97,20 @@ class StatusViewModel( // Refresh only while a screen shows the status lights. Every screen collects uiState with // collectAsStateWithLifecycle, so in the background there is no subscriber and nothing here runs. // The ticker emits at once, so a screen that starts collecting gets a fresh state straight away. - _uiState.subscriptionCount + val visible = _uiState.subscriptionCount .map { it > 0 } .distinctUntilChanged() - .flatMapLatest { visible -> if (visible) refreshTriggers() else emptyFlow() } + visible + .flatMapLatest { shown -> if (shown) refreshTriggers() else emptyFlow() } .onEach { refreshState() } .launchIn(viewModelScope) + // A CGM warm-up and a second sensor move by the minute, so the 60 s tick is too slow for them. + // This tick only rebuilds those two rows from the source's StateFlows, with no database read. + // It does nothing while no source reports either of them and no such row is shown. + visible + .flatMapLatest { shown -> if (shown) tickerFlow(CGM_TICK_MS) else emptyFlow() } + .onEach { if (cgmRowsMayChange()) refreshCgmRows() } + .launchIn(viewModelScope) } private fun refreshTriggers(): Flow = merge( @@ -136,6 +158,8 @@ class StatusViewModel( // Build status items (without expensive TDD calculation) val sensorStatus = buildSensorStatus() + val warmUpStatus = buildWarmUpStatus() + val secondSensorStatus = buildSecondSensorStatus() val insulinStatus = buildInsulinStatus(isPatchPump, pumpDescription.maxReservoirReading.toDouble()) val cannulaChange = withContext(aapsIoDispatcher) { persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.CANNULA_CHANGE) @@ -148,6 +172,9 @@ class StatusViewModel( _uiState.update { state -> state.copy( sensorStatus = sensorStatus, + warmUpStatus = warmUpStatus, + secondSensorStatus = secondSensorStatus, + canPromoteSecondSensor = secondSensorStatus != null && canPromoteSecondSensor(), insulinStatus = insulinStatus, // Preserve previous cannula level while TDD recalculates cannulaStatus = state.cannulaStatus?.let { prev -> @@ -196,6 +223,176 @@ class StatusViewModel( ) } + /** + * True while the active source reports a warm-up or a second sensor, or while one of the two rows + * is still shown. The last part makes the row go away on the next tick once the source stops + * reporting it, instead of staying until the next full refresh. + */ + private fun cgmRowsMayChange(): Boolean { + val source = activePlugin.activeBgSource + val warming = (source as? CgmWarmupProvider)?.warmupStatus?.value?.active == true + val staging = (source as? CgmSensorStatusProvider)?.stagingState?.value.let { it != null && it != StagingState.ABSENT } + val shown = _uiState.value.let { it.warmUpStatus != null || it.secondSensorStatus != null } + return warming || staging || shown + } + + /** Rebuilds only the two CGM rows. They come from StateFlows of the source, so this is cheap. */ + internal fun refreshCgmRows() { + val warmUpStatus = buildWarmUpStatus() + val secondSensorStatus = buildSecondSensorStatus() + val canPromote = secondSensorStatus != null && canPromoteSecondSensor() + _uiState.update { + it.copy(warmUpStatus = warmUpStatus, secondSensorStatus = secondSensorStatus, canPromoteSecondSensor = canPromote) + } + } + + /** + * Countdown while the CGM warms up, for any source that reports it. Null for every other source + * and as soon as the warm-up ends, so the row goes away. + * + * The time left comes from the wall-clock end time when the source gives one, because a stored + * countdown is only updated when the sensor talks, and so goes stale between two radio windows. + * + * A source can also report a connection phase as active. Without a warm-up end time still ahead, + * that is a radio reconnect and not a warm-up, so no row is shown for it. + */ + internal fun buildWarmUpStatus(): StatusItem? { + val status = (activePlugin.activeBgSource as? CgmWarmupProvider)?.warmupStatus?.value ?: return null + if (!status.active) return null + val now = dateUtil.now() + val endsAt = status.endsAtEpochMs + val isWarmUp = status.phase == CgmWarmupStatus.Phase.WARMING || (endsAt != null && endsAt > now) + if (!isWarmUp) return null + + val remainingMs = endsAt?.let { (it - now).coerceAtLeast(0L) } ?: status.remainingMs?.coerceAtLeast(0L) + // Rounded up, so it reads "1 min" until the time is really over and never "0 min" while warming. + val age = remainingMs + ?.takeIf { it > 0L } + ?.let { rh.gs(CoreUiStrings.format_mins, ((it + MINUTE_MS - 1L) / MINUTE_MS).toInt()) } + ?: rh.gs(UiStrings.overview_cgm_warmup_waiting) + // Part of the warm-up that is done, so the bar fills up as the sensor gets ready. + val total = status.totalMs + val percent = if (total != null && total > 0L && remainingMs != null) { + ((total - remainingMs).toFloat() / total).coerceIn(0f, 1f) + } else -1f + + return StatusItem( + label = rh.gs(UiStrings.overview_cgm_warmup_label), + age = age, + ageStatus = StatusLevel.UNSPECIFIED, + agePercent = percent, + icon = Icons.Filled.HourglassTop, + compactLevel = false + ) + } + + /** + * A second sensor that warms up next to the one in use, for any source that supports it. + * Shows how far it is, and how many valid readings it has sent: the readings are the only sign + * that a sensor whose values do not go to the loop is really working. + * + * The source owns the rule for when the sensor may be used and publishes the time left. This + * screen has no copy of that rule, so it cannot show a different time than the one that counts. + */ + internal fun buildSecondSensorStatus(): StatusItem? { + val source = activePlugin.activeBgSource as? CgmSensorStatusProvider ?: return null + val state = source.stagingState.value + val settleRemainingMs = source.stagingSettleRemainingMs.value?.takeIf { it > 0L } + val age = when (state) { + StagingState.ABSENT -> return null + StagingState.WARMUP -> rh.gs(UiStrings.overview_second_sensor_warmup) + StagingState.READY -> rh.gs(UiStrings.overview_second_sensor_ready) + // Whole hours, rounded up: "ready in 1 h" until the last minute, never "ready in 0 h". + // With no time left the source still waits for enough readings. + StagingState.SETTLING -> + settleRemainingMs + ?.let { rh.gs(UiStrings.overview_second_sensor_ready_in, rh.gs(CoreUiStrings.units_format_hours, ((it + HOUR_MS - 1L) / HOUR_MS).toInt())) } + ?: rh.gs(UiStrings.overview_second_sensor_waiting_readings) + } + val ageMs = source.stagingLifecycle.value?.ageMs + val percent = if (state == StagingState.SETTLING && settleRemainingMs != null && ageMs != null && ageMs >= 0L) { + (ageMs.toFloat() / (ageMs + settleRemainingMs)).coerceIn(0f, 1f) + } else -1f + + return StatusItem( + label = rh.gs(UiStrings.overview_second_sensor_label), + age = age, + ageStatus = if (state == StagingState.READY) StatusLevel.NORMAL else StatusLevel.UNSPECIFIED, + agePercent = percent, + level = source.stagingEvidence.value?.let { rh.gs(UiStrings.overview_second_sensor_readings, it.validCount) }, + icon = IcGenericCgm, + compactLevel = false + ) + } + + /** The second sensor is ready, so the loop may switch to it. */ + internal fun canPromoteSecondSensor(): Boolean = + (activePlugin.activeBgSource as? CgmSensorStatusProvider)?.stagingState?.value == StagingState.READY + + /** The switch that is still running, if any. A second tap must not start another one. */ + private var promotionJob: Job? = null + + /** + * Switches the loop to the second sensor. This is the only action on this card that changes + * where the loop gets its glucose from. The result is put into [StatusUiState.promotionMessage], + * so it can be shown in a dialog. + * + * The UI shows the button only when the source says READY ([StatusUiState.canPromoteSecondSensor]) + * and `commandsAllowed` is true. This function does not check either again. The source checks + * its own rules again (soak time, readings) and may refuse. + * + * Never an early switch: that has its own warning on the source's own screen. + */ + fun promoteSecondSensor() { + if (promotionJob?.isActive == true) return + val source = activePlugin.activeBgSource as? CgmSensorStatusProvider + if (source == null) { + // The source was changed while the dialog was open. + _uiState.update { it.copy(promotionMessage = promotionMessage(PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT))) } + refreshCgmRows() + return + } + promotionJob = viewModelScope.launch { + val message = try { + promotionMessage(withContext(aapsIoDispatcher) { source.promoteStagingToProduction(allowEarly = false) }) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // The source did not say what happened, so the user is sent to check, not told it failed. + aapsLogger.error(LTag.UI, "Switch to the second CGM sensor threw", e) + rh.gs(UiStrings.overview_second_sensor_switch_error) + } + _uiState.update { it.copy(promotionMessage = message) } + refreshCgmRows() + } + } + + /** + * What to tell the user after a switch: done, done with a problem, or why it was refused. + * Every result has its own text: a refusal the user cannot understand is worse than no button. + */ + internal fun promotionMessage(result: PromotionResult): String = rh.gs(promotionMessageRef(result)) + + private fun promotionMessageRef(result: PromotionResult): TextRef = when (result) { + PromotionResult.Ok -> UiStrings.overview_second_sensor_switch_ok + PromotionResult.OkBoundFailed -> UiStrings.overview_second_sensor_switch_ok_calibration_failed + is PromotionResult.OkFollowUpFailed -> + if (result.productionIdentityPresent) UiStrings.overview_second_sensor_switch_ok_connect_failed + else UiStrings.overview_second_sensor_switch_ok_sensor_unknown + + is PromotionResult.Rejected -> when (result.reason) { + PromotionRejectReason.STAGING_ABSENT -> UiStrings.overview_second_sensor_switch_refused_absent + PromotionRejectReason.STAGING_NOT_SETTLED -> UiStrings.overview_second_sensor_switch_refused_not_settled + PromotionRejectReason.STAGING_NO_VALID_GLUCOSE -> UiStrings.overview_second_sensor_switch_refused_no_readings + PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE -> UiStrings.overview_second_sensor_switch_refused_no_recent_reading + } + } + + /** Removes the switch result once the user has read it. */ + fun clearPromotionMessage() { + _uiState.update { it.copy(promotionMessage = null) } + } + private suspend fun buildInsulinStatus(isPatchPump: Boolean, maxReading: Double): StatusItem { val event = withContext(aapsIoDispatcher) { persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.INSULIN_CHANGE) @@ -330,4 +527,12 @@ class StatusViewModel( else -> StatusLevel.NORMAL } } + + private companion object { + + /** How often the CGM warm-up and second sensor rows are rebuilt while one of them is shown. */ + const val CGM_TICK_MS = 10_000L + const val MINUTE_MS = 60_000L + const val HOUR_MS = 60L * MINUTE_MS + } } \ No newline at end of file From 7419bb41c325be2c30e2da5adf80e80dc8ed535c Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 29 Oct 2026 00:15:02 +0100 Subject: [PATCH 06/27] Dexcom ONE+ / G7: send fingerstick calibrations to the sensor A fingerstick entered for a Dexcom ONE+ / G7 now goes to the sensor's own algorithm (Control opcode 0x34), as the Dexcom app does, instead of being fitted in the app. A sensor keeps a calibration it accepts for good: it cannot be edited or deleted later. So the value is checked twice, the confirmation warns about it, and the driver never sends a value twice. Setting - New user setting "Send calibration to the sensor" (DexcomOnePlusBooleanKey.SendCalibrationToSensor, dexcom_oneplus_send_calibration_to_sensor). On by default, shown in the plugin settings (not engineering only), not exported. - Off: the fingerstick is stored as an app calibration entry, exactly as before this commit. Where the value goes - The calibration dialog asks the master through MasterActionExecutor. MasterRecordWriter.calibrationRefusal(calibration) asks the BG source when it calibrates in the sensor, the calibration plugin otherwise. calibrationLines() adds a warning line to the confirmation: "This value goes to the sensor. The sensor keeps it for good". - MasterRecordWriter.addCalibration hands the value to BgSource.calibrateSensor and does NOT also store a calibration entry. Queued is logged as "Sent to the sensor"; a refusal is logged and shown to the user; NotSupported falls back to the app calibration. - DexcomOnePlusPlugin.calibrateSensor checks again (time has passed since the confirmation) and offers the value to the production driver only. - In the driver the value waits in OnePlusCalibrationQueue (one slot) and the EGV loop writes it between two Control exchanges. The time sent is the time given for the blood, in sensor seconds, taken from the last known transmitter time. The calibration dialog gives the moment the user confirmed the value, which is a little after the finger prick. The 0x34 answer (or a 0x35 status) is read, then the calibration state (0x32). - The Status screen shows a "Sensor calibration" card while the setting is on: waiting / accepted / refused / unknown / not sent, the raw answer, and a line when the sensor itself asks for a calibration. Checks before anything is queued (OnePlusCalibrationGate) - 40..400 mg/dL; blood not in the future and at most one hour old; sensor not warming up or failed; a production reading in the last 11 min; that reading has a trend and it is at most 2 mg/dL/min. - The driver refuses on a pre-soak slot (checked on the live namespace, so a promoted instance works), without a session, and while a value is already waiting. Checks again right before the write - The same checks run again in the EGV loop just before the value is written, on the driver's live warm-up phase and its last reading (kept across radio windows): not warming up or failed, a reading in the last 11 min with a trend of at most 2 mg/dL/min, at most one hour old, in range. A session given a queue but no check writes nothing. - A value that fails is dropped before any write, with the new outcome "not sent" (OnePlusCalibrationOutcome.NotSent and its reason). The waiting value never reaches another sensor or session - The queue is emptied, as "not sent", on: a new pairing (connect), a new sensor identity, a session restart (auto-resume), a promotion (rebindStore), a disconnect, a shutdown, and a SessionStart written by the EGV loop. Never twice - The queue is emptied when the value is taken for the write, before the write, and only if it is still the value that was checked. A failed write, a lost answer or an unreadable answer is reported as "unknown", never retried. When the answer is lost and the calibration state shows exactly the value and time sent, the outcome becomes accepted. The user text for "unknown" says not to send the value again. - "Not sent" and "unknown" are kept apart. "Not sent" is only for a value dropped before any write (age, range, phase, reading, trend, cleared queue): the text says nothing reached the sensor and the value may be entered again, with the reason. "Unknown" is only for a value that was written. DexcomOnePlusCalibrationText holds these texts for the plugin and the status card. In-app calibration is skipped for this source - New BgSource.calibratesInSensor(). While it is true, PrepareGraphDataRunner.smoothData does not call activeCalibration.calibrate (smoothing still runs). This also covers calibration entries made before the setting was switched on, which would otherwise correct readings the sensor already corrected. Other BG sources see nothing - BgSource gets calibratesInSensor() = false, calibrateSensor() = NotSupported and sensorCalibrationRefusal() = null as defaults, and SensorCalibrationResult is new. Only the ONE+ plugin overrides them, so for every other source the dialog, the confirmation, the stored entry and the graph calibration are unchanged. Adaptations to dev - PrepareGraphDataRunner: only the calibratesInSensor() skip; no other change to how the series is built. - The calibration dialog is not changed: on dev it shows no calibration status message after a commit, so there is nothing to hide. - No change to Calibration or LinearCalibrationPlugin. - OnePlusEgvCalibrationGateTest uses a small idle GATT fake of its own, because the driver has no placeholder GATT client. Also - plugins/dexcom_oneplus/NOTICE lists OnePlusCalibrateTx/Rx (xDrip CalibrateTx/RxMessage shape), the G7 layout taken from AndroidAPS PR 5397 for OnePlusCalibrateTx/Rx and OnePlusCalibrationBoundsRx, and the original calibration files. - 22 English strings in :plugins:source, 2 in :core:ui. - prefs-schema.txt gets the new key. Tests: 68 new driver/plugin cases - OnePlusCgmDriverCalibrationTest (14, incl. the waiting value dropped as "not sent" on disconnect, shutdown, promotion, new identity, new pairing and session restart), OnePlusCalibrateEchoTest (8), OnePlusCalibrateMessageTest (6), OnePlusCalibrationGateTest (8), OnePlusEgvCalibrationGateTest (9, incl. "a lost answer is settled by the calibration state and the value is never sent twice", warm-up and fast change at send time dropped as "not sent", an old value never "unknown"), OnePlusCalibrationQueueTest (8), 2 in OnePlusCgmDriverRealSharedTest, 1 in OnePlusBytesTest, DexcomOnePlusSensorCalibrationTest (8), DexcomOnePlusCalibrationTextTest (4, "not sent" and "unknown" never share a text); plus 5 in MasterRecordWriterTest and 2 in PrepareGraphDataRunnerTest. Unit tests only; nothing has been sent to a real sensor from this branch. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/src/testFull/resources/prefs-schema.txt | 1 + .../aaps/core/interfaces/source/BgSource.kt | 32 +- .../interfaces/source/SensorCalibration.kt | 25 ++ .../ui/src/androidMain/res/values/strings.xml | 2 + .../bolus/MasterActionExecutorImplTest.kt | 6 +- .../bolus/MasterRecordWriterTest.kt | 71 +++- .../bolus/MasterActionExecutorImpl.kt | 5 +- .../bolus/MasterRecordWriter.kt | 49 ++- plugins/dexcom_oneplus/NOTICE | 11 +- .../OnePlusCgmDriverCalibrationTest.kt | 286 +++++++++++++++ .../parse/OnePlusCalibrateEchoTest.kt | 93 +++++ .../parse/OnePlusCalibrateMessageTest.kt | 76 ++++ .../session/OnePlusCalibrationGateTest.kt | 71 ++++ .../session/OnePlusCalibrationQueueTest.kt | 116 +++++++ .../session/OnePlusEgvCalibrationGateTest.kt | 328 ++++++++++++++++++ .../OnePlusCalibrationOutcome.kt | 68 ++++ .../plugins/dexcomoneplus/OnePlusCgmDriver.kt | 24 ++ .../dexcomoneplus/OnePlusCgmDriverReal.kt | 145 ++++++++ .../dexcomoneplus/parse/OnePlusCalibrateRx.kt | 133 +++++++ .../dexcomoneplus/parse/OnePlusCalibrateTx.kt | 45 +++ .../parse/OnePlusCalibrationBoundsRx.kt | 55 +++ .../session/OnePlusBleSession.kt | 29 ++ .../session/OnePlusCalibrationGate.kt | 60 ++++ .../session/OnePlusCalibrationQueue.kt | 111 ++++++ .../session/OnePlusEgvSession.kt | 194 +++++++++++ .../OnePlusCgmDriverRealSharedTest.kt | 23 ++ .../dexcomoneplus/parse/OnePlusBytesTest.kt | 9 + .../DexcomOnePlusCalibrationTextTest.kt | 47 +++ .../DexcomOnePlusSensorCalibrationTest.kt | 199 +++++++++++ .../source/DexcomOnePlusCalibrationText.kt | 40 +++ .../plugins/source/DexcomOnePlusPlugin.kt | 42 +++ .../activities/DexcomOnePlusStatusActivity.kt | 98 +++++- .../src/androidMain/res/values/strings.xml | 22 ++ .../source/keys/DexcomOnePlusBooleanKey.kt | 18 + .../workflow/PrepareGraphDataRunnerTest.kt | 49 +++ .../aaps/workflow/PrepareGraphDataRunner.kt | 11 +- 36 files changed, 2575 insertions(+), 19 deletions(-) create mode 100644 core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverCalibrationTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateEchoTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateMessageTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGateTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueueTest.kt create mode 100644 plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvCalibrationGateTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCalibrationOutcome.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateTx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationBoundsRx.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGate.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueue.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationTextTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationText.kt diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index 7cf9bea8f609..a5660ebdd6ac 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -162,6 +162,7 @@ dexcom_lognssensorchange|BooleanKey|true dexcom_oneplus_anchor_session_to_manual_sensor_change|DexcomOnePlusBooleanKey|false dexcom_oneplus_correct_sensor_start|DexcomOnePlusBooleanKey|false dexcom_oneplus_repair_missing_sensor_change|DexcomOnePlusBooleanKey|false +dexcom_oneplus_send_calibration_to_sensor|DexcomOnePlusBooleanKey|false dexcom_oneplus_staging_auto_promote_hours|DexcomOnePlusIntKey|true dexcom_oneplus_staging_auto_promote|DexcomOnePlusBooleanKey|false dexcom_oneplus_start|DexcomOnePlusIntentKey|false diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt index 95dda4a25a8b..4c58eb74db65 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/BgSource.kt @@ -16,4 +16,34 @@ interface BgSource { * @return true if sensor has error and BG values should not be displayed */ fun hasSensorError(): Boolean = false -} \ No newline at end of file + + /** + * True when a fingerstick should go to the SENSOR instead of being fitted in the app. + * + * False for every source by default, and false even on a source that can do it until the user + * has switched it on. While it is true the app must not also fit a line on top of the same + * sensor's readings, or the correction is applied twice. + */ + fun calibratesInSensor(): Boolean = false + + /** + * Hand a fingerstick to the sensor's own algorithm. + * + * A sensor keeps a calibration it accepts for good: it cannot be edited or deleted + * afterwards, unlike a calibration entry stored in the app. Only ever call this for an explicit + * user action. + * + * @param glucoseMgdl the blood value + * @param bloodAtMs wall clock (epoch ms) used as the time of the blood. The calibration dialog + * passes the moment the user confirmed the value, not the moment of the finger prick. + */ + fun calibrateSensor(glucoseMgdl: Int, bloodAtMs: Long): SensorCalibrationResult = + SensorCalibrationResult.NotSupported + + /** + * Why the sensor must not get this fingerstick now, already readable by the user, or null when + * it may. Asked before the user confirms, so a refusal is shown before anything is sent. + * Only meaningful while [calibratesInSensor] is true. + */ + fun sensorCalibrationRefusal(glucoseMgdl: Int, bloodAtMs: Long): String? = null +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt new file mode 100644 index 000000000000..d70c4dc52d3b --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/SensorCalibration.kt @@ -0,0 +1,25 @@ +package app.aaps.core.interfaces.source + +/** + * What happened when a fingerstick was handed to the sensor itself. + * + * Only says whether the app managed to pass the value on. What the SENSOR then did with it comes + * back later, over the radio, and belongs to the source's own status screen: the sensor is asleep + * between its radio windows, so there is nothing to report at the moment the user taps OK. + */ +sealed interface SensorCalibrationResult { + + /** This source does not hold calibrations in the sensor, or the user has not switched it on. */ + data object NotSupported : SensorCalibrationResult + + /** Handed over. It reaches the sensor at the next radio window, normally within a few minutes. */ + data object Queued : SensorCalibrationResult + + /** + * The app will not pass it on. + * + * @param reason short, already user-readable, e.g. no session, value out of range, one already + * waiting + */ + data class Refused(val reason: String) : SensorCalibrationResult +} diff --git a/core/ui/src/androidMain/res/values/strings.xml b/core/ui/src/androidMain/res/values/strings.xml index 216f88fbcf7a..9d97039582d3 100644 --- a/core/ui/src/androidMain/res/values/strings.xml +++ b/core/ui/src/androidMain/res/values/strings.xml @@ -182,6 +182,8 @@ Data is coming from different pump. Change pump driver to reset pump state. BG Calibration + This value goes to the sensor. The sensor keeps it for good: it cannot be removed later. Make sure it is right. + Sent to the sensor Calibration not saved: BG is changing too fast (Δ %1$s %3$s per 5 min, limit %2$s). Try again when glucose is stable. Calibration not saved: no CGM reading found in the 10 minutes before now. diff --git a/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImplTest.kt b/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImplTest.kt index 8a4b5cbb58f5..d4ce2e65dfa7 100644 --- a/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImplTest.kt +++ b/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImplTest.kt @@ -1867,7 +1867,7 @@ class MasterActionExecutorImplTest : TestBaseWithProfile() { @Test fun prepareBatch_calibration_isRefusedWithTheMastersReason() = runTest { stubPassthroughConstraints() - whenever(masterRecordWriter.calibrationRefusal()).thenReturn("no session") + whenever(masterRecordWriter.calibrationRefusal(BatchAction.Calibration(120.0))).thenReturn("no session") val result = create().prepareBatch(listOf(BatchAction.Calibration(120.0))) @@ -1877,8 +1877,8 @@ class MasterActionExecutorImplTest : TestBaseWithProfile() { @Test fun prepareBatch_calibration_confirmStoresItOnTheMaster() = runTest { stubPassthroughConstraints() - whenever(masterRecordWriter.calibrationRefusal()).thenReturn(null) - whenever(masterRecordWriter.calibrationLine(BatchAction.Calibration(120.0))).thenReturn(ConfirmationLine(ConfirmationRole.PRIMARY, "Calibration: 120")) + whenever(masterRecordWriter.calibrationRefusal(BatchAction.Calibration(120.0))).thenReturn(null) + whenever(masterRecordWriter.calibrationLines(BatchAction.Calibration(120.0))).thenReturn(listOf(ConfirmationLine(ConfirmationRole.PRIMARY, "Calibration: 120"))) val executor = create() val prepared = executor.prepareBatch(listOf(BatchAction.Calibration(120.0))) as MasterActionExecutor.PrepareResult.Preview diff --git a/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterRecordWriterTest.kt b/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterRecordWriterTest.kt index c7c6ed5d1fd3..5175535ae367 100644 --- a/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterRecordWriterTest.kt +++ b/implementation/src/androidHostTest/kotlin/app/aaps/implementation/bolus/MasterRecordWriterTest.kt @@ -13,6 +13,9 @@ import app.aaps.core.interfaces.calibration.AddEntryResult import app.aaps.core.interfaces.calibration.Calibration import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.logging.UserEntryLogger +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.interfaces.source.SensorCalibrationResult import app.aaps.core.interfaces.source.XDripSource import app.aaps.core.interfaces.sync.XDripBroadcast import app.aaps.core.interfaces.utils.Translator @@ -26,6 +29,7 @@ import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.eq +import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.whenever @@ -43,12 +47,14 @@ class MasterRecordWriterTest : TestBaseWithProfile() { @Mock lateinit var xDripSource: XDripSource @Mock lateinit var xDripBroadcast: XDripBroadcast @Mock lateinit var calibration: Calibration + @Mock lateinit var bgSource: BgSource private lateinit var sut: MasterRecordWriter @BeforeEach fun setUp() { whenever(activePlugin.activeCalibration).thenReturn(calibration) + whenever(activePlugin.activeBgSource).thenReturn(bgSource) sut = MasterRecordWriter( persistenceLayer, baseText, dateUtil, profileUtil, profileFunction, decimalFormatter, translator, activePlugin, uel, xDripSource, xDripBroadcast, aapsLogger @@ -152,14 +158,14 @@ class MasterRecordWriterTest : TestBaseWithProfile() { fun `a calibration the master cannot take now is refused with its reason`() = runTest { whenever(calibration.checkPreconditions()).thenReturn(AddEntryResult.Rejected.NoSession) - assertThat(sut.calibrationRefusal()).isEqualTo(baseText.gs(CoreUiStrings.cal_reject_no_session)) + assertThat(sut.calibrationRefusal(BatchAction.Calibration(120.0))).isEqualTo(baseText.gs(CoreUiStrings.cal_reject_no_session)) } @Test fun `a calibration the master can take is not refused`() = runTest { whenever(calibration.checkPreconditions()).thenReturn(AddEntryResult.Accepted) - assertThat(sut.calibrationRefusal()).isNull() + assertThat(sut.calibrationRefusal(BatchAction.Calibration(120.0))).isNull() } @Test @@ -185,4 +191,65 @@ class MasterRecordWriterTest : TestBaseWithProfile() { assertThat(failure?.comment).isEqualTo(baseText.gs(CoreUiStrings.cal_reject_no_pair)) verify(xDripBroadcast, never()).sendCalibration(any()) } + + // ---- A BG source that calibrates in the sensor ---- + + /** The writer with a [ProfileUtil] that formats a value without the unit strings, which these tests do not check. */ + private fun withUnitText(): MasterRecordWriter { + val units: ProfileUtil = mock() + whenever(units.fromMgdlToStringWithUnits(any())).thenReturn("120 mg/dL") + return MasterRecordWriter( + persistenceLayer, baseText, dateUtil, units, profileFunction, decimalFormatter, translator, activePlugin, + uel, xDripSource, xDripBroadcast, aapsLogger + ) + } + + @Test + fun `a sensor that calibrates itself is asked, not the calibration plugin`() = runTest { + whenever(bgSource.calibratesInSensor()).thenReturn(true) + whenever(bgSource.sensorCalibrationRefusal(eq(120), any())).thenReturn("changing too fast") + + assertThat(sut.calibrationRefusal(BatchAction.Calibration(120.0))).isEqualTo("changing too fast") + verify(calibration, never()).checkPreconditions() + } + + @Test + fun `a value for the sensor carries a warning line in the confirmation`() { + whenever(bgSource.calibratesInSensor()).thenReturn(true) + + val lines = withUnitText().calibrationLines(BatchAction.Calibration(120.0)) + + assertThat(lines.map { it.role }).containsExactly(ConfirmationRole.PRIMARY, ConfirmationRole.WARNING).inOrder() + assertThat(lines[1].text).isEqualTo(baseText.gs(CoreUiStrings.calibration_to_sensor_warning)) + } + + @Test + fun `a value for the app has no warning line`() { + assertThat(withUnitText().calibrationLines(BatchAction.Calibration(120.0)).map { it.role }).containsExactly(ConfirmationRole.PRIMARY) + } + + @Test + fun `a value for the sensor goes to the sensor and is never also stored in the app`() = runTest { + whenever(bgSource.calibratesInSensor()).thenReturn(true) + whenever(bgSource.calibrateSensor(eq(120), any())).thenReturn(SensorCalibrationResult.Queued) + var failure: MasterActionExecutor.Failure? = null + + sut.addCalibration(BatchAction.Calibration(120.0), Sources.NSClient) { failure = it } + + assertThat(failure).isNull() + verify(calibration, never()).addEntry(any(), any()) + verify(uel).log(eq(Action.CALIBRATION), eq(Sources.NSClient), eq(baseText.gs(CoreUiStrings.calibration_sent_to_sensor)), any()) + } + + @Test + fun `a value the sensor side refuses reports the reason and stores nothing`() = runTest { + whenever(bgSource.calibratesInSensor()).thenReturn(true) + whenever(bgSource.calibrateSensor(eq(120), any())).thenReturn(SensorCalibrationResult.Refused("warming up")) + var failure: MasterActionExecutor.Failure? = null + + sut.addCalibration(BatchAction.Calibration(120.0), Sources.NSClient) { failure = it } + + assertThat(failure?.comment).isEqualTo("warming up") + verify(calibration, never()).addEntry(any(), any()) + } } diff --git a/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImpl.kt b/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImpl.kt index aede471eb36c..273295a95b9b 100644 --- a/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImpl.kt +++ b/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterActionExecutorImpl.kt @@ -582,7 +582,7 @@ class MasterActionExecutorImpl( return MasterActionExecutor.PrepareResult.Error(rh.gs(CoreUiStrings.no_profile_set)) // A calibration is checked on the MASTER's sensor data (session, warm-up, BG changing too fast): that is the // BG the loop doses on. Refused here, before the user confirms; checked again when it is stored. - if (cal != null) masterRecordWriter.calibrationRefusal()?.let { return MasterActionExecutor.PrepareResult.Error(it) } + if (cal != null) masterRecordWriter.calibrationRefusal(cal)?.let { return MasterActionExecutor.PrepareResult.Error(it) } // Removals: the master finds its own copies by Nightscout id. With none of them here there is nothing to // confirm — refused with the reason, or a plain no-op when the master's own records were removed meanwhile. val removalPlan = if (removals.isNotEmpty()) masterRecordWriter.planRemovals(removals) else null @@ -630,7 +630,8 @@ class MasterActionExecutorImpl( tes.flatMap { buildTherapyEventLine(it) } + teEdits.flatMap { buildTherapyEventEditLine(it) } + (removalPlan?.lines ?: emptyList()) + - listOfNotNull(rse?.let { masterRecordWriter.removeStartEventsLine() }, cal?.let { masterRecordWriter.calibrationLine(it) }) + listOfNotNull(rse?.let { masterRecordWriter.removeStartEventsLine() }) + + (cal?.let { masterRecordWriter.calibrationLines(it) } ?: emptyList()) return MasterActionExecutor.PrepareResult.Preview(insulin, carbs, bolusId, lines = lines, advisorApplies = false, advisorLines = emptyList()) } diff --git a/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterRecordWriter.kt b/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterRecordWriter.kt index d19aebd0b987..f7996a8a831c 100644 --- a/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterRecordWriter.kt +++ b/implementation/src/commonMain/kotlin/app/aaps/implementation/bolus/MasterRecordWriter.kt @@ -30,6 +30,7 @@ import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.profile.ProfileFunction import app.aaps.core.interfaces.profile.ProfileUtil import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.source.SensorCalibrationResult import app.aaps.core.interfaces.source.XDripSource import app.aaps.core.interfaces.sync.XDripBroadcast import app.aaps.core.interfaces.utils.DateUtil @@ -42,6 +43,7 @@ import app.aaps.core.ui.extensions.toStringFull import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.Inject import dev.zacsweers.metro.SingleIn +import kotlin.math.roundToInt import kotlin.time.Duration.Companion.milliseconds /** @@ -358,20 +360,51 @@ class MasterRecordWriter( // ----- Calibration ----- - /** Why the master cannot take a calibration now, or null when it can. Checked on the master's own data. */ - suspend fun calibrationRefusal(): String? = - (activePlugin.activeCalibration.checkPreconditions() as? AddEntryResult.Rejected)?.let { rejectionMessage(it) } + /** + * Why the master cannot take a calibration now, or null when it can. Checked on the master's own data: by + * the sensor itself when the BG source calibrates in the sensor, by the calibration plugin otherwise. + */ + suspend fun calibrationRefusal(calibration: BatchAction.Calibration): String? { + val bgSource = activePlugin.activeBgSource + if (bgSource.calibratesInSensor()) return bgSource.sensorCalibrationRefusal(calibration.glucoseMgdl.roundToInt(), dateUtil.now()) + return (activePlugin.activeCalibration.checkPreconditions() as? AddEntryResult.Rejected)?.let { rejectionMessage(it) } + } - /** The confirmation line for a calibration. */ - fun calibrationLine(calibration: BatchAction.Calibration): ConfirmationLine = - ConfirmationLine(ConfirmationRole.PRIMARY, line(CoreUiStrings.calibration, profileUtil.fromMgdlToStringWithUnits(calibration.glucoseMgdl))) + /** + * The confirmation lines for a calibration. A value that goes to the sensor gets a warning: the sensor keeps + * it for good, unlike a calibration entry stored in the app. + */ + fun calibrationLines(calibration: BatchAction.Calibration): List { + val value = ConfirmationLine(ConfirmationRole.PRIMARY, line(CoreUiStrings.calibration, profileUtil.fromMgdlToStringWithUnits(calibration.glucoseMgdl))) + return if (activePlugin.activeBgSource.calibratesInSensor()) listOf(value, ConfirmationLine(ConfirmationRole.WARNING, rh.gs(CoreUiStrings.calibration_to_sensor_warning))) + else listOf(value) + } /** - * Store a calibration on the master, paired with its own latest sensor reading. The conditions are checked - * again here (time has passed since the prepare); a refusal goes to [onError] so the user is told. + * Store a calibration on the master, paired with its own latest sensor reading, or hand it to the sensor when the + * BG source calibrates in the sensor. Never both: a sensor that holds a calibration re-bases its own readings, + * and a line fitted in the app on top would correct them twice. The conditions are checked again here (time has + * passed since the prepare); a refusal goes to [onError] so the user is told. */ suspend fun addCalibration(calibration: BatchAction.Calibration, source: Sources, onError: (MasterActionExecutor.Failure) -> Unit) { val value = ValueWithUnit.fromGlucoseUnit(profileUtil.fromMgdlToUnits(calibration.glucoseMgdl), profileUtil.units) + val bgSource = activePlugin.activeBgSource + if (bgSource.calibratesInSensor()) { + when (val sent = bgSource.calibrateSensor(calibration.glucoseMgdl.roundToInt(), dateUtil.now())) { + SensorCalibrationResult.Queued -> { + uel.log(action = Action.CALIBRATION, source = source, note = rh.gs(CoreUiStrings.calibration_sent_to_sensor), value = value) + return + } + + is SensorCalibrationResult.Refused -> { + uel.log(action = Action.CALIBRATION, source = source, note = "rejected: ${sent.reason}", value = value) + onError(MasterActionExecutor.Failure(sent.reason)) + return + } + // The source changed its mind between the two calls: store it in the app as before. + SensorCalibrationResult.NotSupported -> Unit + } + } when (val result = activePlugin.activeCalibration.addEntry(calibration.glucoseMgdl, dateUtil.now())) { AddEntryResult.Accepted -> { uel.log(action = Action.CALIBRATION, source = source, value = value) diff --git a/plugins/dexcom_oneplus/NOTICE b/plugins/dexcom_oneplus/NOTICE index 5f88a217babb..4c79d968690d 100644 --- a/plugins/dexcom_oneplus/NOTICE +++ b/plugins/dexcom_oneplus/NOTICE @@ -50,6 +50,7 @@ Ported into original Kotlin (wire format / algorithm identical, text rewritten): parse/OnePlusFastCrc16.kt ← FastCRC16.java parse/OnePlusGlucoseParser.kt ← EGlucoseRxMessage / EGlucoseRxMessage2 parse/OnePlusCalibrationState.kt ← CalibrationState + parse/OnePlusCalibrateTx.kt, Rx.kt ← CalibrateTxMessage / CalibrateRxMessage (0x35 answer shape) parse/OnePlusEGlucoseTx.kt ← EGlucoseTxMessage / BaseMessage.init parse/OnePlusTransmitterTimeTx.kt, Rx.kt ← TransmitterTimeTx/RxMessage parse/OnePlusSessionStartTx.kt, Rx.kt ← SessionStartTx/RxMessage @@ -61,6 +62,12 @@ Ported into original Kotlin (wire format / algorithm identical, text rewritten): session/OnePlusSessionStart.kt ← TxIdHelper.isValidShortPairingCode session/OnePlusKeksGuideCerts.kt ← xDrip G7 keks Auto-Configure QR / Ob1 setPersistence +Layout taken from the Dexcom G7 driver of AndroidAPS PR 5397 (same project, +AGPL-3.0; tested there on G7 sensors): + parse/OnePlusCalibrateTx.kt ← G7 7-byte calibrate request (no CRC) + parse/OnePlusCalibrateRx.kt ← G7CalibrateRxMessage (0x34 echo) + parse/OnePlusCalibrationBoundsRx.kt ← G7CalibrationBoundsMessage (0x32) + Co-derived with Juggluco (also listed in section 2): gatt/OnePlusGattClient.kt, gatt/OnePlusGattClientAndroid.kt, oem/OemDeviceProfile.kt, session/OnePlusAuthStatusRx.kt, @@ -137,7 +144,9 @@ Original to AndroidAPS (no upstream provenance marker): scan/OnePlusScanResult.kt, session/OnePlusBackfill.kt, session/OnePlusBleSession.kt (reconnect/OEM orchestration; carries Juggluco-informed wake-lock / short-auth patterns but is original code), - session/OnePlusSessionStartPolicy.kt, warmup/OnePlusWarmupClock.kt. + session/OnePlusSessionStartPolicy.kt, warmup/OnePlusWarmupClock.kt, + OnePlusCalibrationOutcome.kt, session/OnePlusCalibrationQueue.kt, + session/OnePlusCalibrationGate.kt. The OEM device-profile abstraction (oem/) and the Android GATT plumbing bulk of gatt/OnePlusGattClientAndroid.kt are original AAPS implementation; only the protocol choreography within them is derived (see sections 1 and 2). diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverCalibrationTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverCalibrationTest.kt new file mode 100644 index 000000000000..4df24f114cd6 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverCalibrationTest.kt @@ -0,0 +1,286 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity +import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs +import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner +import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub +import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationQueue +import app.aaps.plugins.dexcomoneplus.session.OnePlusCpuLease +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * Who may hand a fingerstick to a sensor. + * + * The refusals checked here cannot be undone if they are wrong: a sensor keeps a calibration for + * good. Each refusal asserts the queue is still empty, or still holding the value that was already + * waiting — nothing new was accepted. + * + * The session-up cases are the range and occupied-queue refusals, which the driver only reaches + * once a session is up. + */ +class OnePlusCgmDriverCalibrationTest { + + private val now = System.currentTimeMillis() + + @Test + fun `a pre-soak sensor is never calibrated`() { + val staging = OnePlusCgmDriverReal(storeNamespace = OnePlusCgmDrivers.STAGING_NAMESPACE) + markSessionUp(staging) + + assertThat(staging.offerCalibration(glucoseMgdl = 209, bloodAtMs = now)).isFalse() + assertThat(staging.calibrationPending()).isFalse() + assertThat(staging.lastCalibrationOutcome()).isNull() + assertThat(queueOf(staging).peek()).isNull() + } + + @Test + fun `a promoted instance reads the live namespace`() { + val staging = OnePlusCgmDriverReal(storeNamespace = OnePlusCgmDrivers.STAGING_NAMESPACE) + markSessionUp(staging) + assertThat(staging.offerCalibration(glucoseMgdl = 209, bloodAtMs = now)).isFalse() + assertThat(queueOf(staging).peek()).isNull() + + staging.rebindStore(null) + + assertThat(staging.offerCalibration(glucoseMgdl = 209, bloodAtMs = now)).isTrue() + assertThat(staging.calibrationPending()).isTrue() + assertThat(queueOf(staging).peek()?.glucoseMgdl).isEqualTo(209) + } + + @Test + fun `nothing is queued without a session`() { + // No sensor is being followed at all, so nothing would ever take the value. + val production = OnePlusCgmDriverReal() + + assertThat(production.offerCalibration(glucoseMgdl = 209, bloodAtMs = now)).isFalse() + assertThat(production.calibrationPending()).isFalse() + assertThat(production.lastCalibrationOutcome()).isNull() + assertThat(queueOf(production).peek()).isNull() + } + + @Test + fun `a session between two radio windows still takes the value`() { + // A G7 / ONE+ is connected a few seconds every 5 minutes. Between two windows the session is + // not "up", and refusing there refused almost every fingerstick (field report 2026-10-11). + val production = OnePlusCgmDriverReal() + setSession(production, DownSession) + + assertThat(production.offerCalibration(glucoseMgdl = 94, bloodAtMs = now)).isTrue() + assertThat(production.calibrationPending()).isTrue() + } + + @Test + fun `a promoted pre-soak instance takes the value`() { + // A promotion keeps the instance and its session, and only rebinds the store to production. + val promoted = OnePlusCgmDriverReal(storeNamespace = OnePlusCgmDrivers.STAGING_NAMESPACE) + setSession(promoted, DownSession) + promoted.rebindStore(null) + + assertThat(promoted.offerCalibration(glucoseMgdl = 94, bloodAtMs = now)).isTrue() + assertThat(promoted.calibrationPending()).isTrue() + } + + @Test + fun `a value outside 40 to 400 is not queued`() { + val production = OnePlusCgmDriverReal() + markSessionUp(production) + + assertThat(production.offerCalibration(glucoseMgdl = 39, bloodAtMs = now)).isFalse() + assertThat(production.offerCalibration(glucoseMgdl = 401, bloodAtMs = now)).isFalse() + assertThat(production.calibrationPending()).isFalse() + assertThat(production.lastCalibrationOutcome()).isNull() + assertThat(queueOf(production).peek()).isNull() + } + + @Test + fun `a second fingerstick does not replace the one already waiting`() { + val production = OnePlusCgmDriverReal() + markSessionUp(production) + + assertThat(production.offerCalibration(glucoseMgdl = 150, bloodAtMs = now)).isTrue() + assertThat(production.offerCalibration(glucoseMgdl = 160, bloodAtMs = now)).isFalse() + assertThat(production.calibrationPending()).isTrue() + assertThat(production.lastCalibrationOutcome()).isEqualTo(OnePlusCalibrationOutcome.Pending) + assertThat(queueOf(production).peek()?.glucoseMgdl).isEqualTo(150) + } + + @Test + fun `the stub driver takes nothing and says so`() { + val stub = OnePlusCgmDriverStub() + + assertThat(stub.offerCalibration(glucoseMgdl = 209, bloodAtMs = now)).isFalse() + assertThat(stub.lastCalibrationOutcome()).isNull() + assertThat(stub.calibrationPending()).isFalse() + } + + // A value confirmed for one sensor or session must never reach the next one. Each event below + // empties the queue, so the next session has nothing to write, and says "not sent". + + @Test + fun `a disconnect drops the waiting value as not sent`() { + val production = productionWithWaitingValue() + + production.disconnect() + + assertDroppedForSensorChange(production) + } + + @Test + fun `a shutdown drops the waiting value as not sent`() { + val production = productionWithWaitingValue() + + production.shutdown() + + assertDroppedForSensorChange(production) + } + + @Test + fun `a promotion drops a value waiting on the instance`() { + val production = productionWithWaitingValue() + + production.rebindStore(null) + + assertDroppedForSensorChange(production) + } + + @Test + fun `a new sensor identity drops the waiting value`() { + val production = productionWithWaitingValue() + + production.saveIdentity(OnePlusSensorIdentity(pin = "5678")) + + assertDroppedForSensorChange(production) + } + + @Test + fun `a new pairing drops the waiting value before the new session starts`() { + val production = productionWithWaitingValue() + production.attach(NoRadioPlatform()) + + production.connect(deviceAddress = "AA:BB:CC:DD:EE:01", pairingCode = "5678") + + assertDroppedForSensorChange(production) + production.shutdown() + } + + @Test + fun `a session restart drops the value waiting for the session that ended`() { + val production = OnePlusCgmDriverReal() + production.attach(NoRadioPlatform()) + production.saveIdentity(OnePlusSensorIdentity(pin = "1234")) + production.sensorStore()?.saveLastMac("AA:BB:CC:DD:EE:02") + production.sensorStore()?.saveSharedKey(ByteArray(16) { 1 }) + setSession(production, DownSession) + assertThat(production.offerCalibration(glucoseMgdl = 150, bloodAtMs = now)).isTrue() + // The session ends on its own (released), and the watchdog resumes a new one. + setSession(production, null) + + assertThat(production.resumeStoredSession()).isTrue() + + assertDroppedForSensorChange(production) + production.shutdown() + } + + private fun productionWithWaitingValue(): OnePlusCgmDriverReal { + val production = OnePlusCgmDriverReal() + setSession(production, DownSession) + assertThat(production.offerCalibration(glucoseMgdl = 150, bloodAtMs = now)).isTrue() + assertThat(production.calibrationPending()).isTrue() + return production + } + + private fun assertDroppedForSensorChange(driver: OnePlusCgmDriverReal) { + assertThat(driver.calibrationPending()).isFalse() + assertThat(queueOf(driver).peek()).isNull() + assertThat(driver.lastCalibrationOutcome()) + .isEqualTo(OnePlusCalibrationOutcome.NotSent(OnePlusCalibrationOutcome.NotSent.Reason.SENSOR_CHANGED)) + } + + private fun markSessionUp(driver: OnePlusCgmDriverReal) = setSession(driver, UpSession) + + private fun setSession(driver: OnePlusCgmDriverReal, session: OnePlusBleSession?) { + val field = OnePlusCgmDriverReal::class.java.getDeclaredField("session") + field.isAccessible = true + field.set(driver, session) + } + + private fun queueOf(driver: OnePlusCgmDriverReal): OnePlusCalibrationQueue { + val field = OnePlusCgmDriverReal::class.java.getDeclaredField("calibrationQueue") + field.isAccessible = true + return field.get(driver) as OnePlusCalibrationQueue + } + + private object UpSession : FakeSession(up = true) + + private object DownSession : FakeSession(up = false) + + private open class FakeSession(private val up: Boolean) : OnePlusBleSession { + override fun startWithPairingCode(deviceAddress: String, pairingCode: String) = Unit + override fun stop(reason: String?) = Unit + override fun isUp(): Boolean = up + override fun warmupState(): OnePlusWarmupState = + OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY) + } + + /** + * A host with stores and a scanner but no radio. A session that a test starts fails at once on + * the BLE thread when it asks for a GATT client, so nothing is ever written to a sensor. + */ + private class NoRadioPlatform : OnePlusPlatform { + + private val files = mutableMapOf() + + override fun sensorPrefs(fileName: String): OnePlusSensorPrefs = files.getOrPut(fileName) { MemoryPrefs() } + override fun scanner(hint: OnePlusStoredSession?, slot: String): OnePlusBleScanner = OnePlusBleScannerStub() + override fun gattClient(profile: OemDeviceProfile): OnePlusGattClient = + throw IllegalStateException("no radio in this test") + + override fun cpuLease(slot: String): OnePlusCpuLease = object : OnePlusCpuLease { + override fun hold(maxMillis: Long): OnePlusCpuLease.Hold? = null + } + } + + private class MemoryPrefs : OnePlusSensorPrefs { + + private val values = mutableMapOf() + + override fun getString(key: String): String? = values[key] as? String + override fun getLong(key: String, defaultValue: Long): Long = values[key] as? Long ?: defaultValue + override fun getInt(key: String, defaultValue: Int): Int = values[key] as? Int ?: defaultValue + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = values[key] as? Boolean ?: defaultValue + override fun contains(key: String): Boolean = values.containsKey(key) + + override fun edit(block: OnePlusSensorPrefs.Editor.() -> Unit) { + object : OnePlusSensorPrefs.Editor { + override fun putString(key: String, value: String?) { + if (value == null) values.remove(key) else values[key] = value + } + + override fun putLong(key: String, value: Long) { + values[key] = value + } + + override fun putInt(key: String, value: Int) { + values[key] = value + } + + override fun putBoolean(key: String, value: Boolean) { + values[key] = value + } + + override fun remove(key: String) { + values.remove(key) + } + + override fun clear() { + values.clear() + } + }.block() + } + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateEchoTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateEchoTest.kt new file mode 100644 index 000000000000..697ce497e0fa --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateEchoTest.kt @@ -0,0 +1,93 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * What a G7 / Dexcom ONE+ answers to a calibration: the opcode 0x34 again, then a status where 1 + * means the value was taken. Read as in AAPS PR 5397 (`G7CalibrateRxMessage`). + */ +class OnePlusCalibrateEchoTest { + + private fun bytes(vararg values: Int): ByteArray = values.map { it.toByte() }.toByteArray() + + @Test + fun `the ONE+ echo is decoded instead of being dropped`() { + val parsed = OnePlusCalibrateRx.parse(bytes(0x34, 0x00, 0x01, 0x00))!! + + assertThat(parsed.valid).isTrue() + assertThat(parsed.form).isEqualTo(OnePlusCalibrateRx.Form.Echo) + assertThat(parsed.rawHex).isEqualTo("34000100") + } + + @Test + fun `echo status 1 is an acceptance`() { + val parsed = OnePlusCalibrateRx.parse(bytes(0x34, 0x00, 0x01, 0x00))!! + + assertThat(parsed.accepted()).isTrue() + assertThat(parsed.outcome()).isEqualTo(OnePlusCalibrateRx.Outcome.ACCEPTED) + } + + @Test + fun `any other echo status is a refusal`() { + for (status in listOf(bytes(0x34, 0x00, 0x00, 0x00), bytes(0x34, 0x00, 0x02, 0x00), bytes(0x34, 0x00, 0x01, 0x01))) { + val parsed = OnePlusCalibrateRx.parse(status)!! + + assertThat(parsed.accepted()).isFalse() + assertThat(parsed.wantsSecondCalibration()).isFalse() + assertThat(parsed.outcome()).isEqualTo(OnePlusCalibrateRx.Outcome.REFUSED) + } + } + + @Test + fun `a longer echo is still read`() { + assertThat(OnePlusCalibrateRx.parse(bytes(0x34, 0x00, 0x01, 0x00, 0x00))!!.accepted()).isTrue() + } + + @Test + fun `an echo carries its raw bytes into the message, so a field report has them`() { + val parsed = OnePlusCalibrateRx.parse(bytes(0x34, 0x00, 0x02, 0x00))!! + + assertThat(parsed.message()).contains("34000200") + } + + @Test + fun `the G5 style answer still decodes and still says yes or no`() { + val ok = ByteArray(5).also { + it[0] = OnePlusCalibrateRx.OPCODE + it[1] = 0x00 + it[2] = OnePlusCalibrateRx.OK.toByte() + val crc = OnePlusFastCrc16.calculate(it, 3) + it[3] = crc[0] + it[4] = crc[1] + } + val parsed = OnePlusCalibrateRx.parse(ok)!! + + assertThat(parsed.form).isEqualTo(OnePlusCalibrateRx.Form.Status) + assertThat(parsed.accepted()).isTrue() + assertThat(parsed.outcome()).isEqualTo(OnePlusCalibrateRx.Outcome.ACCEPTED) + } + + @Test + fun `a refusal stays a refusal and not an unknown`() { + val refused = ByteArray(5).also { + it[0] = OnePlusCalibrateRx.OPCODE + it[1] = 0x00 + it[2] = OnePlusCalibrateRx.NOT_READY.toByte() + val crc = OnePlusFastCrc16.calculate(it, 3) + it[3] = crc[0] + it[4] = crc[1] + } + val parsed = OnePlusCalibrateRx.parse(refused)!! + + assertThat(parsed.outcome()).isEqualTo(OnePlusCalibrateRx.Outcome.REFUSED) + assertThat(parsed.message()).isEqualTo("Not ready to calibrate") + } + + @Test + fun `a packet that is neither shape is still refused`() { + assertThat(OnePlusCalibrateRx.parse(bytes(0x4e, 0x00, 0x01, 0x00))).isNull() + assertThat(OnePlusCalibrateRx.parse(bytes(0x35, 0x00, 0x00, 0xff, 0xff))).isNull() + assertThat(OnePlusCalibrateRx.parse(bytes(0x34, 0x00, 0x01))).isNull() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateMessageTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateMessageTest.kt new file mode 100644 index 000000000000..e311d78b6384 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateMessageTest.kt @@ -0,0 +1,76 @@ +package app.aaps.plugins.dexcomoneplus.parse + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * The bytes of the calibration exchange, checked against xDrip's `CalibrateTxMessage` / + * `CalibrateRxMessage`. + * + * Nothing here sends anything. A value outside 40..400 produces no packet. + */ +class OnePlusCalibrateMessageTest { + + private fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) } + + @Test + fun `the packet is opcode, glucose and sensor time, little endian, without a CRC`() { + val packet = OnePlusCalibrateTx.build(glucoseMgdl = 150, dexTimeSeconds = 0x01020304)!! + + assertThat(packet).hasLength(7) + assertThat(hex(packet)).isEqualTo("34960004030201") + } + + @Test + fun `a value the sensor would refuse is never built`() { + assertThat(OnePlusCalibrateTx.build(glucoseMgdl = 39, dexTimeSeconds = 1000)).isNull() + assertThat(OnePlusCalibrateTx.build(glucoseMgdl = 401, dexTimeSeconds = 1000)).isNull() + assertThat(OnePlusCalibrateTx.build(glucoseMgdl = 150, dexTimeSeconds = -1)).isNull() + assertThat(OnePlusCalibrateTx.build(glucoseMgdl = 40, dexTimeSeconds = 1000)).isNotNull() + assertThat(OnePlusCalibrateTx.build(glucoseMgdl = 400, dexTimeSeconds = 1000)).isNotNull() + } + + @Test + fun `the field case, sensor 60 and blood 150, builds cleanly`() { + val packet = OnePlusCalibrateTx.build(glucoseMgdl = 150, dexTimeSeconds = 123_456) + + assertThat(packet).isNotNull() + assertThat(packet!!).hasLength(OnePlusCalibrateTx.PACKET_LENGTH) + } + + private fun reply(result: Int): ByteArray { + val packet = byteArrayOf(OnePlusCalibrateRx.OPCODE, 0x00, result.toByte(), 0, 0) + val crc = OnePlusFastCrc16.calculate(packet, OnePlusCalibrateRx.PACKET_LENGTH - 2) + packet[3] = crc[0] + packet[4] = crc[1] + return packet + } + + @Test + fun `the three accepted answers are read as accepted`() { + assertThat(OnePlusCalibrateRx.parse(reply(OnePlusCalibrateRx.OK))!!.accepted()).isTrue() + assertThat(OnePlusCalibrateRx.parse(reply(OnePlusCalibrateRx.DUPLICATE))!!.accepted()).isTrue() + val second = OnePlusCalibrateRx.parse(reply(OnePlusCalibrateRx.SECOND_NEEDED))!! + assertThat(second.accepted()).isTrue() + assertThat(second.wantsSecondCalibration()).isTrue() + } + + @Test + fun `a refusal is a refusal, and says why`() { + val rejected = OnePlusCalibrateRx.parse(reply(OnePlusCalibrateRx.REJECTED))!! + assertThat(rejected.accepted()).isFalse() + assertThat(rejected.message()).isEqualTo("Rejected") + assertThat(OnePlusCalibrateRx.parse(reply(OnePlusCalibrateRx.NOT_READY))!!.message()) + .isEqualTo("Not ready to calibrate") + assertThat(OnePlusCalibrateRx.parse(reply(OnePlusCalibrateRx.STOPPED))!!.accepted()).isFalse() + } + + @Test + fun `a packet that is not a calibration answer is not read as one`() { + assertThat(OnePlusCalibrateRx.parse(byteArrayOf(0x4e, 0x00, 0x00, 0x00, 0x00))).isNull() + assertThat(OnePlusCalibrateRx.parse(byteArrayOf(OnePlusCalibrateRx.OPCODE, 0x00, 0x00))).isNull() + val broken = reply(OnePlusCalibrateRx.OK) + broken[4] = (broken[4] + 1).toByte() + assertThat(OnePlusCalibrateRx.parse(broken)).isNull() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGateTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGateTest.kt new file mode 100644 index 000000000000..37e048dde63d --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGateTest.kt @@ -0,0 +1,71 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate.Refusal +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OnePlusCalibrationGateTest { + + private val now = 1_700_000_000_000L + + private fun reading(ageMs: Long = 60_000L, rate: Double? = 0.5) = + OnePlusGlucoseSample(mgdl = 120.0, timestampMs = now - ageMs, trendSlopeMgdlPerMin = rate) + + private fun check( + glucose: Int = 120, + bloodAgoMs: Long = 60_000L, + phase: OnePlusWarmupState.Phase = OnePlusWarmupState.Phase.READY, + last: OnePlusGlucoseSample? = reading(), + ) = OnePlusCalibrationGate.check(glucose, now - bloodAgoMs, now, phase, last) + + @Test + fun `a stable sensor with a fresh reading takes the value`() { + assertThat(check()).isNull() + } + + @Test + fun `the gap between two radio windows is not a reason to refuse`() { + assertThat(check(phase = OnePlusWarmupState.Phase.RECONNECTING)).isNull() + assertThat(check(phase = OnePlusWarmupState.Phase.CONNECTING)).isNull() + } + + @Test + fun `values outside 40 to 400 are refused`() { + assertThat(check(glucose = 39)).isEqualTo(Refusal.OUT_OF_RANGE) + assertThat(check(glucose = 401)).isEqualTo(Refusal.OUT_OF_RANGE) + assertThat(check(glucose = 40)).isNull() + assertThat(check(glucose = 400)).isNull() + } + + @Test + fun `blood older than one hour or in the future is refused`() { + assertThat(check(bloodAgoMs = 61L * 60_000L)).isEqualTo(Refusal.TOO_OLD) + assertThat(check(bloodAgoMs = -60_000L)).isEqualTo(Refusal.TOO_OLD) + } + + @Test + fun `a warming or failed sensor is refused`() { + assertThat(check(phase = OnePlusWarmupState.Phase.WARMING)).isEqualTo(Refusal.NOT_READY) + assertThat(check(phase = OnePlusWarmupState.Phase.FAILED)).isEqualTo(Refusal.NOT_READY) + } + + @Test + fun `no recent reading is refused`() { + assertThat(check(last = null)).isEqualTo(Refusal.NO_RECENT_READING) + assertThat(check(last = reading(ageMs = OnePlusCalibrationGate.RECENT_READING_MS + 1))).isEqualTo(Refusal.NO_RECENT_READING) + } + + @Test + fun `glucose changing faster than 2 per minute is refused in both directions`() { + assertThat(check(last = reading(rate = 2.1))).isEqualTo(Refusal.CHANGING_TOO_FAST) + assertThat(check(last = reading(rate = -2.1))).isEqualTo(Refusal.CHANGING_TOO_FAST) + assertThat(check(last = reading(rate = 2.0))).isNull() + } + + @Test + fun `a reading without a trend is refused`() { + assertThat(check(last = reading(rate = null))).isEqualTo(Refusal.RATE_UNKNOWN) + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueueTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueueTest.kt new file mode 100644 index 000000000000..1a19284a0fe0 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueueTest.kt @@ -0,0 +1,116 @@ +package app.aaps.plugins.dexcomoneplus.session + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** The one slot a fingerstick waits in, and the transmitter time it is sent with. */ +class OnePlusCalibrationQueueTest { + + private val now = 1_700_000_000_000L + private val minute = 60L * 1000L + + @Test + fun `a fresh fingerstick in range is taken, once`() { + val queue = OnePlusCalibrationQueue() + + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 2 * minute, nowMs = now)).isTrue() + assertThat(queue.offer(glucoseMgdl = 160, bloodAtMs = now, nowMs = now)).isFalse() + + val taken = queue.take() + assertThat(taken?.glucoseMgdl).isEqualTo(150) + assertThat(queue.take()).isNull() + assertThat(queue.offer(glucoseMgdl = 160, bloodAtMs = now, nowMs = now)).isTrue() + } + + @Test + fun `take of an expected value leaves a value that replaced it`() { + // The send path checks a value, then takes it. If the slot changed in between, the new value + // was not checked, so it must stay where it is. + val queue = OnePlusCalibrationQueue() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now, nowMs = now)).isTrue() + val checked = queue.peek()!! + val muchLater = now + 61 * minute + assertThat(queue.offer(glucoseMgdl = 94, bloodAtMs = muchLater, nowMs = muchLater)).isTrue() + + assertThat(queue.take(checked)).isFalse() + assertThat(queue.peek()?.glucoseMgdl).isEqualTo(94) + assertThat(queue.take(queue.peek()!!)).isTrue() + assertThat(queue.peek()).isNull() + } + + @Test + fun `a value left waiting for more than an hour does not block the next one`() { + // The sensor stayed out of reach, so nothing took the first value. It would be dropped at + // sending anyway, and it must not refuse every new fingerstick until an app restart. + val queue = OnePlusCalibrationQueue() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now, nowMs = now)).isTrue() + + val later = now + 59 * minute + assertThat(queue.offer(glucoseMgdl = 94, bloodAtMs = later, nowMs = later)).isFalse() + + val muchLater = now + 61 * minute + assertThat(queue.offer(glucoseMgdl = 94, bloodAtMs = muchLater, nowMs = muchLater)).isTrue() + assertThat(queue.peek()?.glucoseMgdl).isEqualTo(94) + } + + @Test + fun `out of range, in the future, or too old is refused at the door`() { + val queue = OnePlusCalibrationQueue() + + assertThat(queue.offer(glucoseMgdl = 39, bloodAtMs = now, nowMs = now)).isFalse() + assertThat(queue.offer(glucoseMgdl = 401, bloodAtMs = now, nowMs = now)).isFalse() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now + minute, nowMs = now)).isFalse() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 61 * minute, nowMs = now)).isFalse() + assertThat(queue.peek()).isNull() + } + + @Test + fun `the sent time is the time of the blood, not of the sending`() { + val dex = OnePlusCalibrationQueue.dexTimeForBlood( + bloodAtMs = now - 5 * minute, + nowMs = now, + lastDexTimeSeconds = 10_000, + lastDexTimeAtMs = now - 30 * 1000L, + ) + + assertThat(dex).isEqualTo(9_730) + } + + @Test + fun `without a known transmitter clock nothing is sent`() { + assertThat( + OnePlusCalibrationQueue.dexTimeForBlood( + bloodAtMs = now - minute, + nowMs = now, + lastDexTimeSeconds = 0, + lastDexTimeAtMs = now, + ), + ).isNull() + assertThat( + OnePlusCalibrationQueue.dexTimeForBlood( + bloodAtMs = now - minute, + nowMs = now, + lastDexTimeSeconds = 10_000, + lastDexTimeAtMs = 0L, + ), + ).isNull() + } + + @Test + fun `a fingerstick older than the transmitter session cannot be dated`() { + assertThat( + OnePlusCalibrationQueue.dexTimeForBlood( + bloodAtMs = now - 50 * minute, + nowMs = now, + lastDexTimeSeconds = 60, + lastDexTimeAtMs = now, + ), + ).isNull() + } + + @Test + fun `an hour is the limit`() { + assertThat(OnePlusCalibrationQueue.isTooOld(now - 59 * minute, now)).isFalse() + assertThat(OnePlusCalibrationQueue.isTooOld(now - 61 * minute, now)).isTrue() + } +} diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvCalibrationGateTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvCalibrationGateTest.kt new file mode 100644 index 000000000000..745990bfb424 --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvCalibrationGateTest.kt @@ -0,0 +1,328 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusKeksNotify +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateTx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationBoundsRx +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * The Control loop may build opcode 0x34 only after a fingerstick has been taken from the queue, + * the checks at send time have passed and the transmitter clock is known. An empty queue, a failed + * check, or a clock that is still unknown, writes nothing of that opcode. + */ +class OnePlusEgvCalibrationGateTest { + + @Test + fun `an empty queue writes no calibrate frame`() { + val gatt = RecordingGatt() + val session = OnePlusEgvSession(gatt = gatt, calibrationQueue = null) + + runOneTurn(session) + + assertThat(calibrateFrames(gatt)).isEmpty() + } + + @Test + fun `a queued value stays queued and unsent while the transmitter clock is unknown`() { + val gatt = RecordingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val session = OnePlusEgvSession(gatt = gatt, calibrationQueue = queue, calibrationSendCheck = allowAll) + + runOneTurn(session) + + assertThat(calibrateFrames(gatt)).isEmpty() + assertThat(queue.peek()?.glucoseMgdl).isEqualTo(150) + } + + @Test + fun `a known transmitter clock writes opcode 0x34 and then the slot is empty`() { + val gatt = RecordingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val session = OnePlusEgvSession(gatt = gatt, calibrationQueue = queue, calibrationSendCheck = allowAll) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + runOneTurn(session) + + val frames = calibrateFrames(gatt) + assertThat(frames).hasSize(1) + assertThat(frames.single()[0]).isEqualTo(OnePlusCalibrateTx.OPCODE) + assertThat(queue.peek()).isNull() + } + + @Test + fun `a write that throws leaves no frame and reports no acceptance`() { + val gatt = ThrowingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val results = mutableListOf() + val session = OnePlusEgvSession( + gatt = gatt, + calibrationQueue = queue, + onCalibrationResult = { results += it }, + calibrationSendCheck = allowAll, + ) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + runOneTurn(session) + + assertThat(gatt.writes).isEmpty() + assertThat(queue.peek()).isNull() + assertThat(results).containsExactly(null) + } + + @Test + fun `a lost answer is settled by the calibration state and the value is never sent twice`() { + val now = System.currentTimeMillis() + // Blood 60 s ago, clock read 30 s ago at 10 000 s: the value is for sensor second 9 970. + val gatt = ScriptedGatt(statePacket = boundsPacket(glucose = 150, timeSeconds = 9_970)) + val queue = OnePlusCalibrationQueue() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val answers = mutableListOf() + val states = mutableListOf>() + val session = OnePlusEgvSession( + gatt = gatt, + calibrationQueue = queue, + onCalibrationResult = { answers += it }, + onCalibrationState = { state, matches -> states += state to matches }, + calibrationSendCheck = allowAll, + ) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + // The calibration exchange asks shouldContinue several times; a single turn would stop it early. + runTurns(session, calls = 12) + + assertThat(answers).containsExactly(null) + assertThat(states).hasSize(1) + assertThat(states.single().second).isTrue() + assertThat(states.single().first.processing).isEqualTo(OnePlusCalibrationBoundsRx.Processing.IN_PROGRESS) + assertThat(gatt.writes.count { it[0] == OnePlusCalibrateTx.OPCODE }).isEqualTo(1) + assertThat(gatt.writes.count { it[0] == OnePlusCalibrationBoundsRx.OPCODE }).isEqualTo(1) + } + + @Test + fun `a sensor back in warm-up at send time drops the value as not sent, before any write`() { + val gatt = RecordingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val stable = OnePlusGlucoseSample(mgdl = 150.0, timestampMs = now - 60_000L, sequence = 1L, trendSlopeMgdlPerMin = 0.5) + val answers = mutableListOf() + val notSent = mutableListOf() + val session = OnePlusEgvSession( + gatt = gatt, + calibrationQueue = queue, + onCalibrationResult = { answers += it }, + // The real checks, on a sensor that went back to warm-up after the user confirmed. + calibrationSendCheck = { glucose, bloodAt, nowMs -> + OnePlusCalibrationGate.check(glucose, bloodAt, nowMs, OnePlusWarmupState.Phase.WARMING, stable) + }, + onCalibrationNotSent = { notSent += it }, + ) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + runOneTurn(session) + + assertThat(calibrateFrames(gatt)).isEmpty() + assertThat(queue.peek()).isNull() + assertThat(notSent).containsExactly(OnePlusCalibrationOutcome.NotSent.Reason.NOT_READY) + // Nothing went out, so it is not "unknown". + assertThat(answers).isEmpty() + } + + @Test + fun `glucose changing fast at send time drops the value as not sent`() { + val gatt = RecordingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val fast = OnePlusGlucoseSample(mgdl = 150.0, timestampMs = now - 60_000L, sequence = 1L, trendSlopeMgdlPerMin = 3.5) + val notSent = mutableListOf() + val session = OnePlusEgvSession( + gatt = gatt, + calibrationQueue = queue, + calibrationSendCheck = { glucose, bloodAt, nowMs -> + OnePlusCalibrationGate.check(glucose, bloodAt, nowMs, OnePlusWarmupState.Phase.READY, fast) + }, + onCalibrationNotSent = { notSent += it }, + ) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + runOneTurn(session) + + assertThat(calibrateFrames(gatt)).isEmpty() + assertThat(notSent).containsExactly(OnePlusCalibrationOutcome.NotSent.Reason.CHANGING_TOO_FAST) + } + + @Test + fun `a value over one hour old is dropped as not sent, never as unknown`() { + val gatt = RecordingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + // Offered while it was still fresh, then the sensor stayed out of reach for over an hour. + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 61 * 60_000L, nowMs = now - 30 * 60_000L)).isTrue() + val answers = mutableListOf() + val notSent = mutableListOf() + val session = OnePlusEgvSession( + gatt = gatt, + calibrationQueue = queue, + onCalibrationResult = { answers += it }, + calibrationSendCheck = allowAll, + onCalibrationNotSent = { notSent += it }, + ) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + runOneTurn(session) + + assertThat(calibrateFrames(gatt)).isEmpty() + assertThat(notSent).containsExactly(OnePlusCalibrationOutcome.NotSent.Reason.TOO_OLD) + assertThat(answers).isEmpty() + } + + @Test + fun `a session given a queue but no check writes nothing`() { + val gatt = RecordingGatt() + val queue = OnePlusCalibrationQueue() + val now = System.currentTimeMillis() + assertThat(queue.offer(glucoseMgdl = 150, bloodAtMs = now - 60_000L, nowMs = now)).isTrue() + val session = OnePlusEgvSession(gatt = gatt, calibrationQueue = queue) + setDexClock(session, seconds = 10_000, atMs = now - 30_000L) + + runOneTurn(session) + + assertThat(calibrateFrames(gatt)).isEmpty() + } + + /** Every check passes: for the tests about the write itself. */ + private val allowAll: (Int, Long, Long) -> OnePlusCalibrationGate.Refusal? = { _, _, _ -> null } + + private fun boundsPacket(glucose: Int, timeSeconds: Int): ByteArray = ByteArray(OnePlusCalibrationBoundsRx.PACKET_LENGTH).also { + it[0] = OnePlusCalibrationBoundsRx.OPCODE + it[7] = glucose.toByte() + it[8] = (glucose shr 8).toByte() + it[9] = timeSeconds.toByte() + it[10] = (timeSeconds shr 8).toByte() + it[11] = (timeSeconds shr 16).toByte() + it[12] = (timeSeconds shr 24).toByte() + it[13] = OnePlusCalibrationBoundsRx.Processing.IN_PROGRESS.code.toByte() + it[14] = 1 + } + + /** No answer to the calibration itself; the calibration state request gets [statePacket]. */ + private class ScriptedGatt(private val statePacket: ByteArray) : OnePlusGattClient by IdleGatt() { + val writes = mutableListOf() + private var next: ByteArray? = null + + override fun isConnected(): Boolean = true + + override fun writeControl(payload: ByteArray?) { + if (payload == null) return + writes.add(payload.copyOf()) + if (payload.isNotEmpty() && payload[0] == OnePlusCalibrationBoundsRx.OPCODE) next = statePacket + } + + override fun enableControlIndications() = Unit + + override fun enableControlNotifications() = Unit + + override fun awaitControlNotify(timeoutMs: Long): ByteArray? = next.also { next = null } + } + + private fun runTurns(session: OnePlusEgvSession, calls: Int) { + var left = calls + session.run(shouldContinue = { left-- > 0 }, notifyTimeoutMs = 1L, rewriteIntervalMs = Long.MAX_VALUE) + } + + private fun runOneTurn(session: OnePlusEgvSession) { + var entered = false + session.run( + shouldContinue = { + if (!entered) { + entered = true + true + } else { + false + } + }, + notifyTimeoutMs = 1L, + rewriteIntervalMs = Long.MAX_VALUE, + ) + } + + private fun calibrateFrames(gatt: RecordingGatt): List = + gatt.writes.filter { it.isNotEmpty() && it[0] == OnePlusCalibrateTx.OPCODE } + + private fun setDexClock(session: OnePlusEgvSession, seconds: Int, atMs: Long) { + val secondsField = OnePlusEgvSession::class.java.getDeclaredField("lastDexTimeSeconds") + secondsField.isAccessible = true + secondsField.setInt(session, seconds) + val atField = OnePlusEgvSession::class.java.getDeclaredField("lastDexTimeAtMs") + atField.isAccessible = true + atField.setLong(session, atMs) + } + + private class RecordingGatt : OnePlusGattClient by IdleGatt() { + val writes = mutableListOf() + + override fun isConnected(): Boolean = true + + override fun writeControl(payload: ByteArray?) { + if (payload != null) writes.add(payload.copyOf()) + } + + override fun enableControlIndications() = Unit + + override fun enableControlNotifications() = Unit + + override fun awaitControlNotify(timeoutMs: Long): ByteArray? = null + } + + private class ThrowingGatt : OnePlusGattClient by IdleGatt() { + val writes = mutableListOf() + + override fun isConnected(): Boolean = true + + override fun writeControl(payload: ByteArray?) { + if (payload != null && payload.isNotEmpty() && payload[0] == OnePlusCalibrateTx.OPCODE) { + throw IllegalStateException("control busy") + } + } + + override fun enableControlIndications() = Unit + + override fun enableControlNotifications() = Unit + + override fun awaitControlNotify(timeoutMs: Long): ByteArray? = null + } + + /** A link that does nothing and receives nothing. Each fake above replaces only what it needs. */ + private class IdleGatt : OnePlusGattClient { + override fun connect(deviceAddress: String, autoConnect: Boolean) = error("not used in this test") + override fun disconnect() = Unit + override fun isConnected(): Boolean = false + override fun writeAuthentication(payload: ByteArray?) = Unit + override fun writeExtraData(payload: ByteArray?) = Unit + override fun writeControl(payload: ByteArray?) = Unit + override fun enableControlNotifications() = Unit + override fun enableControlIndications() = Unit + override fun enableBackfillNotifications() = Unit + override fun isBonded(): Boolean = false + override fun createBond(): Boolean = false + override fun removeBond(): Boolean = false + override fun awaitBondComplete(timeoutMs: Long): Boolean = false + override fun awaitKeksNotify(timeoutMs: Long): OnePlusKeksNotify? = null + override fun awaitNotify(timeoutMs: Long): ByteArray? = null + override fun awaitControlNotify(timeoutMs: Long): ByteArray? = null + override fun awaitBackfillNotify(timeoutMs: Long): ByteArray? = null + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCalibrationOutcome.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCalibrationOutcome.kt new file mode 100644 index 000000000000..a294376ae2f6 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCalibrationOutcome.kt @@ -0,0 +1,68 @@ +package app.aaps.plugins.dexcomoneplus + +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate + +/** + * Where a fingerstick handed to the sensor got to. + * + * Kept separate from the wire type so the app side never has to know about opcodes, and so the one + * state the wire cannot express — [Pending] — has a place. + * + * [Unknown] is only for a value that was written to the sensor: it is not a failure and not a + * success. The answer was lost or could not be read, and the sensor's calibration state did not + * settle it. It must be shown as "we cannot tell", never quietly rounded to either side. A sensor + * keeps a calibration it accepted for good, so the user is told not to send the value again. + * + * [NotSent] is the opposite case: the value was dropped before anything was written, so the sensor + * never saw it and the user may enter it again. + */ +sealed interface OnePlusCalibrationOutcome { + + /** Waiting for the Control loop to reach the point where it may write. */ + data object Pending : OnePlusCalibrationOutcome + + /** The sensor said it took the value. */ + data class Accepted(val detail: String) : OnePlusCalibrationOutcome + + /** The sensor said no, and said why. */ + data class Refused(val detail: String) : OnePlusCalibrationOutcome + + /** + * Something came back that cannot be read, or nothing came back at all. + * + * @param detail the raw bytes when there were any, so a field report can carry them + */ + data class Unknown(val detail: String) : OnePlusCalibrationOutcome + + /** + * Dropped before any write: nothing reached the sensor, so the value may be entered again. + * + * @param reason why it was dropped + */ + data class NotSent(val reason: Reason) : OnePlusCalibrationOutcome { + + /** + * Why a value was dropped before the write. + * + * @param gateRefusal the check of [OnePlusCalibrationGate] that failed at send time, or null + * when the value was cleared because the sensor or its session changed + */ + enum class Reason(val gateRefusal: OnePlusCalibrationGate.Refusal?) { + + OUT_OF_RANGE(OnePlusCalibrationGate.Refusal.OUT_OF_RANGE), + TOO_OLD(OnePlusCalibrationGate.Refusal.TOO_OLD), + NOT_READY(OnePlusCalibrationGate.Refusal.NOT_READY), + NO_RECENT_READING(OnePlusCalibrationGate.Refusal.NO_RECENT_READING), + RATE_UNKNOWN(OnePlusCalibrationGate.Refusal.RATE_UNKNOWN), + CHANGING_TOO_FAST(OnePlusCalibrationGate.Refusal.CHANGING_TOO_FAST), + + /** A new sensor, a new or restarted session, or a promotion cleared the waiting value. */ + SENSOR_CHANGED(null); + + companion object { + + fun of(refusal: OnePlusCalibrationGate.Refusal): Reason = entries.first { it.gateRefusal == refusal } + } + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt index f249e82eeeb1..660627af55b3 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriver.kt @@ -47,4 +47,28 @@ interface OnePlusCgmDriver { * session is incomplete, or when a session is already running. */ fun resumeStoredSession(): Boolean = false + + /** + * Ask the running session to hand a fingerstick to the sensor's own algorithm. + * + * The value does not reach the sensor here: it waits for the Control loop to reach a point + * where it owns the characteristic, which is normally within one duty cycle. Watch + * [lastCalibrationOutcome] for what the sensor answered. + * + * A sensor keeps a calibration it accepts for good — it cannot be edited or deleted + * afterwards. Callers must have an explicit user action behind this, never an automatic rule. + * + * @param glucoseMgdl blood value, which the sensor only accepts between 40 and 400 mg/dL + * @param bloodAtMs wall clock (epoch ms) used as the time of the blood. The calibration dialog + * passes the moment the user confirmed the value, not the moment of the finger prick. + * @return false when the driver will not take it: no session, a pre-soak sensor, a value out of + * range, a fingerstick over an hour old, or another one already waiting + */ + fun offerCalibration(glucoseMgdl: Int, bloodAtMs: Long): Boolean = false + + /** What became of the last fingerstick offered, or null when none ever was. */ + fun lastCalibrationOutcome(): OnePlusCalibrationOutcome? = null + + /** True while a fingerstick is still waiting to be written. */ + fun calibrationPending(): Boolean = false } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt index db5195857f5d..11a6d187e8d6 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt @@ -8,6 +8,8 @@ import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationBoundsRx import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanListener @@ -15,6 +17,8 @@ import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanResult import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession import app.aaps.plugins.dexcomoneplus.session.OnePlusMacArbiter import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSessionSkeleton +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationQueue import app.aaps.plugins.dexcomoneplus.session.OnePlusConnectPrep import app.aaps.plugins.dexcomoneplus.session.OnePlusSessionAuthKeks import app.aaps.plugins.dexcomoneplus.session.OnePlusSessionStart @@ -22,6 +26,7 @@ import kotlin.concurrent.Volatile import kotlin.concurrent.atomics.AtomicInt import kotlin.concurrent.atomics.ExperimentalAtomicApi import kotlin.concurrent.atomics.incrementAndFetch +import kotlin.time.Clock internal object OnePlusCgmDriverResumePolicy { fun canResume(storedSession: OnePlusStoredSession?): Boolean = @@ -127,6 +132,126 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { @Volatile private var pendingAdvSightingElapsedMs: Long = 0L + /** + * Fingersticks waiting to be handed to the sensor, for this instance's sessions. + * + * One queue per driver instance, so a pre-soak sensor cannot receive the calibration meant for + * the sensor that feeds the loop. [offerCalibration] refuses outright on a staging slot, and a + * promoted instance keeps calling itself "staging" in the log but is production from the + * arbiter's point of view — which is why the check below is on [storeNamespace], read live, + * rather than on the fixed [slot] label. + * + * Every session gets this queue, the pre-soak ones too. That is safe because the refusal in + * [offerCalibration] keeps a pre-soak queue empty, and it is needed because a promotion keeps + * the session the instance had as a pre-soak: a session built without the queue would never + * send anything for the rest of the sensor's life. + */ + private val calibrationQueue = OnePlusCalibrationQueue() + + /** Last answer a sensor gave to a calibration, for the status screen. Null = nothing sent yet. */ + @Volatile + private var lastCalibrationResult: OnePlusCalibrationOutcome? = null + + /** + * Newest reading of this instance's sensor, for the checks run again right before a value is + * written ([calibrationSendCheck]). Kept across radio windows: a value is written at the start + * of a window, before that window's own reading. Forgotten when the sensor changes. + */ + @Volatile + private var lastReading: OnePlusGlucoseSample? = null + + /** + * The checks of [OnePlusCalibrationGate] at send time, on this driver's live warm-up phase and + * last reading: the sensor may have gone back to warm-up, or glucose may change fast now. + */ + private fun calibrationSendCheck(glucoseMgdl: Int, bloodAtMs: Long, nowMs: Long): OnePlusCalibrationGate.Refusal? = + OnePlusCalibrationGate.check(glucoseMgdl, bloodAtMs, nowMs, warmupState().phase, lastReading) + + /** + * Drop the waiting value, if any, because the sensor or its session changed: a new sensor, a + * new pairing, a restarted session, a promotion, a new identity, a disconnect or a shutdown. + * A value confirmed for one sensor must never be written to the next one. Nothing was written, + * so it is reported as [OnePlusCalibrationOutcome.NotSent] and the user may enter it again. + */ + private fun dropPendingCalibration(why: String) { + if (calibrationQueue.take() == null) return + lastCalibrationResult = OnePlusCalibrationOutcome.NotSent(OnePlusCalibrationOutcome.NotSent.Reason.SENSOR_CHANGED) + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: [$slot] calibration dropped before the write — $why") + } + + /** A waiting value failed the checks at send time and was dropped before any write. */ + private fun onCalibrationNotSent(reason: OnePlusCalibrationOutcome.NotSent.Reason) { + lastCalibrationResult = OnePlusCalibrationOutcome.NotSent(reason) + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] calibration outcome = $lastCalibrationResult") + } + + override fun offerCalibration(glucoseMgdl: Int, bloodAtMs: Long): Boolean { + if (storeNamespace != null) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] calibration refused — a pre-soak sensor is never calibrated", + ) + return false + } + // A session that exists but is not "up" is only between two radio windows: a G7 / ONE+ + // connects for a few seconds every 5 minutes. The value waits in the queue and is sent at + // the next connection, or dropped there when it is older than one hour. Asking for `isUp()` + // here refused almost every fingerstick. + if (session == null) { + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: [$slot] calibration refused — no session") + return false + } + val accepted = calibrationQueue.offer(glucoseMgdl, bloodAtMs, Clock.System.now().toEpochMilliseconds()) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] calibration queued=$accepted glucose=$glucoseMgdl", + ) + if (accepted) lastCalibrationResult = OnePlusCalibrationOutcome.Pending + return accepted + } + + override fun lastCalibrationOutcome(): OnePlusCalibrationOutcome? = lastCalibrationResult + + /** + * Turn what came back on the wire into something the user can be told. + * + * A null reply means the write itself failed, or nothing came back before the loop gave up. It + * is [OnePlusCalibrationOutcome.Unknown] and not a refusal: the packet may well have reached a + * sensor whose answer was lost. The calibration state read just after can still settle it. + */ + private fun onCalibrationAnswered(reply: OnePlusCalibrateRx?) { + lastCalibrationResult = when (reply?.outcome()) { + OnePlusCalibrateRx.Outcome.ACCEPTED -> OnePlusCalibrationOutcome.Accepted(reply.message()) + OnePlusCalibrateRx.Outcome.REFUSED -> OnePlusCalibrationOutcome.Refused(reply.message()) + OnePlusCalibrateRx.Outcome.UNKNOWN -> OnePlusCalibrationOutcome.Unknown(reply.message()) + null -> OnePlusCalibrationOutcome.Unknown("The sensor did not answer") + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] calibration outcome = $lastCalibrationResult", + ) + } + + /** + * The sensor's calibration state, read right after a calibration was sent. + * + * When the answer to the calibration itself was lost, a state that holds exactly the value and + * time we sent is the sensor saying it took it. The value is never sent again either way. + */ + private fun onCalibrationState(state: OnePlusCalibrationBoundsRx, matchesSent: Boolean) { + val current = lastCalibrationResult + lastCalibrationResult = when { + matchesSent && current is OnePlusCalibrationOutcome.Unknown -> + OnePlusCalibrationOutcome.Accepted("Found in the sensor's calibration state (${state.processing})") + matchesSent && current is OnePlusCalibrationOutcome.Accepted -> + OnePlusCalibrationOutcome.Accepted("${current.detail}, ${state.processing}") + else -> current + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: [$slot] calibration state matchesSent=$matchesSent " + + "processing=${state.processing} outcome=$lastCalibrationResult", + ) + } + + override fun calibrationPending(): Boolean = calibrationQueue.peek() != null + override fun attach(platform: OnePlusPlatform) { this.platform = platform val store = storeFor(platform, storeNamespace) @@ -149,11 +274,17 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { * call instead of keeping it in a local (see `createSession`). */ fun rebindStore(namespace: String?) { + // A promotion: from here on this instance feeds the loop. Start with an empty queue. + dropPendingCalibration("promotion") + lastReading = null storeNamespace = namespace platform?.let { sensorStore = storeFor(it, namespace) } } fun saveIdentity(identity: OnePlusSensorIdentity) { + // Only the start screen calls this, right before a new connect: a new sensor or a new code. + dropPendingCalibration("new sensor identity") + lastReading = null sensorStore?.saveIdentity(identity) scanner.updateSessionHint(sensorStore?.load()) } @@ -264,6 +395,9 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { Triple(previous, newGeneration, bleExecutor) } previousSession?.stop("superseded") + // A new pairing is a new sensor, or a new session on it. + dropPendingCalibration("new pairing") + lastReading = null sensorStore?.saveIdentity( OnePlusSensorIdentity( pin = pairingCode, @@ -359,6 +493,8 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { scanner.updateSessionHint(stored) queuedGeneration to queuedExecutor } + // A restarted session: a value confirmed for the session that ended does not carry over. + dropPendingCalibration("session restart") OnePlusLog.i( "${OnePlusLogMarkers.SESSION}: [$slot] auto-resume queued mac=***${deviceAddress.takeLast(5)} " + "savedKey=true newStart=false", @@ -430,6 +566,7 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { session.also { session = null } } previousSession?.stop("disconnect") + dropPendingCalibration("disconnect") OnePlusMacArbiter.release(arbiterOwner) } @@ -452,6 +589,7 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { previousSession?.stop("shutdown") } catch (_: Throwable) { } + dropPendingCalibration("shutdown") watchersLock.withLock { watchers.clear() } previousExecutor.shutdownNow() OnePlusMacArbiter.release(arbiterOwner) @@ -491,6 +629,7 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { }, onGlucose = { sample -> ifCurrentOperation(generation) { + if (sample.timestampMs > (lastReading?.timestampMs ?: Long.MIN_VALUE)) lastReading = sample watchersSnapshot().forEach { it.onGlucose(sample) } } }, @@ -517,6 +656,12 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { }, cpuLease = host.cpuLease(slot), slot = slot, + // Always passed, see [calibrationQueue]: the pre-soak refusal lives in offerCalibration. + calibrationQueue = calibrationQueue, + onCalibrationResult = { reply -> onCalibrationAnswered(reply) }, + onCalibrationState = { state, matchesSent -> onCalibrationState(state, matchesSent) }, + calibrationSendCheck = { glucoseMgdl, bloodAtMs, nowMs -> calibrationSendCheck(glucoseMgdl, bloodAtMs, nowMs) }, + onCalibrationNotSent = { reason -> onCalibrationNotSent(reason) }, ) return created } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateRx.kt new file mode 100644 index 000000000000..b5228f2e2526 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateRx.kt @@ -0,0 +1,133 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * What the sensor answered to a calibration. + * + * There are two shapes. + * + * [Form.Echo] is the G7 answer, and what a Dexcom ONE+ sends: 4 bytes or more, `34 | info | + * status (u16 LE)`. Status 1 means the sensor took the value; anything else is a refusal. This is + * how the Dexcom G7 driver of AAPS PR 5397 reads it, tested on G7 sensors. The two public ONE+ + * captures, `34 00 01 00` and `34 00 02 00`, are then one acceptance and one refusal. + * + * [Form.Status] is the G5/G6 answer xDrip documents: opcode 0x35, 5 bytes `opcode | info | result | + * crc16`. Kept in case a sensor answers that way. + * + * Provenance: xDrip `CalibrateRxMessage` (GPL-3.0) for the 0x35 shape; AAPS PR 5397 + * (`G7CalibrateRxMessage`) for the echo. + */ +data class OnePlusCalibrateRx( + val info: Int, + val result: Int, + val valid: Boolean, + val form: Form = Form.Status, + /** The bytes exactly as they arrived, so an unread answer can still be reported and studied. */ + val rawHex: String = "", +) { + + enum class Form { + + /** Opcode 0x35, result byte readable against the code table below. */ + Status, + + /** The G7 / ONE+ answer: opcode 0x34 again, then a status where 1 means taken. */ + Echo + } + + enum class Outcome { + + /** The sensor said it took the value. */ + ACCEPTED, + + /** The sensor said no, and said why. */ + REFUSED, + + /** Something came back that we cannot read. It may or may not have been taken. */ + UNKNOWN + } + + fun outcome(): Outcome = when { + !valid -> Outcome.UNKNOWN + accepted() -> Outcome.ACCEPTED + else -> Outcome.REFUSED + } + + /** + * The sensor took the value. For an echo that is status [ECHO_ACCEPTED]. For the 0x35 answer, + * [SECOND_NEEDED] and [DUPLICATE] are accepted outcomes too. + */ + fun accepted(): Boolean = valid && when (form) { + Form.Echo -> result == ECHO_ACCEPTED + Form.Status -> result == OK || result == SECOND_NEEDED || result == DUPLICATE + } + + /** The sensor took it and asks for a second fingerstick before it fully trusts itself again. */ + fun wantsSecondCalibration(): Boolean = valid && form == Form.Status && result == SECOND_NEEDED + + fun message(): String = when { + !valid -> "Unable to decode" + form == Form.Echo -> if (result == ECHO_ACCEPTED) "Accepted ($rawHex)" else "Refused, status $result ($rawHex)" + result == OK -> "OK" + result == 0x01 -> "Code 1" + result == SECOND_NEEDED -> "Second calibration needed" + result == REJECTED -> "Rejected" + result == STOPPED -> "Sensor stopped" + result == DUPLICATE -> "Duplicate" + result == NOT_READY -> "Not ready to calibrate" + else -> "Unknown code: $result" + } + + companion object { + + const val OPCODE: Byte = 0x35 + const val PACKET_LENGTH: Int = 5 + + /** A G7 / ONE+ answers by echoing the request opcode instead of using [OPCODE]. */ + const val ECHO_OPCODE: Byte = OnePlusCalibrateTx.OPCODE + const val ECHO_PACKET_LENGTH: Int = 4 + + /** Echo status for "taken". */ + const val ECHO_ACCEPTED = 1 + + const val OK = 0x00 + const val SECOND_NEEDED = 0x06 + const val REJECTED = 0x08 + const val STOPPED = 0x0B + const val DUPLICATE = 0x0D + const val NOT_READY = 0x0E + + /** + * Read an answer to a calibration, or null when the packet is something else entirely. + * + * Only ever called while a calibration reply is being waited for, so a 0x34-prefixed packet + * here is an answer to our own request and not a stray command. + */ + fun parse(packet: ByteArray): OnePlusCalibrateRx? { + if (packet.size >= ECHO_PACKET_LENGTH && packet[0] == ECHO_OPCODE) { + return OnePlusCalibrateRx( + info = packet[1].toInt() and 0xff, + result = (packet[2].toInt() and 0xff) or ((packet[3].toInt() and 0xff) shl 8), + valid = true, + form = Form.Echo, + rawHex = packet.toHex(), + ) + } + if (packet.size != PACKET_LENGTH) return null + if (packet[0] != OPCODE) return null + if (!OnePlusFastCrc16.check(packet)) return null + val data = OnePlusByteReader(packet) + data.skip(1) // opcode + val info = data.u8() + val result = data.u8() + return OnePlusCalibrateRx( + info = info, + result = result, + valid = true, + form = Form.Status, + rawHex = packet.toHex(), + ) + } + + private fun ByteArray.toHex(): String = onePlusToHex() + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateTx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateTx.kt new file mode 100644 index 000000000000..2fb39777cf0b --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrateTx.kt @@ -0,0 +1,45 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * Control Calibrate request (opcode 0x34) — hands a fingerstick to the sensor's own algorithm. + * + * Layout (7 bytes, no CRC): opcode | glucose (u16 LE, mg/dL) | sensor time (u32 LE) + * + * This is the G7 layout used by the Dexcom G7 driver of AAPS PR 5397, which was tested on G7 + * sensors. The earlier layout of this file was xDrip's G6 message with a CRC on the end (9 + * bytes). A ONE+ answered that one with `34 00 02 00`, which the G7 layout reads as a refusal. + * Whether the ONE+ takes the 7-byte form has to be seen on a real sensor: check the answer in + * the log the first time. + * + * The time is the time given for the blood, in sensor seconds, not the moment the value is sent: + * the sensor needs it to line the fingerstick up with its own history. The calibration dialog + * gives the moment the user confirmed the value, which is a little after the finger prick. A + * value whose time is wrong is worse than no calibration at all. + * + * Nothing here decides WHETHER to send. The sensor keeps a calibration for good — it cannot be + * edited or deleted afterwards — so the gates live at the call site (range, age, stability). + */ +object OnePlusCalibrateTx { + + const val OPCODE: Byte = 0x34 + const val PACKET_LENGTH: Int = 7 + + /** Range the sensor itself accepts, and the same one the official app and xDrip apply. */ + const val MIN_GLUCOSE_MGDL = 40 + const val MAX_GLUCOSE_MGDL = 400 + + /** + * @param glucoseMgdl fingerstick value in mg/dL, [MIN_GLUCOSE_MGDL]..[MAX_GLUCOSE_MGDL] + * @param dexTimeSeconds sensor time of the FINGERSTICK (not of this call) + * @return the packet, or null when the value is outside the range the sensor accepts + */ + fun build(glucoseMgdl: Int, dexTimeSeconds: Int): ByteArray? { + if (glucoseMgdl < MIN_GLUCOSE_MGDL || glucoseMgdl > MAX_GLUCOSE_MGDL) return null + if (dexTimeSeconds < 0) return null + val buf = OnePlusByteWriter(PACKET_LENGTH) + buf.put(OPCODE) + buf.putShort(glucoseMgdl.toShort()) + buf.putInt(dexTimeSeconds) + return buf.array() + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationBoundsRx.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationBoundsRx.kt new file mode 100644 index 000000000000..7df8124fb7aa --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusCalibrationBoundsRx.kt @@ -0,0 +1,55 @@ +package app.aaps.plugins.dexcomoneplus.parse + +/** + * The sensor's own calibration state (opcode 0x32), read after a calibration is sent. + * + * It answers two questions the 0x34 answer cannot: did the value really arrive when that answer + * was lost on the way, and has the sensor finished taking it in. The second matters because a + * reading or two right after a calibration can still be the old one. + * + * Layout (20 bytes): opcode | … | last glucose u16 LE @7 | last calibration time u32 LE @9 | + * processing @13 | calibrations permitted @14 | … + * + * Provenance: AAPS PR 5397 (`G7CalibrationBoundsMessage`), tested on G7 sensors. Not yet seen + * from a ONE+: when it does not answer, nothing changes. + */ +data class OnePlusCalibrationBoundsRx( + val lastGlucoseMgdl: Int, + /** Sensor seconds; 0 when the sensor was never calibrated. */ + val lastCalibrationTimeSeconds: Long, + val processing: Processing, + val calibrationsPermitted: Boolean, +) { + + enum class Processing(val code: Int) { + NONE(0), FACTORY_CALIBRATED(1), IN_PROGRESS(2), COMPLETE_HIGH(3), COMPLETE_LOW(4), UNKNOWN(255); + + companion object { + + fun fromCode(code: Int): Processing = entries.firstOrNull { it.code == code } ?: UNKNOWN + } + } + + /** True when this is the value we sent, at the time we sent for it. */ + fun matches(glucoseMgdl: Int, dexTimeSeconds: Int): Boolean = + lastGlucoseMgdl == glucoseMgdl && lastCalibrationTimeSeconds == dexTimeSeconds.toLong() + + companion object { + + const val OPCODE: Byte = 0x32 + const val PACKET_LENGTH: Int = 20 + + /** The request is the opcode alone. */ + fun request(): ByteArray = byteArrayOf(OPCODE) + + fun parse(packet: ByteArray): OnePlusCalibrationBoundsRx? { + if (packet.size < PACKET_LENGTH || packet[0] != OPCODE) return null + val data = OnePlusByteReader(packet, position = 7) + val lastGlucose = data.short().toInt() and 0xffff + val lastTime = data.int().toLong() and 0xffffffffL + val processing = Processing.fromCode(data.u8()) + val permitted = data.u8() == 1 + return OnePlusCalibrationBoundsRx(lastGlucose, lastTime, processing, permitted) + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt index e942ca42c6a9..13bd4d10e564 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt @@ -2,6 +2,7 @@ package app.aaps.plugins.dexcomoneplus.session import app.aaps.core.interfaces.concurrent.AapsLock import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample import app.aaps.plugins.dexcomoneplus.OnePlusLog import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers @@ -10,6 +11,8 @@ import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile import app.aaps.plugins.dexcomoneplus.onePlusSleep +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationBoundsRx import app.aaps.plugins.dexcomoneplus.reconnect.OemAwareReconnectPolicy import app.aaps.plugins.dexcomoneplus.reconnect.OnePlusReconnectPolicy import app.aaps.plugins.dexcomoneplus.warmup.OnePlusWarmupClock @@ -316,6 +319,27 @@ class OnePlusBleSessionSkeleton( private val cpuLease: OnePlusCpuLease? = null, /** Sensor slot owning this session (`prod` / `staging`) — logged on every marker. */ private val slot: String = OnePlusLogMarkers.SLOT_PRODUCTION, + /** + * Fingersticks waiting to be handed to the sensor's own algorithm, or null when this session may + * not calibrate. + * + * The driver passes its queue to every session, the pre-soak ones too, so a promoted session + * can calibrate. A pre-soak sensor must never be calibrated — it is not the one feeding the + * loop, and a sensor keeps a calibration for good — so the driver refuses every offer on a + * pre-soak slot and that queue stays empty. The plugin switch and its checks are a second gate: + * while the switch is off nothing is offered. + */ + private val calibrationQueue: OnePlusCalibrationQueue? = null, + /** What the sensor answered to a calibration, so a refusal or an unreadable answer reaches the user. */ + private val onCalibrationResult: (OnePlusCalibrateRx?) -> Unit = {}, + /** The sensor's calibration state read after a calibration, and whether it holds the value sent. */ + private val onCalibrationState: (OnePlusCalibrationBoundsRx, Boolean) -> Unit = { _, _ -> }, + /** Checks run again right before a waiting value is written, see `OnePlusEgvSession`. Default: refuse. */ + private val calibrationSendCheck: (Int, Long, Long) -> OnePlusCalibrationGate.Refusal? = { _, _, _ -> + OnePlusCalibrationGate.Refusal.NOT_READY + }, + /** A waiting value was dropped before any write, and why. */ + private val onCalibrationNotSent: (OnePlusCalibrationOutcome.NotSent.Reason) -> Unit = {}, ) : OnePlusBleSession { @Volatile @@ -713,6 +737,11 @@ class OnePlusBleSessionSkeleton( }, onError = onError, requestNewSensorStart = requestNewSensorStart, + calibrationQueue = calibrationQueue, + onCalibrationResult = onCalibrationResult, + onCalibrationState = onCalibrationState, + calibrationSendCheck = calibrationSendCheck, + onCalibrationNotSent = onCalibrationNotSent, ) try { egv.run(shouldContinue = { running && gatt.isConnected() }) diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGate.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGate.kt new file mode 100644 index 000000000000..fff7c2ad871b --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationGate.kt @@ -0,0 +1,60 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateTx +import kotlin.math.abs + +/** + * Whether a fingerstick may go to the sensor now. + * + * A sensor keeps a calibration it takes for good, so these checks run before the user confirms and + * again when the value is handed over. The limits are software choices, not clinical advice: + * range 40..400 mg/dL as the sensor accepts, blood at most one hour old, sensor past warm-up with a + * recent reading, and glucose not changing faster than [MAX_RATE_MGDL_PER_MIN]. + */ +object OnePlusCalibrationGate { + + enum class Refusal { + + /** Outside 40..400 mg/dL, what the sensor itself accepts. */ + OUT_OF_RANGE, + + /** The blood was measured more than an hour ago, or in the future. */ + TOO_OLD, + + /** The sensor is warming up, or has failed. */ + NOT_READY, + + /** No usable reading in the last [RECENT_READING_MS]: nothing proves the sensor is past warm-up. */ + NO_RECENT_READING, + + /** The last reading has no trend, so it is not known whether glucose is stable. */ + RATE_UNKNOWN, + + /** Glucose changes faster than [MAX_RATE_MGDL_PER_MIN]. A fingerstick then does not match the sensor. */ + CHANGING_TOO_FAST, + } + + /** Two G7 cycles and a little more. */ + const val RECENT_READING_MS = 11L * 60L * 1000L + + const val MAX_RATE_MGDL_PER_MIN = 2.0 + + fun check( + glucoseMgdl: Int, + bloodAtMs: Long, + nowMs: Long, + phase: OnePlusWarmupState.Phase, + lastReading: OnePlusGlucoseSample?, + ): Refusal? { + if (glucoseMgdl < OnePlusCalibrateTx.MIN_GLUCOSE_MGDL || glucoseMgdl > OnePlusCalibrateTx.MAX_GLUCOSE_MGDL) return Refusal.OUT_OF_RANGE + if (bloodAtMs > nowMs || OnePlusCalibrationQueue.isTooOld(bloodAtMs, nowMs)) return Refusal.TOO_OLD + // CONNECTING and RECONNECTING are the normal gap between two radio windows, not a reason to refuse. + if (phase == OnePlusWarmupState.Phase.WARMING || phase == OnePlusWarmupState.Phase.FAILED) return Refusal.NOT_READY + if (lastReading == null || nowMs - lastReading.timestampMs > RECENT_READING_MS) return Refusal.NO_RECENT_READING + val rate = lastReading.trendSlopeMgdlPerMin ?: return Refusal.RATE_UNKNOWN + if (abs(rate) > MAX_RATE_MGDL_PER_MIN) return Refusal.CHANGING_TOO_FAST + return null + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueue.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueue.kt new file mode 100644 index 000000000000..7eb7cbe4877f --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusCalibrationQueue.kt @@ -0,0 +1,111 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.core.interfaces.concurrent.AapsLock +import app.aaps.core.interfaces.concurrent.withLock +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateTx + +/** + * The one command a caller outside the BLE thread may ask a running session to send. + * + * The Control/EGV loop is a blocking cycle: it writes a request, waits for an indication, handles it, + * and starts again. There is no general command channel into it — the only thing of this kind before + * was a boolean for "start a new sensor". A calibration cannot use that shape, because it carries a + * value, a time, and an answer that has to come back to the user. + * + * So: one slot, not a list. A second fingerstick while one is still waiting is a mistake far more + * often than an intention, and a sensor keeps every calibration it accepts for good. + * + * Nothing in this file sends anything. What may be offered is decided by `OnePlusCalibrationGate`. + */ +class OnePlusCalibrationQueue { + + /** A fingerstick waiting to be handed to the sensor. */ + data class Pending( + /** Blood value in mg/dL. */ + val glucoseMgdl: Int, + /** + * Wall clock (epoch ms) given as the time of the blood. The calibration dialog passes the + * moment the user confirmed the value, not the moment of the finger prick, so it is a few + * seconds to minutes after the real blood time. + */ + val bloodAtMs: Long, + ) + + private val lock = AapsLock() + + private var pending: Pending? = null + + /** + * Ask for [glucoseMgdl] to be sent to the sensor. + * + * @return false when the value is outside what the sensor accepts, when the fingerstick is + * already too old to be meaningful, or when another one is still waiting. A waiting one that + * is older than [MAX_AGE_MS] does not count: it would be dropped at sending anyway, and it + * must not block every new fingerstick when the sensor stays out of reach. + */ + fun offer(glucoseMgdl: Int, bloodAtMs: Long, nowMs: Long): Boolean { + if (glucoseMgdl < OnePlusCalibrateTx.MIN_GLUCOSE_MGDL || glucoseMgdl > OnePlusCalibrateTx.MAX_GLUCOSE_MGDL) return false + if (isTooOld(bloodAtMs, nowMs) || bloodAtMs > nowMs) return false + return lock.withLock { + val waiting = pending + if (waiting != null && !isTooOld(waiting.bloodAtMs, nowMs)) return@withLock false + pending = Pending(glucoseMgdl, bloodAtMs) + true + } + } + + /** What is waiting, without taking it. */ + fun peek(): Pending? = lock.withLock { pending } + + /** Take the waiting fingerstick, if any. The slot is free again from here on. */ + fun take(): Pending? = lock.withLock { pending.also { pending = null } } + + /** + * Take [expected] out of the slot, only when it is still the value waiting there. + * + * @return false when the slot is empty or holds another value (it was replaced or cleared + * since [expected] was read); the slot is then left as it is + */ + fun take(expected: Pending): Boolean = lock.withLock { + if (pending !== expected) return@withLock false + pending = null + true + } + + companion object { + + /** + * Past this age a fingerstick is not worth sending: the sensor lines it up with its own + * history, and an hour of drift makes the pairing wrong. Same limit as xDrip and as the + * Dexcom apps, which ask for the value within minutes of the prick. + */ + const val MAX_AGE_MS = 60L * 60L * 1000L + + fun isTooOld(bloodAtMs: Long, nowMs: Long): Boolean = nowMs - bloodAtMs > MAX_AGE_MS + + /** + * Transmitter time for the time given for the blood ([Pending.bloodAtMs], which is the + * moment the user confirmed the value). + * + * The sensor is told when the blood was taken, not when the packet is written, so the + * wall-clock age of the fingerstick is taken off the transmitter clock. The transmitter + * clock itself is only known as "this value, read at that moment", so its own age counts too. + * + * @param lastDexTimeSeconds transmitter time last read from the sensor (0 = never) + * @param lastDexTimeAtMs wall clock when that transmitter time was read + * @return the transmitter second to put in the packet, or null when it cannot be worked out + */ + fun dexTimeForBlood( + bloodAtMs: Long, + nowMs: Long, + lastDexTimeSeconds: Int, + lastDexTimeAtMs: Long, + ): Int? { + if (lastDexTimeSeconds <= 0 || lastDexTimeAtMs <= 0L) return null + val dexNow = lastDexTimeSeconds + ((nowMs - lastDexTimeAtMs) / 1000L) + val dexBlood = dexNow - ((nowMs - bloodAtMs) / 1000L) + if (dexBlood <= 0L || dexBlood > Int.MAX_VALUE) return null + return dexBlood.toInt() + } + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt index a703e0643d21..3429ab04794a 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusEgvSession.kt @@ -1,11 +1,15 @@ package app.aaps.plugins.dexcomoneplus.session +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample import app.aaps.plugins.dexcomoneplus.OnePlusLog import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient import app.aaps.plugins.dexcomoneplus.onePlusSleep +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateRx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrateTx +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationBoundsRx import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationMapper import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationState import app.aaps.plugins.dexcomoneplus.parse.OnePlusEGlucoseTx @@ -47,6 +51,30 @@ class OnePlusEgvSession( * Never auto SessionStop. Dex time for Start comes from EGV session age when available. */ private val requestNewSensorStart: Boolean = false, + /** + * Fingersticks waiting to be handed to the sensor's own algorithm, or null when this session may + * not calibrate at all. A null queue here never builds opcode 0x34. + */ + private val calibrationQueue: OnePlusCalibrationQueue? = null, + /** What the sensor answered to a calibration (0x34 echo, or 0x35), so a refusal can reach the user. */ + private val onCalibrationResult: (OnePlusCalibrateRx?) -> Unit = {}, + /** + * The sensor's calibration state (0x32) read right after, and whether it holds the value just + * sent. That is how a lost answer is resolved without sending the value a second time. + */ + private val onCalibrationState: (OnePlusCalibrationBoundsRx, Boolean) -> Unit = { _, _ -> }, + /** + * The checks of [OnePlusCalibrationGate], run again right before a waiting value is written: + * minutes or hours may have passed since the user confirmed it. Gets the value, its time and + * now; returns why it must not go out, or null. The driver answers from its own warm-up phase + * and last reading. The default refuses, so a session that was given a queue but no check + * never writes. + */ + private val calibrationSendCheck: (Int, Long, Long) -> OnePlusCalibrationGate.Refusal? = { _, _, _ -> + OnePlusCalibrationGate.Refusal.NOT_READY + }, + /** A waiting value was dropped before anything was written, and why. The sensor never saw it. */ + private val onCalibrationNotSent: (OnePlusCalibrationOutcome.NotSent.Reason) -> Unit = {}, ) { @Volatile @@ -56,9 +84,21 @@ class OnePlusEgvSession( @Volatile private var lastDexTimeSeconds: Int = 0 + /** + * Wall clock when [lastDexTimeSeconds] was read. The transmitter clock is only ever known as + * "this value, at that moment", and a calibration carries the time of the BLOOD, so both ages + * have to be taken off it. + */ + @Volatile + private var lastDexTimeAtMs: Long = 0L + @Volatile private var backfillAttempted = false + /** Fingerstick already reported as "waiting for the transmitter clock", so it is said once. */ + @Volatile + private var waitingForDexTimeAtMs: Long = 0L + /** * Continuous Control/EGV loop until [shouldContinue] is false or GATT drops. * @@ -95,6 +135,12 @@ class OnePlusEgvSession( while (shouldContinue() && gatt.isConnected()) { val now = Clock.System.now().toEpochMilliseconds() + // Between two Control exchanges is the only safe moment: the loop owns the + // characteristic, and nothing else is waiting for an indication right now. + if (sendPendingCalibration(shouldContinue)) { + lastWriteMs = Clock.System.now().toEpochMilliseconds() + continue + } if (now - lastWriteMs >= rewriteIntervalMs) { writeEgvRequest(preferShort = preferShort) lastWriteMs = now @@ -189,8 +235,144 @@ class OnePlusEgvSession( return deliveredGlucose || gotPacket } + /** + * Hand the waiting fingerstick to the sensor, and wait for what it says about it. + * + * Returns true when a calibration was actually written, so the caller re-arms its own EGV + * request: the exchange has used the Control characteristic in the middle of the cycle. + * + * The checks of [OnePlusCalibrationGate] run again here ([calibrationSendCheck]): the sensor may + * have gone back to warm-up, the last reading may be old, or glucose may now change fast. A + * value that fails them, or is too old or out of range, is dropped before any write and + * reported as [OnePlusCalibrationOutcome.NotSent]: it is never kept for later, because an old + * value sent to a sensor that lines it up with its own history is worse than no calibration. + * Only a value that was written can end as "unknown". + */ + private fun sendPendingCalibration(shouldContinue: () -> Boolean): Boolean { + val queue = calibrationQueue ?: return false + val waiting = queue.peek() ?: return false + val now = Clock.System.now().toEpochMilliseconds() + if (dropIfNotAllowed(queue, waiting, now)) return false + val dexTime = OnePlusCalibrationQueue.dexTimeForBlood( + bloodAtMs = waiting.bloodAtMs, + nowMs = now, + lastDexTimeSeconds = lastDexTimeSeconds, + lastDexTimeAtMs = lastDexTimeAtMs, + ) + if (dexTime == null) { + if (waiting.bloodAtMs != waitingForDexTimeAtMs) { + waitingForDexTimeAtMs = waiting.bloodAtMs + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: calibration waiting — transmitter time unknown") + } + return false + } + // Taken only if it is still the value that was checked: a sensor change may have cleared it. + if (!queue.take(waiting)) return false + val pending = waiting + val packet = OnePlusCalibrateTx.build(pending.glucoseMgdl, dexTime) + if (packet == null) { + reportNotSent(OnePlusCalibrationOutcome.NotSent.Reason.OUT_OF_RANGE) + return false + } + try { + gatt.writeControl(packet) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: wrote CalibrateTx opcode=0x34 " + + "glucose=${pending.glucoseMgdl} dexTime=$dexTime", + ) + } catch (t: Throwable) { + // The write may have reached the sensor before it failed, so this is "unknown", not "not sent". + OnePlusLog.e("${OnePlusLogMarkers.ERROR}: calibration write failed: ${t.message}", t) + onCalibrationResult(null) + return false + } + awaitCalibrationReply(shouldContinue) + readCalibrationState(pending.glucoseMgdl, dexTime, shouldContinue) + return true + } + + /** Why [pending] must not be written now, or null when it may. */ + private fun notAllowed(pending: OnePlusCalibrationQueue.Pending, nowMs: Long): OnePlusCalibrationOutcome.NotSent.Reason? { + if (OnePlusCalibrationQueue.isTooOld(pending.bloodAtMs, nowMs)) return OnePlusCalibrationOutcome.NotSent.Reason.TOO_OLD + val refusal = calibrationSendCheck(pending.glucoseMgdl, pending.bloodAtMs, nowMs) ?: return null + return OnePlusCalibrationOutcome.NotSent.Reason.of(refusal) + } + + /** Takes [waiting] out of the queue and reports it as not sent when it must not go out now. */ + private fun dropIfNotAllowed(queue: OnePlusCalibrationQueue, waiting: OnePlusCalibrationQueue.Pending, nowMs: Long): Boolean { + val reason = notAllowed(waiting, nowMs) ?: return false + if (queue.take(waiting)) reportNotSent(reason) + return true + } + + private fun reportNotSent(reason: OnePlusCalibrationOutcome.NotSent.Reason) { + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: calibration dropped before the write — $reason") + onCalibrationNotSent(reason) + } + + /** + * Ask the sensor for its calibration state (0x32) and report it. + * + * Never sends the value again, whatever comes back: a sensor keeps every calibration it takes, + * so a second copy cannot be undone. A sensor that does not answer changes nothing. + */ + private fun readCalibrationState(sentGlucoseMgdl: Int, sentDexTimeSeconds: Int, shouldContinue: () -> Boolean) { + if (!shouldContinue() || !gatt.isConnected()) return + try { + gatt.writeControl(OnePlusCalibrationBoundsRx.request()) + } catch (t: Throwable) { + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: calibration state request failed: ${t.message}") + return + } + for (attempt in 0 until CALIBRATION_REPLY_ROUNDS) { + if (!shouldContinue() || !gatt.isConnected()) return + val packet = gatt.awaitControlNotify(CALIBRATION_REPLY_TIMEOUT_MS) ?: break + val bounds = OnePlusCalibrationBoundsRx.parse(packet) + if (bounds == null) { + handleControlPacket(packet, shouldContinue) + continue + } + val matches = bounds.matches(sentGlucoseMgdl, sentDexTimeSeconds) + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: calibration state last=${bounds.lastGlucoseMgdl} " + + "at=${bounds.lastCalibrationTimeSeconds} processing=${bounds.processing} " + + "permitted=${bounds.calibrationsPermitted} matchesSent=$matches", + ) + onCalibrationState(bounds, matches) + return + } + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: no calibration state answer") + } + + /** + * Wait for the answer (0x34 echo, or 0x35), letting anything else through on the way. + * + * The sensor may well send a glucose packet before it answers, and dropping it here would lose a + * reading, so every other packet keeps going through the normal handling. + */ + private fun awaitCalibrationReply(shouldContinue: () -> Boolean) { + for (attempt in 0 until CALIBRATION_REPLY_ROUNDS) { + if (!shouldContinue() || !gatt.isConnected()) break + val reply = gatt.awaitControlNotify(CALIBRATION_REPLY_TIMEOUT_MS) ?: break + val parsed = OnePlusCalibrateRx.parse(reply) + if (parsed == null) { + handleControlPacket(reply, shouldContinue) + continue + } + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: CalibrateRx form=${parsed.form} result=0x${parsed.result.toString(16)} " + + "accepted=${parsed.accepted()} msg=${parsed.message()}", + ) + onCalibrationResult(parsed) + return + } + OnePlusLog.w("${OnePlusLogMarkers.SESSION}: no CalibrateRx — the sensor did not answer the calibration") + onCalibrationResult(null) + } + private fun applyTransmitterTime(rx: OnePlusTransmitterTimeRx) { lastDexTimeSeconds = rx.currentTimeSeconds + lastDexTimeAtMs = Clock.System.now().toEpochMilliseconds() val age = rx.sessionAgeSeconds() OnePlusLog.d( "${OnePlusLogMarkers.SESSION}: TransmitterTimeRx current=${rx.currentTimeSeconds} " + @@ -214,6 +396,8 @@ class OnePlusEgvSession( if (sessionStartAttempted) return sessionStartAttempted = true if (!gatt.isConnected() || !shouldContinue()) return + // A new sensor session starts with a warm-up: a value confirmed before it does not belong to it. + if (calibrationQueue?.take() != null) reportNotSent(OnePlusCalibrationOutcome.NotSent.Reason.SENSOR_CHANGED) val payload = OnePlusSessionStartTx.build( dexTimeSeconds = lastDexTimeSeconds, @@ -252,6 +436,7 @@ class OnePlusEgvSession( if (rx.transmitterTime != 0 && rx.transmitterTime != OnePlusSessionStartRx.INVALID_TIME) { lastDexTimeSeconds = rx.transmitterTime + lastDexTimeAtMs = Clock.System.now().toEpochMilliseconds() } when { @@ -324,6 +509,7 @@ class OnePlusEgvSession( ) if (rx.transmitterTime != 0) { lastDexTimeSeconds = rx.transmitterTime + lastDexTimeAtMs = Clock.System.now().toEpochMilliseconds() } return } @@ -334,6 +520,7 @@ class OnePlusEgvSession( ) if (rx.transmitterTime != 0 && rx.transmitterTime != OnePlusSessionStartRx.INVALID_TIME) { lastDexTimeSeconds = rx.transmitterTime + lastDexTimeAtMs = Clock.System.now().toEpochMilliseconds() } return } @@ -360,6 +547,7 @@ class OnePlusEgvSession( parsed.sessionAgeSeconds?.takeIf { it > 0 }?.let { age -> lastDexTimeSeconds = age + lastDexTimeAtMs = Clock.System.now().toEpochMilliseconds() } val warmup = OnePlusCalibrationMapper.toWarmupState( @@ -405,5 +593,11 @@ class OnePlusEgvSession( const val SESSION_STOP_TIMEOUT_MS: Long = 15_000L /** xDrip `SessionStopTxMessage.postExecuteGuardTime`. */ const val SESSION_STOP_GUARD_MS: Long = 1_000L + + /** Per-wait for the calibration answer, and for the calibration state. */ + const val CALIBRATION_REPLY_TIMEOUT_MS: Long = 10_000L + + /** How many packets may arrive before the answer — a glucose packet often comes first. */ + const val CALIBRATION_REPLY_ROUNDS: Int = 3 } } diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt index fa99c9c84dca..c20b9b77038f 100644 --- a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt @@ -15,6 +15,7 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Clock /** * The real driver's own state, run on every platform the module builds for. @@ -33,6 +34,8 @@ class OnePlusCgmDriverRealSharedTest { assertNull(driver.sensorStore()) assertFalse(driver.isSessionUp()) assertEquals(OnePlusWarmupState.Phase.IDLE, driver.warmupState().phase) + assertNull(driver.lastCalibrationOutcome()) + assertFalse(driver.calibrationPending()) driver.shutdown() } @@ -69,6 +72,24 @@ class OnePlusCgmDriverRealSharedTest { staging.shutdown() } + @Test + fun `a pre-soak sensor is never calibrated`() { + val driver = OnePlusCgmDriverReal(storeNamespace = "staging") + driver.attach(FakePlatform()) + assertFalse(driver.offerCalibration(glucoseMgdl = 120, bloodAtMs = nowMs())) + assertNull(driver.lastCalibrationOutcome()) + driver.shutdown() + } + + @Test + fun `a fingerstick is refused while there is no session`() { + val driver = OnePlusCgmDriverReal() + driver.attach(FakePlatform()) + assertFalse(driver.offerCalibration(glucoseMgdl = 120, bloodAtMs = nowMs())) + assertFalse(driver.calibrationPending()) + driver.shutdown() + } + @Test fun `nothing is resumed when the store is empty`() { val driver = OnePlusCgmDriverReal() @@ -109,6 +130,8 @@ class OnePlusCgmDriverRealSharedTest { assertFalse(driver.isSessionUp()) } + private fun nowMs(): Long = Clock.System.now().toEpochMilliseconds() + /** A host with a store and a scanner, and nothing that needs a radio. */ private class FakePlatform : OnePlusPlatform { diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt index ade1593972d6..5bef80a1f95e 100644 --- a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/parse/OnePlusBytesTest.kt @@ -84,6 +84,15 @@ class OnePlusBytesTest { assertEquals("", ByteArray(0).onePlusToHex()) } + @Test + fun `a calibration request carries the same bytes on every target`() { + val packet = assertNotNull(OnePlusCalibrateTx.build(glucoseMgdl = 150, dexTimeSeconds = 0x01020304)) + + assertEquals(OnePlusCalibrateTx.PACKET_LENGTH, packet.size) + assertEquals(OnePlusCalibrateTx.OPCODE, packet[0]) + assertEquals("34960004030201", packet.onePlusToHex()) + } + @Test fun `a session start answer is read on every target`() { val writer = OnePlusByteWriter(OnePlusSessionStartRx.PACKET_LENGTH) diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationTextTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationTextTest.kt new file mode 100644 index 000000000000..b04880003fd1 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationTextTest.kt @@ -0,0 +1,47 @@ +package app.aaps.plugins.source + +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * The user text for each calibration result. "Not sent" and "unknown" ask the user for opposite + * things (enter it again / do not send it again), so they must never share a text. + */ +class DexcomOnePlusCalibrationTextTest { + + @Test + fun `a value dropped before the write says it was not sent and may be entered again`() { + val notSent = OnePlusCalibrationOutcome.NotSent(OnePlusCalibrationOutcome.NotSent.Reason.NOT_READY) + + assertThat(DexcomOnePlusCalibrationText.status(notSent, waiting = false)) + .isEqualTo(SourceStrings.dexcom_oneplus_calibration_dropped) + } + + @Test + fun `a written value with no clear answer stays unknown`() { + assertThat(DexcomOnePlusCalibrationText.status(OnePlusCalibrationOutcome.Unknown("no answer"), waiting = false)) + .isEqualTo(SourceStrings.dexcom_oneplus_calibration_unknown) + } + + @Test + fun `not sent and unknown never share a text`() { + val notSentTexts = OnePlusCalibrationOutcome.NotSent.Reason.entries.map { + DexcomOnePlusCalibrationText.status(OnePlusCalibrationOutcome.NotSent(it), waiting = false) + }.toSet() + + assertThat(notSentTexts).containsExactly(SourceStrings.dexcom_oneplus_calibration_dropped) + assertThat(notSentTexts).doesNotContain(SourceStrings.dexcom_oneplus_calibration_unknown) + } + + @Test + fun `the reason of a dropped value reads like the refusal before the confirmation`() { + OnePlusCalibrationGate.Refusal.entries.forEach { refusal -> + assertThat(DexcomOnePlusCalibrationText.notSentReason(OnePlusCalibrationOutcome.NotSent.Reason.of(refusal))) + .isEqualTo(DexcomOnePlusCalibrationText.refusal(refusal)) + } + assertThat(DexcomOnePlusCalibrationText.notSentReason(OnePlusCalibrationOutcome.NotSent.Reason.SENSOR_CHANGED)) + .isEqualTo(SourceStrings.dexcom_oneplus_calibration_dropped_sensor_changed) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt new file mode 100644 index 000000000000..963a537b6393 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt @@ -0,0 +1,199 @@ +package app.aaps.plugins.source + +import android.content.Context +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.calibration.Calibration +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.interfaces.source.SensorCalibrationResult +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationQueue +import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * The switch is on by default. While it is off, [DexcomOnePlusPlugin.calibrateSensor] returns + * [SensorCalibrationResult.NotSupported] and the production queue stays empty, so the Control loop + * has nothing from which to build opcode 0x34. While it is on, every check of + * `OnePlusCalibrationGate` must pass before anything is queued, and only one value can wait. + * + * The session is forced up on purpose: a missing check would queue the value. The assertion is + * that the queue is still empty. + */ +class DexcomOnePlusSensorCalibrationTest : TestBase() { + + @Mock lateinit var rh: ResourceHelper + @Mock lateinit var preferences: Preferences + @Mock lateinit var config: Config + @Mock lateinit var context: Context + @Mock lateinit var persistenceLayer: PersistenceLayer + + private val notificationManager: NotificationManager = mock() + private val activePlugin: ActivePlugin = mock().also { + whenever(it.activeCalibration).thenReturn(mock()) + } + + private lateinit var plugin: DexcomOnePlusPlugin + + @BeforeEach + fun setup() { + whenever(context.applicationContext).thenReturn(context) + whenever(rh.gs(any())).thenReturn("not sent") + plugin = DexcomOnePlusPlugin( + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + activePlugin, rxBus, + ) + } + + @AfterEach + fun tearDownDrivers() { + OnePlusCgmDrivers.shutdownAll() + } + + @Test + fun `the switch defaults to on and is a normal setting`() { + assertThat(DexcomOnePlusBooleanKey.SendCalibrationToSensor.defaultValue).isTrue() + assertThat(DexcomOnePlusBooleanKey.SendCalibrationToSensor.engineeringModeOnly).isFalse() + assertThat(DexcomOnePlusBooleanKey.SendCalibrationToSensor.exportable).isFalse() + } + + @Test + fun `switch off returns NotSupported and queues nothing`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(false) + val driver = OnePlusCgmDrivers.realProduction() + markSessionUp(driver) + val before = queueOf(driver).peek() + + val result = plugin.calibrateSensor(glucoseMgdl = 150, bloodAtMs = System.currentTimeMillis()) + + assertThat(result).isEqualTo(SensorCalibrationResult.NotSupported) + assertThat(driver.calibrationPending()).isFalse() + assertThat(driver.lastCalibrationOutcome()).isNull() + assertThat(queueOf(driver).peek()).isEqualTo(before) + assertThat(queueOf(driver).peek()).isNull() + } + + @Test + fun `switch on and session down refuses without queueing`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(true) + val driver = OnePlusCgmDrivers.realProduction() + giveReading(rate = 0.5) + + val result = plugin.calibrateSensor(glucoseMgdl = 150, bloodAtMs = System.currentTimeMillis()) + + assertThat(result).isInstanceOf(SensorCalibrationResult.Refused::class.java) + assertThat((result as SensorCalibrationResult.Refused).reason).isEqualTo("not sent") + assertThat(driver.calibrationPending()).isFalse() + assertThat(driver.lastCalibrationOutcome()).isNull() + assertThat(queueOf(driver).peek()).isNull() + } + + @Test + fun `switch on and a value outside 40 to 400 queues nothing`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(true) + val driver = OnePlusCgmDrivers.realProduction() + markSessionUp(driver) + giveReading(rate = 0.5) + + val low = plugin.calibrateSensor(glucoseMgdl = 39, bloodAtMs = System.currentTimeMillis()) + val high = plugin.calibrateSensor(glucoseMgdl = 401, bloodAtMs = System.currentTimeMillis()) + + assertThat(low).isInstanceOf(SensorCalibrationResult.Refused::class.java) + assertThat(high).isInstanceOf(SensorCalibrationResult.Refused::class.java) + assertThat(driver.calibrationPending()).isFalse() + assertThat(driver.lastCalibrationOutcome()).isNull() + assertThat(queueOf(driver).peek()).isNull() + } + + @Test + fun `switch on keeps the first fingerstick when a second one arrives`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(true) + val driver = OnePlusCgmDrivers.realProduction() + markSessionUp(driver) + giveReading(rate = 0.5) + val now = System.currentTimeMillis() + + val first = plugin.calibrateSensor(glucoseMgdl = 150, bloodAtMs = now) + val second = plugin.calibrateSensor(glucoseMgdl = 160, bloodAtMs = now) + + assertThat(first).isEqualTo(SensorCalibrationResult.Queued) + assertThat(second).isInstanceOf(SensorCalibrationResult.Refused::class.java) + assertThat(driver.calibrationPending()).isTrue() + assertThat(driver.lastCalibrationOutcome()).isEqualTo(OnePlusCalibrationOutcome.Pending) + assertThat(queueOf(driver).peek()?.glucoseMgdl).isEqualTo(150) + } + + @Test + fun `switch on without a recent reading refuses before the value is shown to the sensor`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(true) + val driver = OnePlusCgmDrivers.realProduction() + markSessionUp(driver) + val now = System.currentTimeMillis() + + assertThat(plugin.sensorCalibrationRefusal(glucoseMgdl = 150, bloodAtMs = now)).isNotNull() + assertThat(plugin.calibrateSensor(glucoseMgdl = 150, bloodAtMs = now)).isInstanceOf(SensorCalibrationResult.Refused::class.java) + assertThat(queueOf(driver).peek()).isNull() + } + + @Test + fun `switch on and glucose changing fast refuses`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(true) + val driver = OnePlusCgmDrivers.realProduction() + markSessionUp(driver) + giveReading(rate = 3.0) + val now = System.currentTimeMillis() + + assertThat(plugin.calibrateSensor(glucoseMgdl = 150, bloodAtMs = now)).isInstanceOf(SensorCalibrationResult.Refused::class.java) + assertThat(queueOf(driver).peek()).isNull() + } + + @Test + fun `switch off asks nothing of the sensor`() { + whenever(preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor)).thenReturn(false) + + assertThat(plugin.sensorCalibrationRefusal(glucoseMgdl = 150, bloodAtMs = System.currentTimeMillis())).isNull() + } + + /** A production reading one minute old, as `onGlucose` would have left it. */ + private fun giveReading(rate: Double?) { + val field = DexcomOnePlusPlugin::class.java.getDeclaredField("lastProductionReading") + field.isAccessible = true + field.set(plugin, OnePlusGlucoseSample(mgdl = 120.0, timestampMs = System.currentTimeMillis() - 60_000L, trendSlopeMgdlPerMin = rate)) + } + + private fun markSessionUp(driver: OnePlusCgmDriverReal) { + val field = OnePlusCgmDriverReal::class.java.getDeclaredField("session") + field.isAccessible = true + field.set(driver, UpSession) + } + + private fun queueOf(driver: OnePlusCgmDriverReal): OnePlusCalibrationQueue { + val field = OnePlusCgmDriverReal::class.java.getDeclaredField("calibrationQueue") + field.isAccessible = true + return field.get(driver) as OnePlusCalibrationQueue + } + + private object UpSession : OnePlusBleSession { + override fun startWithPairingCode(deviceAddress: String, pairingCode: String) = Unit + override fun stop(reason: String?) = Unit + override fun isUp(): Boolean = true + override fun warmupState() = OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationText.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationText.kt new file mode 100644 index 000000000000..25fab63f151f --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusCalibrationText.kt @@ -0,0 +1,40 @@ +package app.aaps.plugins.source + +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate + +/** + * Which user text goes with a sensor calibration result. One place for the plugin and the status + * screen, so a refusal before the confirmation and a value dropped at send time read the same. + * + * [OnePlusCalibrationOutcome.NotSent] and [OnePlusCalibrationOutcome.Unknown] must never share a + * text: after NotSent nothing reached the sensor and the user may enter the value again, after + * Unknown the value was written and must not be sent again. + */ +object DexcomOnePlusCalibrationText { + + /** Why the value may not go to the sensor now. */ + fun refusal(refusal: OnePlusCalibrationGate.Refusal): TextRef = when (refusal) { + OnePlusCalibrationGate.Refusal.OUT_OF_RANGE -> SourceStrings.dexcom_oneplus_calibration_refused_range + OnePlusCalibrationGate.Refusal.TOO_OLD -> SourceStrings.dexcom_oneplus_calibration_refused_too_old + OnePlusCalibrationGate.Refusal.NOT_READY -> SourceStrings.dexcom_oneplus_calibration_refused_not_ready + OnePlusCalibrationGate.Refusal.NO_RECENT_READING -> SourceStrings.dexcom_oneplus_calibration_refused_no_reading + OnePlusCalibrationGate.Refusal.RATE_UNKNOWN -> SourceStrings.dexcom_oneplus_calibration_refused_rate_unknown + OnePlusCalibrationGate.Refusal.CHANGING_TOO_FAST -> SourceStrings.dexcom_oneplus_calibration_refused_too_fast + } + + /** The main line of the status card. */ + fun status(outcome: OnePlusCalibrationOutcome?, waiting: Boolean): TextRef = when { + waiting || outcome is OnePlusCalibrationOutcome.Pending -> SourceStrings.dexcom_oneplus_calibration_waiting + outcome is OnePlusCalibrationOutcome.Accepted -> SourceStrings.dexcom_oneplus_calibration_accepted + outcome is OnePlusCalibrationOutcome.Refused -> SourceStrings.dexcom_oneplus_calibration_refused + outcome is OnePlusCalibrationOutcome.Unknown -> SourceStrings.dexcom_oneplus_calibration_unknown + outcome is OnePlusCalibrationOutcome.NotSent -> SourceStrings.dexcom_oneplus_calibration_dropped + else -> SourceStrings.dexcom_oneplus_calibration_none + } + + /** Why a value was dropped before it was written. */ + fun notSentReason(reason: OnePlusCalibrationOutcome.NotSent.Reason): TextRef = + reason.gateRefusal?.let { refusal(it) } ?: SourceStrings.dexcom_oneplus_calibration_dropped_sensor_changed +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt index 33297ad8f41d..f10af1a9390a 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt @@ -26,6 +26,7 @@ import app.aaps.core.interfaces.source.CgmWarmupProvider import app.aaps.core.interfaces.source.CgmWarmupStatus import app.aaps.core.interfaces.source.PromotionRejectReason import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.SensorCalibrationResult import app.aaps.core.interfaces.source.StagingState import app.aaps.core.interfaces.concurrent.AapsLock import app.aaps.core.interfaces.concurrent.withLock @@ -41,6 +42,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore +import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate import app.aaps.plugins.source.compose.BgSourceComposeContent import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey import app.aaps.plugins.source.keys.DexcomOnePlusIntKey @@ -169,6 +171,10 @@ class DexcomOnePlusPlugin @Inject constructor( @Volatile private var warmupPhase: OnePlusWarmupState.Phase = OnePlusWarmupState.Phase.IDLE + /** The newest reading of the production sensor, for the calibration checks. */ + @Volatile + private var lastProductionReading: OnePlusGlucoseSample? = null + private val _warmup = MutableStateFlow(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE)) /** Live warm-up / session status of the native driver — feeds the ongoing notification and the warm-up ring. */ @@ -280,12 +286,45 @@ class DexcomOnePlusPlugin @Inject constructor( } + /** + * A fingerstick goes to the sensor while [DexcomOnePlusBooleanKey.SendCalibrationToSensor] is on, + * which is the default. + * + * When it is true the app must not also fit a software line on the same readings. The graph + * worker already does this: its `PrepareGraphDataRunner.smoothData` skips the software + * calibration while this returns true, and the master's calibration path sends the value here + * instead of storing a calibration entry. + */ + override fun calibratesInSensor(): Boolean = + preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor) + + /** Why the sensor must not get [glucoseMgdl] now, already readable by the user, or null. */ + override fun sensorCalibrationRefusal(glucoseMgdl: Int, bloodAtMs: Long): String? { + if (!calibratesInSensor()) return null + val refusal = OnePlusCalibrationGate.check(glucoseMgdl, bloodAtMs, nowMs(), warmupPhase, lastProductionReading) + ?: return null + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_CALIBRATION: refused $refusal") + return resources.gs(DexcomOnePlusCalibrationText.refusal(refusal)) + } + + override fun calibrateSensor(glucoseMgdl: Int, bloodAtMs: Long): SensorCalibrationResult { + if (!calibratesInSensor()) return SensorCalibrationResult.NotSupported + // Checked again here: time has passed since the user saw the confirmation. + sensorCalibrationRefusal(glucoseMgdl, bloodAtMs)?.let { return SensorCalibrationResult.Refused(it) } + // Only the production driver: a pre-soak sensor is not the one feeding the loop, and a + // calibration it accepted would stay in it for the whole of its own life. + val queued = driver.offerCalibration(glucoseMgdl, bloodAtMs) + return if (queued) SensorCalibrationResult.Queued + else SensorCalibrationResult.Refused(resources.gs(SourceStrings.dexcom_oneplus_calibration_not_sent)) + } + override fun getPreferenceScreenContent() = PreferenceSubScreenDef( key = "dexcom_oneplus_settings", title = SourceStrings.dexcom_oneplus_native, summary = SourceStrings.dexcom_oneplus_plugin_summary, // The three screen buttons come from the host, because opening a screen needs a Context. items = host.screenItems(this) + listOf( + DexcomOnePlusBooleanKey.SendCalibrationToSensor, DexcomOnePlusBooleanKey.AutoPromote, DexcomOnePlusIntKey.AutoPromoteHours, DexcomOnePlusBooleanKey.RepairMissingSensorChange, @@ -392,6 +431,7 @@ class DexcomOnePlusPlugin @Inject constructor( if (warmupPhase != OnePlusWarmupState.Phase.READY && warmupPhase != OnePlusWarmupState.Phase.IDLE) { onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.READY)) } + if (sample.timestampMs > (lastProductionReading?.timestampMs ?: Long.MIN_VALUE)) lastProductionReading = sample ingestToLoop(sample, sensorStore) } @@ -921,6 +961,8 @@ class DexcomOnePlusPlugin @Inject constructor( runCatching { if (outgoing !== promoted && outgoing !== retired) outgoing.shutdown() } // 6) Only now retire the staging store — nothing points at it any more. stagingStore.clearAll() + // The last reading belongs to the sensor just retired: a calibration must wait for the new one. + lastProductionReading = null // The promoted sensor becomes the loop's sensor: its age must show on the overview from the // moment it was applied (its staging start, verified above), not from the promotion. logSensorChange(startMs) diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt index bd250baf5b47..c4ea05492263 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt @@ -47,7 +47,10 @@ import app.aaps.core.ui.compose.MetroAppCompatActivity import app.aaps.core.ui.compose.dialogs.DatePickerModal import app.aaps.core.ui.compose.dialogs.TimePickerModal import app.aaps.core.ui.compose.stringResource as coreStringResource +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationState +import app.aaps.plugins.source.DexcomOnePlusCalibrationText import app.aaps.plugins.source.DexcomOnePlusPlugin import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection import app.aaps.plugins.source.DexcomOnePlusStaging @@ -94,7 +97,7 @@ class DexcomOnePlusStatusActivity : MetroAppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Other apps may not draw over this screen: an overlay could hide what a tap really does, here on a - // sensor (start, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. + // sensor (start, calibration, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. window.setHideOverlayWindows(true) dexcomOnePlusPlugin.syncDriverFromPrefs() setContent { @@ -186,7 +189,14 @@ private fun DexcomOnePlusStatusScreen( var state by remember { mutableStateOf(OnePlusCgmDrivers.default().warmupState()) } var sessionUp by remember { mutableStateOf(OnePlusCgmDrivers.default().isSessionUp()) } var newestGlucose by remember { mutableStateOf(null) } + var calibrationOutcome by remember { mutableStateOf(null) } + var calibrationWaiting by remember { mutableStateOf(false) } + // The card exists only while values are sent to the sensor. With the setting off the value + // never leaves the phone, so there is nothing to report. The switch is on by default. val preferences = LocalPreferences.current + val sendCalibrationToSensor = remember(preferences) { + preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor) + } val correctSensorStartEnabled = preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart) val stagingState by stagingStateFlow.collectAsState() val stagingEvidence by stagingEvidenceFlow.collectAsState() @@ -218,6 +228,8 @@ private fun DexcomOnePlusStatusScreen( val driver = OnePlusCgmDrivers.default() state = driver.warmupState() sessionUp = driver.isSessionUp() + calibrationOutcome = driver.lastCalibrationOutcome() + calibrationWaiting = driver.calibrationPending() now = System.currentTimeMillis() delay(1_000L) } @@ -259,6 +271,15 @@ private fun DexcomOnePlusStatusScreen( onCorrectSensorStart = onCorrectSensorStart, ) } + if (sendCalibrationToSensor) { + item(key = "sensorCalibration") { + SensorCalibrationCard( + outcome = calibrationOutcome, + waiting = calibrationWaiting, + driverMessage = state.message, + ) + } + } // Prompt for a pre-soak exactly when it is useful: the sensor in use is near its end and // no replacement is warming up yet. if (lifecycle?.endOfLife == true && stagingState == StagingState.ABSENT) { @@ -487,6 +508,81 @@ private fun CorrectInsertionDateAction( } } +/** + * What became of a finger prick value handed to the sensor itself. + * + * On screen only while [DexcomOnePlusBooleanKey.SendCalibrationToSensor] is on, which is the + * default. The texts come from [DexcomOnePlusCalibrationText]. + * + * [OnePlusCalibrationOutcome.Unknown] is not softened: the value was written and the answer was + * lost or unreadable, so it is neither a failure of the app nor a success. + * [OnePlusCalibrationOutcome.NotSent] says the opposite: nothing reached the sensor, and the value + * may be entered again. + */ +@Composable +private fun SensorCalibrationCard( + outcome: OnePlusCalibrationOutcome?, + waiting: Boolean, + driverMessage: String?, +) { + val warning = outcome is OnePlusCalibrationOutcome.Refused || outcome is OnePlusCalibrationOutcome.NotSent + val tone = if (warning) CgmCardTone.Warning else CgmCardTone.Neutral + CgmCard(tone = tone) { + CgmCardHeader(stringResource(R.string.dexcom_oneplus_calibration_heading)) + sensorCalibrationRequest(driverMessage)?.let { request -> + Text( + text = request, + style = MaterialTheme.typography.bodyMedium, + ) + } + Text( + text = coreStringResource(DexcomOnePlusCalibrationText.status(outcome, waiting)), + style = MaterialTheme.typography.bodyMedium, + ) + if (!waiting && outcome is OnePlusCalibrationOutcome.NotSent) { + Text( + text = coreStringResource(DexcomOnePlusCalibrationText.notSentReason(outcome.reason)), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + val detail = when (outcome) { + is OnePlusCalibrationOutcome.Accepted -> outcome.detail + is OnePlusCalibrationOutcome.Refused -> outcome.detail + is OnePlusCalibrationOutcome.Unknown -> outcome.detail + else -> null + } + detail?.takeIf { it.isNotBlank() }?.let { text -> + Text( + text = stringResource(R.string.dexcom_oneplus_calibration_detail, text), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** + * What the sensor itself is asking for, read back out of the driver status line. + * + * Null when the line is about something else, which it is most of the time. + */ +@Composable +private fun sensorCalibrationRequest(driverMessage: String?): String? { + val state = OnePlusCalibrationState.entries.firstOrNull { it.name == driverMessage } ?: return null + return when (state) { + OnePlusCalibrationState.NeedsCalibration -> + stringResource(R.string.dexcom_oneplus_calibration_state_needs) + OnePlusCalibrationState.NeedsFirstCalibration -> + stringResource(R.string.dexcom_oneplus_calibration_state_needs_first) + OnePlusCalibrationState.NeedsSecondCalibration -> + stringResource(R.string.dexcom_oneplus_calibration_state_needs_second) + OnePlusCalibrationState.CalibrationSent -> + stringResource(R.string.dexcom_oneplus_calibration_state_sent) + else -> null + } +} + /** * The collect-only second sensor. * diff --git a/plugins/source/src/androidMain/res/values/strings.xml b/plugins/source/src/androidMain/res/values/strings.xml index 0634bdd98d7e..03609c80edbe 100644 --- a/plugins/source/src/androidMain/res/values/strings.xml +++ b/plugins/source/src/androidMain/res/values/strings.xml @@ -97,6 +97,28 @@ Enter a valid 4-digit sensor pairing code Allow Bluetooth Bluetooth permission is required before starting the sensor + Send calibration to the sensor + On: a finger prick value is sent to the sensor itself, as the Dexcom app does. The sensor keeps it for good and it cannot be edited or deleted. Off: the value is used to correct readings inside the app, and can be removed later. + The sensor accepts a finger prick value from 40 to 400 mg/dL (2.2 to 22.2 mmol/L) only. + This finger prick value is more than one hour old. Measure again. + The sensor is still warming up, or has stopped. Calibrate when it shows readings again. + No sensor reading in the last 10 minutes. Wait for the next reading, then try again. + The sensor did not give a trend with its last reading. Wait for the next reading, then try again. + Glucose is changing too fast. Calibrate when it is stable. + The value could not be sent to the sensor. The sensor may be out of range, still warming up, or another value may still be on its way. + Sensor calibration + No finger prick value has been sent to this sensor yet. + Your value is waiting to be sent to the sensor. It goes out the next time the app and the sensor talk, which is usually within a few minutes. + The sensor says it took your value. + The sensor says it did not take your value. Your reading was not changed. + The sensor did not give a clear answer, so it is not possible to say whether your value was used. It is not an app error and it is not a success. Do not send the value again. Compare the sensor with a finger prick within the next hour before you rely on its readings, and ask your care team if you are unsure. + Your value was not sent to the sensor. Nothing reached the sensor, so you can enter the value again. + The sensor or its connection changed before the value went out. + Sensor answer: %1$s + The sensor is asking for a calibration. + The sensor is asking for its first calibration. + The sensor is asking for a second calibration. + The sensor reports that a calibration has reached it. Repair a missing sensor change On by default. When "Create sensor change" is also on, a missing sensor change for the running sensor is written once, so the sensor age is right. An event you delete after that write is not written again. Use a sensor change you logged as the start diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt index 6eb3f2d88ac7..e54bc6b9b6e4 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusBooleanKey.kt @@ -21,6 +21,24 @@ enum class DexcomOnePlusBooleanKey( override val exportable: Boolean = false, ) : BooleanPreferenceKey { + /** + * Send a fingerstick to the sensor instead of correcting its readings inside the phone. + * + * On by default: a fingerstick is the reference, so it goes to the sensor's own algorithm, as + * the Dexcom app does. A sensor keeps a calibration it accepts for good — it cannot be edited + * or deleted — so the confirmation says so, and `OnePlusCalibrationGate` refuses a value at a + * bad moment (warm-up, no recent reading, glucose changing fast, blood older than one hour). + * While it is on, the app does not fit its own calibration line on this source's readings. + * Off: the value is stored as an app calibration entry, as for any other source. + */ + SendCalibrationToSensor( + key = "dexcom_oneplus_send_calibration_to_sensor", + defaultValue = true, + title = SourceStrings.dexcom_oneplus_send_calibration_to_sensor, + summary = SourceStrings.dexcom_oneplus_send_calibration_to_sensor_summary, + exportable = false, + ), + /** * Put a missing SENSOR_CHANGE back for the running ONE+ session. * diff --git a/workflow/src/androidHostTest/kotlin/app/aaps/workflow/PrepareGraphDataRunnerTest.kt b/workflow/src/androidHostTest/kotlin/app/aaps/workflow/PrepareGraphDataRunnerTest.kt index 9c22b5a3a256..8a4f2fc6c210 100644 --- a/workflow/src/androidHostTest/kotlin/app/aaps/workflow/PrepareGraphDataRunnerTest.kt +++ b/workflow/src/androidHostTest/kotlin/app/aaps/workflow/PrepareGraphDataRunnerTest.kt @@ -1,5 +1,6 @@ package app.aaps.workflow +import app.aaps.core.data.iob.InMemoryGlucoseValue import app.aaps.core.data.model.CA import app.aaps.core.data.model.GV import app.aaps.core.data.time.T @@ -7,6 +8,7 @@ import app.aaps.core.interfaces.aps.AutosensData import app.aaps.core.interfaces.aps.AutosensDataStore import app.aaps.core.interfaces.aps.IobTotal import app.aaps.core.interfaces.aps.Sensitivity +import app.aaps.core.interfaces.calibration.Calibration import app.aaps.core.interfaces.concurrent.AapsLock import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.iob.IobCobCalculator @@ -18,6 +20,8 @@ import app.aaps.core.interfaces.overview.graph.TimeRange import app.aaps.core.interfaces.profiling.Profiler import app.aaps.core.interfaces.rx.bus.RxBus import app.aaps.core.interfaces.rx.events.EventBucketedDataCreated +import app.aaps.core.interfaces.smoothing.Smoothing +import app.aaps.core.interfaces.source.BgSource import app.aaps.core.interfaces.workflow.CalculationSignalsEmitter import app.aaps.core.interfaces.workflow.CalculationWorkflow.ProgressData import app.aaps.core.objects.workflow.WorkOutcome @@ -51,6 +55,8 @@ class PrepareGraphDataRunnerTest : TestBaseWithProfile() { @Mock lateinit var cache: OverviewDataCache @Mock lateinit var overviewData: OverviewData @Mock lateinit var signals: CalculationSignalsEmitter + @Mock lateinit var activeCalibration: Calibration + @Mock lateinit var activeSmoothing: Smoothing private val autosensDataProvider = { mock() } @@ -220,4 +226,47 @@ class PrepareGraphDataRunnerTest : TestBaseWithProfile() { // Terminal-only progress not emitted when emitFinalProgress = false verify(signals, never()).emitProgress(eq(ProgressData.DRAW_FINAL), any()) } + + // ----- never correct twice: glucose the sensor already corrected is not calibrated again here ----- + + /** Makes the smoothing step run on one real reading, with [source] as the active BG source. */ + private suspend fun stubSmoothingCalls(source: BgSource) { + val data = mutableListOf(InMemoryGlucoseValue(timestamp = 1000L, value = 100.0)) + whenever(dataAds.bucketedData).thenReturn(data) + whenever(dataIobCob.calculateIobFromBolus()).thenReturn(IobTotal(0L)) + whenever(dataIobCob.calculateIobFromTempBasalsIncludingConvertedExtended()).thenReturn(IobTotal(0L)) + whenever(activePlugin.activeBgSource).thenReturn(source) + whenever(activePlugin.activeCalibration).thenReturn(activeCalibration) + whenever(activeCalibration.calibrate(any(), any())).thenAnswer { it.getArgument(0) } + whenever(activePlugin.activeSmoothing).thenReturn(activeSmoothing) + whenever(activeSmoothing.smooth(any())).thenAnswer { it.getArgument(0) } + } + + private fun source(calibratesInSensor: Boolean): BgSource = mock().also { + whenever(it.calibratesInSensor()).thenReturn(calibratesInSensor) + } + + @Test + fun `no calibration in the app when the source calibrates in the sensor`() = runTest { + stubSuspendCalls() + stubSmoothingCalls(source(calibratesInSensor = true)) + whenever(workflowChainData.prepareFor(anyOrNull(), any())).thenReturn(buildData(bgDataReload = true, emitFinalProgress = false)) + + assertIs(run()) + + verify(activeCalibration, never()).calibrate(any(), any()) + // Smoothing is a local filter, so it still runs. + verify(activeSmoothing).smooth(any()) + } + + @Test + fun `calibration runs in the app for a normal source`() = runTest { + stubSuspendCalls() + stubSmoothingCalls(source(calibratesInSensor = false)) + whenever(workflowChainData.prepareFor(anyOrNull(), any())).thenReturn(buildData(bgDataReload = true, emitFinalProgress = false)) + + assertIs(run()) + + verify(activeCalibration).calibrate(any(), any()) + } } diff --git a/workflow/src/commonMain/kotlin/app/aaps/workflow/PrepareGraphDataRunner.kt b/workflow/src/commonMain/kotlin/app/aaps/workflow/PrepareGraphDataRunner.kt index 8654278db1fd..d2c07df645e4 100644 --- a/workflow/src/commonMain/kotlin/app/aaps/workflow/PrepareGraphDataRunner.kt +++ b/workflow/src/commonMain/kotlin/app/aaps/workflow/PrepareGraphDataRunner.kt @@ -184,7 +184,16 @@ class PrepareGraphDataRunner( val workingCopy = dataLock.withLock { bucketedData?.map { it.copy(smoothed = null, calibrated = null) }?.toMutableList() } ?: return - val calibrated = activePlugin.activeCalibration.calibrate(workingCopy, CalibrationContext.NONE) + // A sensor that holds its own calibration: the fingerstick went to the sensor, its algorithm + // re-based itself, and the readings arriving here are already corrected. Fitting a line in the + // app on top would correct them twice. This rule has to live here and not only where an entry + // is stored, because entries made BEFORE the user switched sending on are still in the + // database and would otherwise keep correcting readings the sensor has already corrected. + // + // Smoothing still runs: it is a local filter, not a per sensor correction. + val calibrated = + if (activePlugin.activeBgSource.calibratesInSensor()) workingCopy + else activePlugin.activeCalibration.calibrate(workingCopy, CalibrationContext.NONE) val smoothed = activePlugin.activeSmoothing.smooth(calibrated) dataLock.withLock { bucketedData = smoothed From 8f961ddb4065ddec211d971a53cc38938363f134 Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 29 Oct 2026 00:20:08 +0100 Subject: [PATCH 07/27] Dexcom ONE+ / G7: cancel a high temp basal while no reading arrives The problem While a Dexcom ONE+ / G7 warms up (about 30 min), or while its Bluetooth link is lost and being rebuilt, no glucose arrives. When the last glucose is older than 7 minutes the oref glucose status is null, the APS does not run and the loop sets nothing new. A temp basal that is already running then keeps going until its own end, with no glucose to correct it. A high temp set just before a sensor change or a signal loss can so run for its whole duration. What it does (effect on dosing) New DexcomOnePlusWarmupBasalGuard. It cancels the running temp basal, so the pump goes back to the profile basal, only when ALL of these hold: - the Dexcom ONE+ / G7 plugin is the active BG source; - the loop is enabled and the mode is CLOSED_LOOP or CLOSED_LOOP_LGS (open loop, disabled loop and every paused or suspended mode are left alone, so a protective zero temp is never lifted); - the last glucose value in the database is older than 7 minutes, the same cutoff as the oref glucose status, so it never fights a temp the loop set on a fresh reading; - a temp basal is running and its absolute rate is above the profile basal by more than 0.005 U/h. It can only lower delivery, down to the profile basal. A low or zero temp is kept. It never sets a temp and never boluses. It cancels ANY temp above the profile basal, also one the user set by hand: with no glucose nothing tells a manual high temp from a loop temp that now runs blind. A manual temp at or below profile is kept. How it cancels - CommandQueue.cancelTempBasal(enforceNew = false, autoForced = false), the same call as LoopPlugin.applyAPSRequest, started without waiting for the result. A cancel the pump refuses stays a failure, so AAPS keeps counting the temp. - All conditions are checked again inside the launched job, right before the command. A fresh reading and a new loop temp that arrive in between are never cancelled. - Each cancel goes to the user entry log as CANCEL_TEMP_BASAL with the source DexcomOnePlus (the source this plugin already uses for its readings and sensor changes; it has its own icon and colour in the log), so the user can see that the BG source ended the temp. When it runs - DexcomOnePlusPlugin starts a collector in onStart and cancels it in onStop (it also runs on the plugin work scope that onStop cancels). Nothing runs while the plugin is off. - It is checked on every change of the warm-up / connection state while that state is active: WARMING, and also CONNECTING, RECONNECTING and PAIRING. So it acts on every link loss, not only on a new sensor. - A change is a change of the generic warm-up status or of the driver's status text. A long reconnect that reports new attempts is checked again each time, also after the glucose has become older than 7 min. - A real reading forces the state to READY, the status becomes null and the guard stops; the loop doses normally again. There is no setting: it is always on for this source. No new strings or keys. Adaptation to dev - The trigger reads the driver state (warmup) and keys a change on the generic CgmWarmupStatus plus the driver status text. CgmWarmupStatus on dev has no message field, so collecting warmupStatus alone would check a long reconnect only once, when the glucose is usually still fresh. - The class has a Metro @Inject on the class and gets the loop through a () -> Loop provider, which avoids a cycle with LoopPlugin. Tests - DexcomOnePlusWarmupBasalGuardTest (11): all conditions hold -> cancel; not the active source, loop disabled, open loop, suspended by user, recent glucose, no temp running, temp at or below profile -> no cancel; the command is exactly cancelTempBasal(enforceNew = false, autoForced = false) and the user entry is logged; a reading that arrives before the launched job runs -> no cancel and no log; nothing launched when the first check fails. Uses a test scheduler. - DexcomOnePlusPluginLifetimeTest (+2): the guard is asked on each warm-up or connection change while the plugin runs, including a reconnect where only the status text changes (each change awaited, so the state flow cannot merge two); after onStop the collector is no longer active, no work runs, and the guard is not asked again. No sleep. - The other plugin tests pass a mocked guard to the constructor. Unit tests only; not checked on a pump from this branch. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../source/DexcomOnePlusInsertionDateTest.kt | 2 +- .../source/DexcomOnePlusPluginLifetimeTest.kt | 41 +++- .../DexcomOnePlusPluginVisibilityTest.kt | 3 +- .../source/DexcomOnePlusPromotionOrderTest.kt | 2 +- .../DexcomOnePlusSensorAgeRepairTest.kt | 2 +- .../DexcomOnePlusSensorCalibrationTest.kt | 2 +- .../DexcomOnePlusWarmupBasalGuardTest.kt | 164 ++++++++++++++++ .../plugins/source/DexcomOnePlusPlugin.kt | 41 ++++ .../source/DexcomOnePlusWarmupBasalGuard.kt | 181 ++++++++++++++++++ 9 files changed, 432 insertions(+), 6 deletions(-) create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuardTest.kt create mode 100644 plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuard.kt diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt index d13b86df59fe..6a8f89a95fff 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt @@ -67,7 +67,7 @@ class DexcomOnePlusInsertionDateTest : TestBase() { whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())).thenReturn(emptyList()) plugin = DexcomOnePlusPlugin( rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, - activePlugin, rxBus, + mock(), activePlugin, rxBus, ) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt index 14400c7716ef..1482b3410566 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt @@ -28,6 +28,11 @@ import org.mockito.Mock import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verifyBlocking import org.mockito.kotlin.whenever /** @@ -46,6 +51,7 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { @Mock lateinit var notificationManager: NotificationManager @Mock lateinit var activePlugin: ActivePlugin + private val warmupBasalGuard: DexcomOnePlusWarmupBasalGuard = mock() private lateinit var driver: OnePlusCgmDriverStub private lateinit var plugin: DexcomOnePlusPlugin @@ -55,7 +61,7 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { driver = OnePlusCgmDriverStub() plugin = DexcomOnePlusPlugin( rh, AAPSLoggerTest(), preferences, config, notificationManager, FakeHost(driver), persistenceLayer, - activePlugin, rxBus, + warmupBasalGuard, activePlugin, rxBus, ) } @@ -121,6 +127,39 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { assertThat(plugin.hasRunningWork()).isFalse() } + @Test + fun `the basal guard is asked on each warm-up or connection change while the plugin runs`() = runTest { + plugin.onStart() + + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.WARMING, remainingMs = 60_000L)) + verifyBlocking(warmupBasalGuard, timeout(5_000L).times(1)) { ensureProfileBasalDuringWarmup(eq(plugin), any(), any()) } + // A reconnect with only a new status text is a change too: the glucose may be older by now. + // Each change is awaited before the next one: the state is a StateFlow, and two changes sent + // at once may be merged into one before the collector sees them. + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.RECONNECTING, message = "attempt 1")) + verifyBlocking(warmupBasalGuard, timeout(5_000L).times(2)) { ensureProfileBasalDuringWarmup(eq(plugin), any(), any()) } + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.RECONNECTING, message = "attempt 2")) + verifyBlocking(warmupBasalGuard, timeout(5_000L).times(3)) { ensureProfileBasalDuringWarmup(eq(plugin), any(), any()) } + + plugin.onStop() + } + + @Test + fun `the basal guard runs only between onStart and onStop`() = runTest { + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.WARMING, remainingMs = 60_000L)) + plugin.onStart() + verifyBlocking(warmupBasalGuard, timeout(5_000L).times(1)) { ensureProfileBasalDuringWarmup(eq(plugin), any(), any()) } + assertThat(plugin.isWarmupGuardRunning()).isTrue() + plugin.onStop() + + // No collector and no job are left after onStop, so nothing can call the guard again. + assertThat(plugin.isWarmupGuardRunning()).isFalse() + assertThat(plugin.hasRunningWork()).isFalse() + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.RECONNECTING, message = "after stop")) + + verifyBlocking(warmupBasalGuard, times(1)) { ensureProfileBasalDuringWarmup(any(), any(), any()) } + } + /** Everything the plugin asks of the phone, answered without Bluetooth or a file. */ private class FakeHost(private val driver: OnePlusCgmDriver) : DexcomOnePlusHost { diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt index 230446595026..33366db698db 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt @@ -14,6 +14,7 @@ import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock +import org.mockito.kotlin.mock import org.mockito.kotlin.whenever /** @@ -40,7 +41,7 @@ class DexcomOnePlusPluginVisibilityTest : TestBase() { fun setup() { plugin = DexcomOnePlusPlugin( rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, - activePlugin, rxBus + mock(), activePlugin, rxBus ) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt index 3846f219cc4f..dd998dc46984 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt @@ -84,7 +84,7 @@ class DexcomOnePlusPromotionOrderTest : TestBase() { .thenReturn(PersistenceLayer.TransactionResult()) plugin = DexcomOnePlusPlugin( rh, logger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, - activePlugin, rxBus, + mock(), activePlugin, rxBus, ) plugin.promotionAlerter = { alerts += it } } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt index d0b65e63511e..03d87e18efb7 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt @@ -76,7 +76,7 @@ class DexcomOnePlusSensorAgeRepairTest : TestBase() { .thenReturn(emptyList()) plugin = DexcomOnePlusPlugin( rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, - activePlugin, rxBus, + mock(), activePlugin, rxBus, ) DexcomOnePlusIngest.reset() } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt index 963a537b6393..e14798b1cc87 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt @@ -58,7 +58,7 @@ class DexcomOnePlusSensorCalibrationTest : TestBase() { whenever(rh.gs(any())).thenReturn("not sent") plugin = DexcomOnePlusPlugin( rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, - activePlugin, rxBus, + mock(), activePlugin, rxBus, ) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuardTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuardTest.kt new file mode 100644 index 000000000000..6629fa0575d1 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuardTest.kt @@ -0,0 +1,164 @@ +package app.aaps.plugins.source + +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.RM +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.model.TB +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.data.ue.Action +import app.aaps.core.data.ue.Sources +import app.aaps.core.interfaces.aps.Loop +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.logging.UserEntryLogger +import app.aaps.core.interfaces.profile.EffectiveProfile +import app.aaps.core.interfaces.pump.PumpEnactResult +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.source.BgSource +import app.aaps.shared.tests.TestBaseWithProfile +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +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.verifyNoInteractions +import org.mockito.kotlin.whenever + +/** + * When [DexcomOnePlusWarmupBasalGuard] cancels a temp basal: every condition, one test each, plus + * the case where all of them hold. The last tests check the pump command it starts, the user entry + * log, and the second check right before the command. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class DexcomOnePlusWarmupBasalGuardTest : TestBaseWithProfile() { + + private val loop: Loop = mock() + private val commandQueue: CommandQueue = mock() + private val uel: UserEntryLogger = mock() + private val cancelResult: PumpEnactResult = mock() + private val persistenceLayer: PersistenceLayer = mock() + private val owner: BgSource = mock() + private val profile: EffectiveProfile = mock() + + private lateinit var guard: DexcomOnePlusWarmupBasalGuard + + private val fixedNow = 1_000_000_000L + private val highTemp = TB(timestamp = fixedNow - 60_000L, type = TB.Type.NORMAL, isAbsolute = true, rate = 2.0, duration = 30 * 60_000L) + private val lowTemp = TB(timestamp = fixedNow - 60_000L, type = TB.Type.NORMAL, isAbsolute = true, rate = 0.3, duration = 30 * 60_000L) + + @BeforeEach + fun prepareGuard() { + guard = DexcomOnePlusWarmupBasalGuard(aapsLogger, commandQueue, uel, { loop }, activePlugin, profileFunction, persistenceLayer) + runTest { + // Happy path: active source, closed loop, no fresh glucose, HIGH residual temp, profile 1.0 U/h. + whenever(activePlugin.activeBgSource).thenReturn(owner) + whenever(loop.isEnabled()).thenReturn(true) + whenever(loop.runningMode()).thenReturn(RM.Mode.CLOSED_LOOP) + whenever(persistenceLayer.getLastGlucoseValue()).thenReturn(null) + whenever(persistenceLayer.getTemporaryBasalActiveAt(fixedNow)).thenReturn(highTemp) + whenever(profile.getBasal()).thenReturn(1.0) + whenever(profileFunction.getProfile()).thenReturn(profile) + whenever(cancelResult.success).thenReturn(true) + whenever(commandQueue.cancelTempBasal(any(), any())).thenReturn(cancelResult) + } + } + + @Test + fun `high temp, no fresh glucose, closed loop, active source → cancel`() = runTest { + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isTrue() + } + + @Test + fun `not the active BG source → skip`() = runTest { + whenever(activePlugin.activeBgSource).thenReturn(mock()) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `loop disabled → skip`() = runTest { + whenever(loop.isEnabled()).thenReturn(false) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `open loop → skip (do not auto-enact)`() = runTest { + whenever(loop.runningMode()).thenReturn(RM.Mode.OPEN_LOOP) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `suspended by user → skip (never lift a protective zero-temp)`() = runTest { + whenever(loop.runningMode()).thenReturn(RM.Mode.SUSPENDED_BY_USER) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `recent glucose present → skip (loop owns dosing)`() = runTest { + val recent = GV( + timestamp = fixedNow - 2 * 60_000L, + raw = null, + value = 120.0, + trendArrow = TrendArrow.FLAT, + noise = null, + sourceSensor = SourceSensor.UNKNOWN, + ) + whenever(persistenceLayer.getLastGlucoseValue()).thenReturn(recent) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `no active temp → skip (already on profile)`() = runTest { + whenever(persistenceLayer.getTemporaryBasalActiveAt(fixedNow)).thenReturn(null) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `temp at or below profile → skip (never raise delivery)`() = runTest { + whenever(persistenceLayer.getTemporaryBasalActiveAt(fixedNow)).thenReturn(lowTemp) + assertThat(guard.shouldCancelResidualTemp(owner, fixedNow)).isFalse() + } + + @Test + fun `the cancel is the loop's own call, not forced, and is in the user entry log`() = runTest { + guard.ensureProfileBasalDuringWarmup(owner, this) { fixedNow } + runCurrent() + + // autoForced = false: a cancel the pump refuses must stay a failure, so AAPS keeps the temp. + verify(commandQueue).cancelTempBasal(enforceNew = false, autoForced = false) + verify(uel).log(Action.CANCEL_TEMP_BASAL, Sources.DexcomOnePlus) + } + + @Test + fun `a reading that arrives before the launched cancel runs → nothing is cancelled`() = runTest { + guard.ensureProfileBasalDuringWarmup(owner, this) { fixedNow } + // The first check passed and the cancel is queued. Now a fresh reading arrives and the loop + // sets a new temp before the queued job runs. + val fresh = GV( + timestamp = fixedNow - 60_000L, + raw = null, + value = 180.0, + trendArrow = TrendArrow.FLAT, + noise = null, + sourceSensor = SourceSensor.UNKNOWN, + ) + whenever(persistenceLayer.getLastGlucoseValue()).thenReturn(fresh) + runCurrent() + + verify(commandQueue, never()).cancelTempBasal(any(), any()) + verifyNoInteractions(uel) + } + + @Test + fun `conditions not met at the first check → nothing is launched`() = runTest { + whenever(persistenceLayer.getTemporaryBasalActiveAt(fixedNow)).thenReturn(lowTemp) + guard.ensureProfileBasalDuringWarmup(owner, this) { fixedNow } + runCurrent() + + verify(commandQueue, never()).cancelTempBasal(any(), any()) + verifyNoInteractions(uel) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt index f10af1a9390a..74f783a3596a 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt @@ -63,6 +63,8 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex @@ -96,6 +98,7 @@ class DexcomOnePlusPlugin @Inject constructor( notificationManager: NotificationManager, private val host: DexcomOnePlusHost, private val persistenceLayer: PersistenceLayer, + private val warmupBasalGuard: DexcomOnePlusWarmupBasalGuard, private val activePlugin: ActivePlugin, private val rxBus: RxBus, ) : AbstractBgSourcePlugin( @@ -197,6 +200,12 @@ class DexcomOnePlusPlugin @Inject constructor( /** Namespaced store for the STAGING sensor (identity / markers / session start kept separate). */ private val stagingStore by lazy { host.slotStore(host.stagingNamespace) } + /** Runs [DexcomOnePlusWarmupBasalGuard] on every warm-up / connection change. Started in onStart, cancelled in onStop. */ + private var warmupGuardJob: Job? = null + + /** True while the [DexcomOnePlusWarmupBasalGuard] collector runs. For tests. */ + internal fun isWarmupGuardRunning(): Boolean = warmupGuardJob?.isActive == true + /** Session start already checked by [healMissingSensorChange], so a deletion is not undone twice. */ @Volatile private var healedSensorChangeStartMs: Long = 0L @@ -372,10 +381,42 @@ class DexcomOnePlusPlugin @Inject constructor( "autoResumeQueued=$autoResumeQueued " + "stagingResumeQueued=$stagingResumeQueued", ) + startWarmupBasalGuard() + } + + /** + * While the sensor warms up or the link is (re)connecting, no glucose arrives and the APS does + * not run, so a high temp basal could keep running blind. On every change of that state the + * guard checks its conditions and may cancel a temp basal above profile, see + * [DexcomOnePlusWarmupBasalGuard]. It works in the background, with no screen open, and does + * nothing once a reading ends the warm-up (the state becomes null). + * + * A change is a change of the generic status or of the driver's status text, so a long + * reconnect that keeps reporting new attempts is checked again each time, also after the last + * glucose has become older than 7 minutes. + */ + private fun startWarmupBasalGuard() { + warmupGuardJob?.cancel() + warmupGuardJob = ioScope().launch { + warmup + .map { state -> DexcomOnePlusWarmupMapper.toCgmWarmupStatus(state)?.let { status -> status to state.message } } + .distinctUntilChanged() + .collect { active -> + if (active != null) { + try { + warmupBasalGuard.ensureProfileBasalDuringWarmup(this@DexcomOnePlusPlugin, ioScope()) + } catch (t: Throwable) { + aapsLogger.error(LTag.BGSOURCE, "ONEPLUS_WARMUP_BASAL guard error: ${t.message}", t) + } + } + } + } } override suspend fun onStop() { cancelReconnectWatchdog() + warmupGuardJob?.cancel() + warmupGuardJob = null driver.removeWatcher(this) driver.shutdown() // Tear down any staging session too (independent of production). diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuard.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuard.kt new file mode 100644 index 000000000000..a28810760e6d --- /dev/null +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/DexcomOnePlusWarmupBasalGuard.kt @@ -0,0 +1,181 @@ +package app.aaps.plugins.source + +import app.aaps.core.data.ue.Action +import app.aaps.core.data.ue.Sources +import app.aaps.core.interfaces.aps.Loop +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.logging.UserEntryLogger +import app.aaps.core.interfaces.plugin.ActivePlugin +import app.aaps.core.interfaces.profile.ProfileFunction +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.source.BgSource +import app.aaps.core.objects.extensions.convertedToAbsolute +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import dev.zacsweers.metro.Inject +import kotlin.math.absoluteValue +import kotlin.math.roundToLong +import kotlin.time.Clock + +/** + * Cancels a high temp basal while the Dexcom ONE+ / G7 gives no glucose. + * + * When: the plugin calls [ensureProfileBasalDuringWarmup] each time its warm-up / connection state + * changes while that state is active: sensor warm-up, and also CONNECTING, RECONNECTING and PAIRING, + * which is every time the Bluetooth link to the sensor is lost and comes back. + * + * Why: with no glucose newer than 7 minutes the APS does not run (the oref glucose status is null + * for older data), so the loop sets nothing new and a temp basal that is already running keeps + * going until its own end. During a 30 min warm-up, or a long signal loss, a high temp could run + * for its whole duration with no glucose to correct it. + * + * What: cancel the running temp basal, so the pump goes back to the profile basal. Only when ALL of + * these hold ([shouldCancelResidualTemp]): + * - this plugin is the active BG source (never act for another source); + * - the loop is enabled and the running mode is CLOSED_LOOP or CLOSED_LOOP_LGS + * (`isClosedLoopOrLgs()`). Open loop, disabled loop and every paused mode (suspended, + * disconnected, super bolus) are left alone, so a protective zero temp is never lifted; + * - the last glucose value is older than [GLUCOSE_FRESHNESS_MIN] minutes. With fresher glucose the + * loop may have set the temp on purpose, and this guard must not fight it; + * - a temp basal is running and its absolute rate is ABOVE the profile basal by more than + * [RATE_EPSILON_U_PER_H]. A low or zero temp is kept, so this can only lower delivery, down to + * the profile basal, never raise it. + * + * This is ANY temp basal above the profile basal, also one the user set by hand. With no glucose + * there is nothing that tells a manual high temp from a loop temp that is now running blind, so + * both are ended. A manual temp at or below the profile basal is kept, like every low temp. + * + * How: `CommandQueue.cancelTempBasal(enforceNew = false, autoForced = false)`, the same call the + * loop makes in `LoopPlugin.applyAPSRequest`. A cancel the pump refuses stays a failure, so AAPS + * keeps counting the temp. The conditions are checked again inside the launched job, just before + * the command, so a fresh reading and a new loop temp that arrive in between are never cancelled. + * Each cancel is written to the user entry log (`CANCEL_TEMP_BASAL`, source `DexcomOnePlus`), so the + * user can see that this BG source ended the temp and why. + * + * Cancelling goes back to the profile schedule, so no limit is bypassed, and it does nothing when + * repeated, so calling it on every state change is safe. Software behaviour only, not medical + * advice. + */ +@Inject +class DexcomOnePlusWarmupBasalGuard( + private val aapsLogger: AAPSLogger, + private val commandQueue: CommandQueue, + private val uel: UserEntryLogger, + private val loopProvider: () -> Loop, + private val activePlugin: ActivePlugin, + private val profileFunction: ProfileFunction, + private val persistenceLayer: PersistenceLayer, +) { + + /** + * Evaluate the guards and, if warranted, revert the pump to profile basal. The pump command is + * launched fire-and-forget on [scope] (per the CommandQueue deadlock guidance — never await a + * queue command from a queue/BLE execution context). The guards are checked again in the + * launched job, with a new [now], right before the command: a reading and a new loop temp may + * have arrived since the first check. + */ + suspend fun ensureProfileBasalDuringWarmup( + owner: BgSource, + scope: CoroutineScope, + now: () -> Long = { Clock.System.now().toEpochMilliseconds() }, + ) { + if (!shouldCancelResidualTemp(owner, now())) return + scope.launch { + if (!shouldCancelResidualTemp(owner, now())) { + aapsLogger.info(LTag.APS, "ONEPLUS_WARMUP_BASAL: state changed before the cancel, nothing sent") + return@launch + } + uel.log(Action.CANCEL_TEMP_BASAL, Sources.DexcomOnePlus) + val result = commandQueue.cancelTempBasal(enforceNew = false, autoForced = false) + if (!result.success) { + aapsLogger.error(LTag.APS, "ONEPLUS_WARMUP_BASAL: cancel failed, the temp basal stays counted: ${result.comment}") + } + } + } + + /** + * Pure decision (all guards) — extracted for unit testing. Returns true only when a residual + * temp **above** profile basal should be cancelled under safe conditions. + */ + internal suspend fun shouldCancelResidualTemp(owner: BgSource, nowMs: Long): Boolean { + if (activePlugin.activeBgSource !== owner) return false + + val loop = loopProvider() + if (!loop.isEnabled()) return false + + val mode = loop.runningMode() + if (!mode.isClosedLoopOrLgs()) { + aapsLogger.debug(LTag.APS, "ONEPLUS_WARMUP_BASAL: skip — mode=$mode (not closed-loop/LGS)") + return false + } + + // Recent-glucose guard: if the loop still has fresh glucose it may have set this temp + // legitimately — do not fight it. Act only once glucose is as stale as the APS considers it. + val lastGv = persistenceLayer.getLastGlucoseValue() + if (lastGv != null && nowMs - lastGv.timestamp < GLUCOSE_FRESHNESS_MIN * 60_000L) { + aapsLogger.debug(LTag.APS, "ONEPLUS_WARMUP_BASAL: skip — recent glucose present, loop owns dosing") + return false + } + + val tb = persistenceLayer.getTemporaryBasalActiveAt(nowMs) + if (tb == null) { + aapsLogger.debug(LTag.APS, "ONEPLUS_WARMUP_BASAL: no active temp — pump already on profile") + return false + } + + val profile = profileFunction.getProfile() + if (profile == null) { + aapsLogger.debug(LTag.APS, "ONEPLUS_WARMUP_BASAL: no profile — skip") + return false + } + + val profileBasal = profile.getBasal() + val tempAbsolute = tb.convertedToAbsolute(nowMs, profile) + + // Never raise delivery while there is no glucose: only cancel a temp ABOVE profile. + if (tempAbsolute <= profileBasal + RATE_EPSILON_U_PER_H) { + aapsLogger.info( + LTag.APS, + "ONEPLUS_WARMUP_BASAL: keep temp ${rate(tempAbsolute)}U/h (<= profile ${rate(profileBasal)}U/h) — " + + "not raising delivery during warm-up", + ) + return false + } + + aapsLogger.info( + LTag.APS, + "ONEPLUS_WARMUP_BASAL: cancel high temp ${rate(tempAbsolute)}U/h (> profile ${rate(profileBasal)}U/h) → " + + "revert to profile basal (warm-up, no glucose)", + ) + return true + } + + /** + * A basal rate for the log, with three decimals. + * + * `String.format` is JVM only, and this class is shared code now. The rate is only ever read by + * a person in a log line, so a plain round is enough and it needs no locale. + */ + private fun rate(uPerHour: Double): String { + val milliUnits = (uPerHour * 1000.0).roundToLong() + val whole = milliUnits / 1000L + val fraction = (milliUnits % 1000L).absoluteValue + return "$whole.${fraction.toString().padStart(3, '0')}" + } + + companion object { + + /** Margin so a temp equal to (or within noise of) profile basal is treated as "not above". */ + private const val RATE_EPSILON_U_PER_H = 0.005 + + /** + * Glucose older than this counts as "no fresh glucose". Same 7 min as the oref glucose status + * (`GlucoseStatusCalculatorSMB`, `GlucoseStatusCalculatorAutoIsf`), so this guard acts exactly + * when the APS itself stops running. Kept local because `:plugins:aps` is not a dependency of + * this module; the two must stay aligned. + */ + private const val GLUCOSE_FRESHNESS_MIN = 7L + } +} From 7bfbe67ede2e5666887ed5c102429babab014b4e Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 29 Oct 2026 21:23:23 +0100 Subject: [PATCH 08/27] CGM sources: make the shared log screen and strings vendor neutral This prepares the shared CGM code for other native CGM drivers, so a second driver can use the same files without changing them. - The driver log screen no longer knows the Dexcom ONE+ / G7 driver. The caller gives the logger names (and an optional title) in the intent. The ONE+ screens pass their own log tag, so they show the same lines as before. - DriverLogReader.read() takes the logger names as a parameter. - The driver log screen has its own member injector, CgmMemberInjectors, apart from the ONE+ screens, so another driver can use the same file. - Its manifest entry sits on its own, after RequestDexcomPermissionActivity, apart from the ONE+ entries. - The string dexcom_oneplus_nav_back is now cgm_nav_back. - The generic cgm_* and staging_* strings are in their own block of strings.xml, away from the ONE+ strings. - Comments in the shared files no longer name ONE+ only. No change in behaviour. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../notifications/NotificationId.kt | 2 +- .../CgmDriverLogActivityIntentTest.kt | 41 +++++++++++++++ .../compose/DexcomOnePlusStartStringsTest.kt | 2 +- .../source/logs/DriverLogReaderTest.kt | 35 +++++++++++-- .../src/androidMain/AndroidManifest.xml | 7 +-- .../source/activities/CgmDriverLogActivity.kt | 42 ++++++++++++++-- .../activities/DexcomOnePlusStatusActivity.kt | 3 +- .../activities/DexcomOnePlusWarmupActivity.kt | 3 +- .../plugins/source/di/CgmMemberInjectors.kt | 33 ++++++++++++ .../source/di/SourceMemberInjectors.kt | 13 ++--- .../plugins/source/logs/DriverLogReader.kt | 19 +++---- .../src/androidMain/res/values/strings.xml | 50 ++++++++++--------- .../plugins/source/StagingAutoPromotion.kt | 4 +- .../plugins/source/compose/CgmScaffold.kt | 6 +-- .../aaps/plugins/source/compose/CgmWindow.kt | 2 +- .../plugins/source/compose/SensorAgeFormat.kt | 2 +- 16 files changed, 197 insertions(+), 67 deletions(-) create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivityIntentTest.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/di/CgmMemberInjectors.kt 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 0279cb28354c..e4d004539f28 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 @@ -258,7 +258,7 @@ enum class NotificationId( // the same reason as above. SECRETS_NOT_PROTECTED(IMPORTANT, SYSTEM), - // A pre-soak sensor (Dexcom ONE+ / G7) was made the production sensor by the app itself, without the + // A pre-soak sensor of a native CGM driver was made the production sensor by the app itself, without the // user pressing the promote button. Appended at the END for the same reason as above. CGM_STAGING_AUTO_PROMOTED(NORMAL, CGM); diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivityIntentTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivityIntentTest.kt new file mode 100644 index 000000000000..e43988649962 --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/activities/CgmDriverLogActivityIntentTest.kt @@ -0,0 +1,41 @@ +package app.aaps.plugins.source.activities + +import android.content.Intent +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +/** What a driver screen hands to the shared log screen, and what the log screen reads back. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [35]) +class CgmDriverLogActivityIntentTest { + + @Test + fun `the logger names and the title come back as they were given`() { + val context = RuntimeEnvironment.getApplication() + + val intent = CgmDriverLogActivity.intent(context, setOf("DEXCOM_ONEPLUS", "OTHER_DRIVER"), "My driver log") + + assertThat(intent.component?.className).isEqualTo(CgmDriverLogActivity::class.java.name) + assertThat(CgmDriverLogActivity.loggerNamesOf(intent)).containsExactly("DEXCOM_ONEPLUS", "OTHER_DRIVER") + assertThat(intent.getStringExtra(CgmDriverLogActivity.EXTRA_TITLE)).isEqualTo("My driver log") + } + + @Test + fun `without a title the intent carries none so the generic title is used`() { + val context = RuntimeEnvironment.getApplication() + + val intent = CgmDriverLogActivity.intent(context, setOf("DEXCOM_ONEPLUS")) + + assertThat(intent.hasExtra(CgmDriverLogActivity.EXTRA_TITLE)).isFalse() + assertThat(CgmDriverLogActivity.loggerNamesOf(intent)).containsExactly("DEXCOM_ONEPLUS") + } + + @Test + fun `an intent without logger names gives an empty set`() { + assertThat(CgmDriverLogActivity.loggerNamesOf(Intent())).isEmpty() + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt index 4546528d0be6..0a030045189e 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartStringsTest.kt @@ -95,7 +95,7 @@ class DexcomOnePlusStartStringsTest { SourceStrings.dexcom_oneplus_help_how_to_start, SourceStrings.dexcom_oneplus_help_permissions, SourceStrings.dexcom_oneplus_help_slot, - SourceStrings.dexcom_oneplus_nav_back, + SourceStrings.cgm_nav_back, SourceStrings.dexcom_oneplus_new_sensor_code_warning, SourceStrings.dexcom_oneplus_pairing_code_invalid, SourceStrings.dexcom_oneplus_pairing_code_required, diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt index 853cb19115f7..0dfd59bc52d5 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/logs/DriverLogReaderTest.kt @@ -8,6 +8,9 @@ import java.io.File /** What the log screen is allowed to show, and what it must not lose on the way. */ class DriverLogReaderTest { + /** The reader knows no driver, so the test names one, the way a caller does. */ + private val oneDriver = setOf("DEXCOM_ONEPLUS") + @Test fun `keeps only the lines of the driver`() { val lines = listOf( @@ -16,7 +19,7 @@ class DriverLogReaderTest { "10:00:00.003 [main] D/LoopPlugin: something else entirely", ) - assertThat(DriverLogReader.keep(lines, DriverLogReader.DRIVER_LOGGERS, 100)) + assertThat(DriverLogReader.keep(lines, oneDriver, 100)) .containsExactly("10:00:00.002 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_SESSION: link is up") } @@ -30,7 +33,7 @@ class DriverLogReaderTest { "java.lang.IllegalStateException: not ours either", ) - val kept = DriverLogReader.keep(lines, DriverLogReader.DRIVER_LOGGERS, 100) + val kept = DriverLogReader.keep(lines, oneDriver, 100) assertThat(kept).hasSize(3) assertThat(kept[1]).isEqualTo("java.io.IOException: link closed") @@ -41,7 +44,7 @@ class DriverLogReaderTest { fun `when there are too many lines the newest are the ones kept`() { val lines = (1..10).map { "10:00:00.00$it [main] I/DEXCOM_ONEPLUS: line $it" } - val kept = DriverLogReader.keep(lines, DriverLogReader.DRIVER_LOGGERS, 3) + val kept = DriverLogReader.keep(lines, oneDriver, 3) assertThat(kept).hasSize(3) assertThat(kept.last()).endsWith("line 10") @@ -63,7 +66,7 @@ class DriverLogReaderTest { @Test fun `a build that has not written anything yet answers with nothing`(@TempDir folder: File) { - assertThat(DriverLogReader.read(folder.absolutePath)).isEmpty() + assertThat(DriverLogReader.read(folder.absolutePath, oneDriver)).isEmpty() } @Test @@ -74,10 +77,32 @@ class DriverLogReaderTest { "10:00:00.003 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_BG: value taken\n" ) - val all = DriverLogReader.read(folder.absolutePath) + val all = DriverLogReader.read(folder.absolutePath, oneDriver) assertThat(all).hasSize(2) assertThat(all.first()).contains("DEXCOM_ONEPLUS_SCAN") assertThat(all.last()).contains("DEXCOM_ONEPLUS_BG") } + + @Test + fun `only the lines of the logger names the caller gives are kept`() { + val lines = listOf( + "10:00:00.001 [main] I/DEXCOM_ONEPLUS: from the first driver", + "10:00:00.002 [main] I/OTHER_DRIVER: from the second driver", + "10:00:00.003 [main] I/OTHER_DRIVER_SCAN: a name that only starts the same", + ) + + assertThat(DriverLogReader.keep(lines, setOf("OTHER_DRIVER"), 100)) + .containsExactly("10:00:00.002 [main] I/OTHER_DRIVER: from the second driver") + assertThat(DriverLogReader.keep(lines, setOf("DEXCOM_ONEPLUS", "OTHER_DRIVER"), 100)).hasSize(2) + } + + @Test + fun `no logger names means no lines even when the file has some`(@TempDir folder: File) { + File(folder, DriverLogReader.CURRENT_FILE).writeText( + "10:00:00.001 [main] I/DEXCOM_ONEPLUS: DEXCOM_ONEPLUS_SCAN: sensor heard\n" + ) + + assertThat(DriverLogReader.read(folder.absolutePath, emptySet())).isEmpty() + } } diff --git a/plugins/source/src/androidMain/AndroidManifest.xml b/plugins/source/src/androidMain/AndroidManifest.xml index fd232df66307..7296b96efe8b 100644 --- a/plugins/source/src/androidMain/AndroidManifest.xml +++ b/plugins/source/src/androidMain/AndroidManifest.xml @@ -10,6 +10,10 @@ android:name=".activities.RequestDexcomPermissionActivity" android:exported="false" /> + + - + Back + Close + Show more + Show less + Step %1$d of %2$d + remaining + Ends at %1$s + What happened + Sensor + Name + Address + Actions + Bluetooth session + Sensor driver log + Refresh + Share the log + Nothing yet. Lines appear here as soon as the driver starts working. + %1$d lines + Driver log + Follow + Switch to the pre-soak sensor automatically + After the set number of hours, the pre-soak sensor feeds the loop if its recent readings are good. The sensor in use is stopped. The promote button still works. + Hours before the automatic switch + The pre-soak sensor now feeds the loop. Automatic switch after %1$s. + MicroTech CGM App Receive CGM values from LinX, LinX vista, Equil G. Smart 2, Diaexpert 2 etc. @@ -80,7 +106,6 @@ Last successful MAC: %1$s Sensor warm-up ~30 minute warm-up countdown - Back Before pairing: allow nearby Bluetooth devices (and notifications if prompted). Keep the phone near the sensor during start and warm-up. Scan for nearby ONE+ / G7-family sensors. Stop other Dexcom / xDrip / Juggluco Direct apps first. Every ONE+ / G7 sensor in range is listed. The 4-digit code is not sent in the Bluetooth signal, so the app cannot use it to find your sensor. Pick the one you have just applied. The code is checked when you press Connect. @@ -199,10 +224,6 @@ Staging sensor has not settled long enough to promote yet. Staging sensor has not produced enough valid glucose yet. Staging sensor has not sent a reading in the last minutes. Wait until it reads again before switching to it. - Close - Show more - Show less - Step %1$d of %2$d Production Pre-soak How to start — 6 steps @@ -216,19 +237,11 @@ Signal %1$d dBm No sensor found yet. Press Scan and keep the phone right next to the sensor. Connect adopts %1$s and opens warm-up. - remaining - Ends at %1$s - What happened Try connecting again Start another sensor - Sensor - Name - Address Status Production sensor Pre-soak sensor - Actions - Bluetooth session Started %1$s ago No reading received yet. Readings collected @@ -237,16 +250,5 @@ Starting a pre-soak sensor now means the next one is already warm when this one stops. Start a pre-soak sensor A pre-soak sensor collects readings alongside the one in use. It never feeds the loop until you promote it here. - Sensor driver log - Refresh - Share the log - Nothing yet. Lines appear here as soon as the driver starts working. - %1$d lines - Driver log - Follow - Switch to the pre-soak sensor automatically - After the set number of hours, the pre-soak sensor feeds the loop if its recent readings are good. The sensor in use is stopped. The promote button still works. - Hours before the automatic switch - The pre-soak sensor now feeds the loop. Automatic switch after %1$s. \ No newline at end of file diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt index fc67d40afc9d..1e1ff28b8ca8 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/StagingAutoPromotion.kt @@ -4,7 +4,7 @@ package app.aaps.plugins.source * Decides when a pre-soak sensor may take over the loop by itself, without the user pressing the * promote button. * - * Used by the Dexcom ONE+ / G7 plugin. It is checked on every reading of the + * Used by the native CGM plugins that have a pre-soak sensor. It is checked on every reading of the * pre-soak sensor, so it needs no timer, it survives an app restart, and a sensor that sends nothing * is never switched to. * @@ -64,7 +64,7 @@ object StagingAutoPromotion { * @param startMs pre-soak start (epoch ms), 0 or less when not known * @param readings pre-soak readings as (timestamp ms, mg/dL), any order * @param minRecentReadings how many readings the last [RECENT_WINDOW_MS] must hold; it depends on - * the sensor cadence (5 min for ONE+ / G7) + * the sensor cadence (5 min for Dexcom ONE+ / G7) * @param nowMs current time (epoch ms) */ fun decide( diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt index 64eddb007c8b..cc0b6eda4ff5 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmScaffold.kt @@ -28,7 +28,7 @@ import app.aaps.core.ui.compose.stringResource import app.aaps.plugins.source.SourceStrings /** - * Which job the navigation icon of a ONE+ screen does — see the convention documented on + * Which job the navigation icon of a native CGM screen does — see the convention documented on * [app.aaps.core.ui.compose.AapsTopAppBar]. */ enum class CgmNavIcon { @@ -41,7 +41,7 @@ enum class CgmNavIcon { } /** - * Shared frame for every ONE+ / G7 screen. + * Shared frame for every native CGM driver screen. * * Three things are settled here once, instead of being re-decided per screen: * @@ -75,7 +75,7 @@ fun CgmScaffold( when (navIcon) { CgmNavIcon.Back -> Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, - contentDescription = stringResource(SourceStrings.dexcom_oneplus_nav_back), + contentDescription = stringResource(SourceStrings.cgm_nav_back), ) CgmNavIcon.Close -> Icon( diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt index 9cc238711f91..fc239a7eaa75 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/CgmWindow.kt @@ -21,7 +21,7 @@ enum class CgmWidth { } /** - * Size of the window a ONE+ screen is drawn in. + * Size of the window a native CGM screen is drawn in. * * The width classes follow the same 600 dp step as [TABLET_MIN_SW_DP], which the theme already uses * to scale typography, so a screen never disagrees with the theme about what a tablet is. diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt index 0fe150aae80f..517360b47e25 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/SensorAgeFormat.kt @@ -8,7 +8,7 @@ import kotlin.time.Duration.Companion.hours import kotlin.time.Duration.Companion.milliseconds /** - * The age of a CGM sensor, as shown in "Started %1$s ago" on the ONE+ screens. + * The age of a CGM sensor, as shown in "Started %1$s ago" on the native CGM screens. * * It keeps the two largest units, like the old `DateUtil.age(millis, false, rh)` did: * "2 days, 5 hours", "3 hours, 10 minutes", "7 minutes". Every piece comes from a translated From 4ffba70045faf297de8f5521523eaaac67b0967a Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 29 Oct 2026 22:45:10 +0100 Subject: [PATCH 09/27] Dexcom ONE+ / G7: start no work after the plugin is stopped The work scope of the plugin was made again on first use. So after onStop a late driver callback, the reconnect watchdog or a button on a setup screen could start new work that nothing would cancel, for example a Bluetooth reconnect while the plugin is switched off. - A `stopped` flag is set in onStop and cleared in onStart. While it is set no work scope is made: callbacks, the watchdog, the sensor age repair and the automatic promotion start nothing (logged at debug). - Connect on the Start screen, begin pre-soak and Promote are refused while the plugin is stopped, with a message that says to switch it on first. - onStop runs each step on its own, so a driver whose removeWatcher or shutdown throws no longer skips the work cancel or the session service stop. - onStop shuts down only driver instances that exist. The registry can now be asked for them without building a new one. Tests: late callbacks and user actions after onStop start no work and connect nothing; onStop finishes when the driver throws; onStop builds no driver. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../dexcomoneplus/OnePlusCgmDrivers.kt | 6 + .../source/DexcomOnePlusPluginLifetimeTest.kt | 116 ++++++++++++++++-- .../compose/DexcomOnePlusStartScreenTest.kt | 3 + .../source/DexcomOnePlusAndroidHost.kt | 4 + .../aaps/plugins/source/DexcomOnePlusHost.kt | 9 ++ .../plugins/source/DexcomOnePlusPlugin.kt | 113 +++++++++++++---- .../activities/DexcomOnePlusStartActivity.kt | 1 + .../activities/DexcomOnePlusStatusActivity.kt | 8 ++ .../compose/DexcomOnePlusStartScreen.kt | 10 ++ .../src/androidMain/res/values/strings.xml | 1 + 10 files changed, 237 insertions(+), 34 deletions(-) diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt index ec2a6dc9368b..7dc5cbe01c3d 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDrivers.kt @@ -63,6 +63,12 @@ object OnePlusCgmDrivers { /** The driver feeding the loop. */ fun default(): OnePlusCgmDriver = realProduction() + /** The production instance if one was built, else null. Builds nothing. */ + fun existingProduction(): OnePlusCgmDriverReal? = lock.withLock { productionReal } + + /** The staging instance if one was built, else null. Builds nothing. */ + fun existingStaging(): OnePlusCgmDriverReal? = lock.withLock { stagingReal } + /** The production driver, with [watcher] attached. Adding the same watcher twice is harmless. */ fun production(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = realProduction().also { it.addWatcher(watcher) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt index 1482b3410566..0be2775318db 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt @@ -5,6 +5,8 @@ import app.aaps.core.interfaces.db.PersistenceLayer import app.aaps.core.interfaces.notifications.NotificationManager import app.aaps.core.interfaces.plugin.ActivePlugin import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult import app.aaps.core.interfaces.source.StagingState import app.aaps.core.keys.interfaces.PreferenceItem import app.aaps.core.keys.interfaces.Preferences @@ -53,18 +55,22 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { private val warmupBasalGuard: DexcomOnePlusWarmupBasalGuard = mock() private lateinit var driver: OnePlusCgmDriverStub + private lateinit var host: FakeHost private lateinit var plugin: DexcomOnePlusPlugin @BeforeEach fun setup() = runTest { whenever(persistenceLayer.getBgReadingsDataFromTime(any(), any())).thenReturn(emptyList()) driver = OnePlusCgmDriverStub() - plugin = DexcomOnePlusPlugin( - rh, AAPSLoggerTest(), preferences, config, notificationManager, FakeHost(driver), persistenceLayer, - warmupBasalGuard, activePlugin, rxBus, - ) + host = FakeHost(driver) + plugin = pluginWith(host) } + private fun pluginWith(fakeHost: FakeHost) = DexcomOnePlusPlugin( + rh, AAPSLoggerTest(), preferences, config, notificationManager, fakeHost, persistenceLayer, + warmupBasalGuard, activePlugin, rxBus, + ) + @Test fun `a plugin that was never started runs nothing and its flows still answer`() { assertThat(plugin.hasRunningWork()).isFalse() @@ -160,23 +166,113 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { verifyBlocking(warmupBasalGuard, times(1)) { ensureProfileBasalDuringWarmup(any(), any(), any()) } } - /** Everything the plugin asks of the phone, answered without Bluetooth or a file. */ - private class FakeHost(private val driver: OnePlusCgmDriver) : DexcomOnePlusHost { + @Test + fun `late driver callbacks after onStop start no work`() = runTest { + plugin.onStart() + plugin.onStop() + + plugin.onSession(up = false, reason = "link lost") + plugin.onGlucose(OnePlusGlucoseSample(mgdl = 120.0, timestampMs = System.currentTimeMillis(), sequence = 900_002L)) + plugin.onWarmup(OnePlusWarmupState(phase = OnePlusWarmupState.Phase.RECONNECTING, message = "late")) + + assertThat(plugin.isStopped()).isTrue() + assertThat(plugin.hasWorkScope()).isFalse() + assertThat(plugin.isReconnectWatchdogArmed()).isFalse() + assertThat(plugin.hasRunningWork()).isFalse() + } + + @Test + fun `user actions after onStop are refused and connect nothing`() = runTest { + plugin.onStart() + plugin.onStop() + val attachesBefore = host.attachCount + + assertThat(plugin.beginStaging("AA:BB:CC:DD:EE:FF")).isFalse() + assertThat(plugin.promoteStagingToProduction(allowEarly = true)) + .isEqualTo(PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT)) + + // beginStaging attaches the pre-soak driver before it connects. It never got that far. + assertThat(host.attachCount).isEqualTo(attachesBefore) + assertThat(plugin.hasWorkScope()).isFalse() + assertThat(plugin.stagingState.value).isEqualTo(StagingState.ABSENT) + } + + @Test + fun `onStop finishes its work even when the driver throws`() = runTest { + val throwing = ThrowingDriver() + val throwingHost = FakeHost(throwing) + val stopping = pluginWith(throwingHost) + stopping.onStart() + stopping.onSession(up = false, reason = "link lost") + assertThat(stopping.hasRunningWork()).isTrue() + + stopping.onStop() + + assertThat(throwing.shutdownCalls).isEqualTo(2) // production and staging slot, both tried + assertThat(throwingHost.sessionServiceWanted).contains(false) + assertThat(stopping.hasWorkScope()).isFalse() + assertThat(stopping.hasRunningWork()).isFalse() + } + + @Test + fun `onStop does not build a driver only to shut it down`() = runTest { + val noDriverYet = FakeHost(driver, built = false) + val stopping = pluginWith(noDriverYet) + stopping.onStart() + val requestsBefore = noDriverYet.driverRequests + + stopping.onStop() + + assertThat(noDriverYet.driverRequests).isEqualTo(requestsBefore) + assertThat(noDriverYet.sessionServiceWanted).contains(false) + } + + /** A driver whose stop calls all throw, as a broken Bluetooth stack can. */ + private class ThrowingDriver(inner: OnePlusCgmDriver = OnePlusCgmDriverStub()) : OnePlusCgmDriver by inner { + + var shutdownCalls = 0 + + override fun removeWatcher(watcher: OnePlusGlucoseWatcher) = throw IllegalStateException("removeWatcher failed") + + override fun shutdown() { + shutdownCalls++ + throw IllegalStateException("shutdown failed") + } + } + + /** + * Everything the plugin asks of the phone, answered without Bluetooth or a file. + * + * @param built whether the registry already holds the driver instances. + */ + private class FakeHost(private val driver: OnePlusCgmDriver, private val built: Boolean = true) : DexcomOnePlusHost { private val stores = mutableMapOf() - override fun attachPlatform(driver: OnePlusCgmDriver) = Unit + /** Calls that would build a driver in the real registry. */ + var driverRequests = 0 + var attachCount = 0 + val sessionServiceWanted = mutableListOf() + + override fun attachPlatform(driver: OnePlusCgmDriver) { + attachCount++ + } + override fun slotStore(namespace: String?): OnePlusSensorStore = stores.getOrPut(namespace) { OnePlusSensorStore(MemoryPrefs()) } override val stagingNamespace: String = "staging" - override fun productionDriver(): OnePlusCgmDriver = driver - override fun stagingDriver(): OnePlusCgmDriver = driver + override fun productionDriver(): OnePlusCgmDriver = driver.also { driverRequests++ } + override fun stagingDriver(): OnePlusCgmDriver = driver.also { driverRequests++ } + override fun existingProductionDriver(): OnePlusCgmDriver? = driver.takeIf { built } + override fun existingStagingDriver(): OnePlusCgmDriver? = driver.takeIf { built } override fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = driver.also { it.addWatcher(watcher) } override fun promoteStagingInstance(): OnePlusCgmDriver? = null - override fun setSessionServiceWanted(wanted: Boolean) = Unit + override fun setSessionServiceWanted(wanted: Boolean) { + sessionServiceWanted += wanted + } override fun showWarmup(state: OnePlusWarmupState) = Unit override fun cancelWarmupNotification() = Unit override fun alert(message: String) = Unit diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt index a450d87cdad4..0be1906b9d9b 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt @@ -57,6 +57,7 @@ class DexcomOnePlusStartScreenTest { onBack = {}, onEnsureDriver = { OnePlusCgmDriverStub.instance }, onActivatePlugin = {}, + isPluginStopped = { false }, onStarted = {}, onBeginStaging = { true }, onIsStagingSensor = { false }, @@ -121,6 +122,8 @@ class DexcomOnePlusStartScreenTest { override val stagingNamespace: String = "staging" override fun productionDriver(): OnePlusCgmDriver = OnePlusCgmDriverStub.instance override fun stagingDriver(): OnePlusCgmDriver = OnePlusCgmDriverStub.instance + override fun existingProductionDriver(): OnePlusCgmDriver? = OnePlusCgmDriverStub.instance + override fun existingStagingDriver(): OnePlusCgmDriver? = OnePlusCgmDriverStub.instance override fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = OnePlusCgmDriverStub.instance diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt index 4b7a3347ae48..b13912ff1f01 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt @@ -57,6 +57,10 @@ class DexcomOnePlusAndroidHost( override fun stagingDriver(): OnePlusCgmDriver = OnePlusCgmDrivers.staging() + override fun existingProductionDriver(): OnePlusCgmDriver? = OnePlusCgmDrivers.existingProduction() + + override fun existingStagingDriver(): OnePlusCgmDriver? = OnePlusCgmDrivers.existingStaging() + override fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver = OnePlusCgmDrivers.production(watcher) diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt index 39472e486ef4..f7664dd81029 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt @@ -47,6 +47,15 @@ interface DexcomOnePlusHost { /** The second, independent driver for a pre-soak sensor. */ fun stagingDriver(): OnePlusCgmDriver + /** + * The driver feeding the loop if it was already built, else null. Unlike [productionDriver] this + * never builds one, so a stop does not make a driver only to shut it down. + */ + fun existingProductionDriver(): OnePlusCgmDriver? + + /** The pre-soak driver if it was already built, else null. See [existingProductionDriver]. */ + fun existingStagingDriver(): OnePlusCgmDriver? + /** The driver feeding the loop, with [watcher] attached. */ fun attachProductionDriver(watcher: OnePlusGlucoseWatcher): OnePlusCgmDriver diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt index 74f783a3596a..6e5f0f3276c8 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt @@ -54,6 +54,7 @@ import dev.zacsweers.metro.IntKey import dev.zacsweers.metro.SingleIn import dev.zacsweers.metro.binding import app.aaps.core.interfaces.concurrent.aapsIoDispatcher +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.cancel @@ -130,15 +131,35 @@ class DexcomOnePlusPlugin @Inject constructor( * * Made when work is first needed (normally by [onStart]) and cancelled in [onStop], so nothing * runs for a user who never enables the plugin, and nothing keeps running after it is stopped. - * A user action on a setup screen after a stop makes a new one. + * After [onStop] no new one is made until the next [onStart], see [stopped]. */ private var workScope: CoroutineScope? = null - /** Guards [workScope]. */ + /** Guards [workScope] and [stopped]. */ private val workScopeLock = AapsLock() - private fun ioScope(): CoroutineScope = workScopeLock.withLock { - workScope ?: CoroutineScope(SupervisorJob() + aapsIoDispatcher).also { workScope = it } + /** + * True from [onStop] until the next [onStart]. + * + * While it is true [ioScope] gives no scope, so a late driver callback, the reconnect watchdog or + * the automatic promotion cannot start work that nothing would ever cancel, for example a + * Bluetooth reconnect while the plugin is switched off. The setup screens ask [isStopped] and + * refuse their actions with a message. + */ + @Volatile + private var stopped = false + + /** True after [onStop] until the next [onStart]. The setup screens refuse their actions then. */ + fun isStopped(): Boolean = stopped + + /** The work scope, or null while the plugin is [stopped]. */ + private fun ioScope(): CoroutineScope? = workScopeLock.withLock { + if (stopped) { + aapsLogger.debug(LTag.BGSOURCE, "DEXCOM_ONEPLUS_SESSION: plugin is stopped, no new work started") + null + } else { + workScope ?: CoroutineScope(SupervisorJob() + aapsIoDispatcher).also { workScope = it } + } } /** Cancels everything started on [ioScope]. */ @@ -154,6 +175,12 @@ class DexcomOnePlusPlugin @Inject constructor( workScope?.coroutineContext?.get(Job)?.children?.any { it.isActive } == true } + /** True while a work scope exists, even an idle one. For tests. */ + internal fun hasWorkScope(): Boolean = workScopeLock.withLock { workScope != null } + + /** True while the reconnect watchdog waits. For tests. */ + internal fun isReconnectWatchdogArmed(): Boolean = reconnectWatchdog?.isActive == true + /** * The last resort that brings a sensor back. * @@ -347,6 +374,7 @@ class DexcomOnePlusPlugin @Inject constructor( override suspend fun onStart() { super.onStart() + workScopeLock.withLock { stopped = false } ioScope() syncDriverFromPrefs() // Rehydrate the ingest dedup BEFORE any reconnect can deliver glucose, so an app update / @@ -397,14 +425,15 @@ class DexcomOnePlusPlugin @Inject constructor( */ private fun startWarmupBasalGuard() { warmupGuardJob?.cancel() - warmupGuardJob = ioScope().launch { + warmupGuardJob = ioScope()?.launch { warmup .map { state -> DexcomOnePlusWarmupMapper.toCgmWarmupStatus(state)?.let { status -> status to state.message } } .distinctUntilChanged() .collect { active -> - if (active != null) { + val scope = ioScope() + if (active != null && scope != null) { try { - warmupBasalGuard.ensureProfileBasalDuringWarmup(this@DexcomOnePlusPlugin, ioScope()) + warmupBasalGuard.ensureProfileBasalDuringWarmup(this@DexcomOnePlusPlugin, scope) } catch (t: Throwable) { aapsLogger.error(LTag.BGSOURCE, "ONEPLUS_WARMUP_BASAL guard error: ${t.message}", t) } @@ -414,22 +443,45 @@ class DexcomOnePlusPlugin @Inject constructor( } override suspend fun onStop() { - cancelReconnectWatchdog() - warmupGuardJob?.cancel() + // First: from here on no new work may start, also not from a callback that arrives while + // the drivers below are shutting down. + workScopeLock.withLock { stopped = true } + // Each step on its own: a driver that throws must not skip the steps after it. The work + // cancel and the session service stop must always run. + stopStep("watchdog cancel") { cancelReconnectWatchdog() } + stopStep("warm-up guard cancel") { warmupGuardJob?.cancel() } warmupGuardJob = null - driver.removeWatcher(this) - driver.shutdown() + // Only the instances that exist. Asking the registry for "the driver" would build a new + // one just to shut it down. + host.existingProductionDriver()?.let { production -> + stopStep("production removeWatcher") { production.removeWatcher(this) } + stopStep("production shutdown") { production.shutdown() } + } // Tear down any staging session too (independent of production). - runCatching { stagingDriver.removeWatcher(stagingWatcher) } - runCatching { stagingDriver.shutdown() } - host.cancelWarmupNotification() - host.setSessionServiceWanted(false) - // Last, after the drivers are stopped, so no late callback can start new work after it. + host.existingStagingDriver()?.let { staging -> + stopStep("staging removeWatcher") { staging.removeWatcher(stagingWatcher) } + stopStep("staging shutdown") { staging.shutdown() } + } + stopStep("warm-up notification cancel") { host.cancelWarmupNotification() } + stopStep("session service stop") { host.setSessionServiceWanted(false) } + // Last, after the drivers are stopped. [stopped] already keeps late callbacks from making + // a new scope. cancelWork() aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_SESSION: plugin stop") super.onStop() } + /** One step of [onStop]. A throw is logged and does not stop the next steps. */ + private inline fun stopStep(name: String, step: () -> Unit) { + try { + step() + } catch (e: CancellationException) { + throw e + } catch (t: Throwable) { + aapsLogger.error(LTag.BGSOURCE, "DEXCOM_ONEPLUS_SESSION: plugin stop, $name failed: ${t.message}", t) + } + } + /** * Make sure this plugin watches the production driver and that the driver has its platform. * Safe to call from the Start screen before connect. @@ -489,7 +541,7 @@ class DexcomOnePlusPlugin @Inject constructor( return } val glucoseValues = listOf(DexcomOnePlusIngest.mapToGv(sample)) - ioScope().launch { + ioScope()?.launch { val result = persistenceLayer.insertCgmSourceData( Sources.DexcomOnePlus, glucoseValues, @@ -549,7 +601,7 @@ class DexcomOnePlusPlugin @Inject constructor( logSensorChange(startMs) return } - ioScope().launch { + ioScope()?.launch { val anchoredStartMs = DexcomOnePlusSensorChangeAnchor.resolve( autoStartMs = startMs, lastSensorChangeMs = persistenceLayer.getLastTherapyRecordUpToNow(TE.Type.SENSOR_CHANGE)?.timestamp, @@ -567,7 +619,7 @@ class DexcomOnePlusPlugin @Inject constructor( */ private fun logSensorChange(startMs: Long) { if (!preferences.get(BooleanKey.BgSourceCreateSensorChange)) return - ioScope().launch { writeSensorChange(startMs) } + ioScope()?.launch { writeSensorChange(startMs) } } /** @return true when a sensor change was really written (the DB refuses a duplicate timestamp). */ @@ -671,7 +723,7 @@ class DexcomOnePlusPlugin @Inject constructor( */ private fun armReconnectWatchdog() { reconnectWatchdog?.cancel() - reconnectWatchdog = ioScope().launch { + reconnectWatchdog = ioScope()?.launch { delay(RECONNECT_WATCHDOG_MS) if (driver.isSessionUp()) return@launch val real = driver @@ -784,6 +836,10 @@ class DexcomOnePlusPlugin @Inject constructor( * the UI keeps the invariant for every future call site. */ fun beginStaging(deviceAddress: String): Boolean { + if (stopped) { + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_STAGING: refused, the plugin is stopped") + return false + } // Like onSensorSessionStarted, and before the early return: a pre-soak started while // production is stopped is still a Bluetooth session, and without this it would run its GATT // link with no foreground service at all. @@ -927,8 +983,15 @@ class DexcomOnePlusPlugin @Inject constructor( * with no gap, and every other reader of [DexcomOnePlusHost.productionDriver] (the * Status/Warmup screens, the reconnect watchdog) now sees it too. */ - override suspend fun promoteStagingToProduction(allowEarly: Boolean): PromotionResult = - promoteMutex.withLock { promoteLocked(allowEarly, byAuto = false) } + override suspend fun promoteStagingToProduction(allowEarly: Boolean): PromotionResult { + // The screen asks isStopped first and says why. This is the check for every other caller: + // the pre-soak driver was shut down by onStop, so there is no running pre-soak to switch to. + if (stopped) { + aapsLogger.info(LTag.BGSOURCE, "DEXCOM_ONEPLUS_PROMOTE: refused, the plugin is stopped") + return PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT) + } + return promoteMutex.withLock { promoteLocked(allowEarly, byAuto = false) } + } /** The promotion itself. Call it only while holding [promoteMutex]. */ private suspend fun promoteLocked(allowEarly: Boolean, byAuto: Boolean): PromotionResult { @@ -1169,11 +1232,13 @@ class DexcomOnePlusPlugin @Inject constructor( nowMs = askedAtMs, ) if (decision != StagingAutoPromotion.Decision.PROMOTE) return + // Before the claim: a stopped plugin switches nothing, and must not keep the claim. + val scope = ioScope() ?: return val claimed = autoPromoteLock.withLock { if (autoPromoteInFlight) false else { autoPromoteInFlight = true; true } } if (!claimed) return - ioScope().launch { + scope.launch { try { val allowEarly = askedAtMs - startMs < DexcomOnePlusStaging.STAGING_MIN_SETTLE_MS aapsLogger.info( @@ -1205,7 +1270,7 @@ class DexcomOnePlusPlugin @Inject constructor( val startMs = sensorStore.loadSessionStart() _lifecycle.value = DexcomOnePlusStaging.computeLifecycle(startMs, nowMs()) - if (startMs > 0L) ioScope().launch { healMissingSensorChange(startMs) } + if (startMs > 0L) ioScope()?.launch { healMissingSensorChange(startMs) } } /** diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt index b4bf81648927..5ef536a09c6d 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt @@ -59,6 +59,7 @@ class DexcomOnePlusStartActivity : MetroAppCompatActivity() { type = PluginType.BGSOURCE, ) }, + isPluginStopped = { dexcomOnePlusPlugin.isStopped() }, onStarted = { startedSlot -> // PRODUCTION: hand the user to the warm-up screen so the new sensor is // visibly taken over (pairing → warm-up countdown). Returning straight to diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt index 1db7720a7307..bf1eef2c3ddb 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt @@ -126,6 +126,7 @@ class DexcomOnePlusStatusActivity : MetroAppCompatActivity() { lastGlucose = { persistenceLayer.getLastGlucoseValue() }, onCancelStaging = { dexcomOnePlusPlugin.cancelStaging() }, onPromote = { allowEarly -> dexcomOnePlusPlugin.promoteStagingToProduction(allowEarly) }, + isPluginStopped = { dexcomOnePlusPlugin.isStopped() }, onCorrectSensorStart = { startMs -> dexcomOnePlusPlugin.correctProductionSensorStart(startMs) }, ) } @@ -181,6 +182,8 @@ private fun DexcomOnePlusStatusScreen( lastGlucose: suspend () -> GV?, onCancelStaging: () -> Unit, onPromote: suspend (Boolean) -> PromotionResult, + /** True while the plugin is switched off: Promote is then refused with a message. */ + isPluginStopped: () -> Boolean, onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, ) { // Not `remember`-ed: a promotion swaps which driver instance `default()` hands out (see @@ -220,6 +223,7 @@ private fun DexcomOnePlusStatusScreen( val promoteFollowUpFailed = stringResource(R.string.dexcom_oneplus_staging_promote_follow_up_failed) val promoteFollowUpNoIdentity = stringResource(R.string.dexcom_oneplus_staging_promote_follow_up_failed_no_identity) val promoteRejectedAbsent = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_absent) + val promotePluginStopped = stringResource(R.string.dexcom_oneplus_plugin_stopped) val promoteRejectedNotSettled = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_not_settled) val promoteRejectedNoGlucose = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_no_glucose) val promoteRejectedNoRecentGlucose = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_no_recent_glucose) @@ -366,6 +370,10 @@ private fun DexcomOnePlusStatusScreen( onClick = { showPromoteConfirm = false val allowEarly = promoteEarly + if (isPluginStopped()) { + promoteResultText = promotePluginStopped + return@TextButton + } scope.launch { promoteResultText = dexcomOnePlusPromotionMessage( result = onPromote(allowEarly), diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt index 8b8482826d56..b8ff85cbb0c4 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt @@ -86,6 +86,11 @@ fun DexcomOnePlusStartScreen( onBack: () -> Unit, onEnsureDriver: () -> OnePlusCgmDriver, onActivatePlugin: () -> Unit, + /** + * True after the plugin was stopped (switched off) and before it starts again. Connect is then + * refused with a message: a session started now would run with no plugin to stop it. + */ + isPluginStopped: () -> Boolean, onStarted: (SensorSlot) -> Unit, /** STAGING only: the user started this sensor now — anchors the pre-soak clock on its MAC. */ onBeginStaging: (String) -> Boolean, @@ -170,6 +175,7 @@ fun DexcomOnePlusStartScreen( val serialNone = stringResource(SourceStrings.dexcom_oneplus_applicator_serial_none) val newSensorCodeWarning = stringResource(SourceStrings.dexcom_oneplus_new_sensor_code_warning) val stagingIsProduction = stringResource(SourceStrings.dexcom_oneplus_staging_is_production) + val pluginStopped = stringResource(SourceStrings.dexcom_oneplus_plugin_stopped) var connectRequested by remember { mutableStateOf(false) } // Guided-flow progress for the stepper: Prepare → Code → Connect → Warm-up. @@ -197,6 +203,10 @@ fun DexcomOnePlusStartScreen( // user with a selected device and no way to validate it — and the slot store still holding the // PREVIOUS sensor's MAC. val onConnectClick: () -> Unit = onConnectClick@{ + if (isPluginStopped()) { + errorText = pluginStopped + return@onConnectClick + } val identity = parsedIdentity ?: OnePlusGs1ApplicatorParser.parse(applicatorInput) if (identity == null) { diff --git a/plugins/source/src/androidMain/res/values/strings.xml b/plugins/source/src/androidMain/res/values/strings.xml index 6e912bfcf14f..2a9e4916f0a9 100644 --- a/plugins/source/src/androidMain/res/values/strings.xml +++ b/plugins/source/src/androidMain/res/values/strings.xml @@ -186,6 +186,7 @@ Promote it instead Cancel pre-soak and start here Leave it soaking + Dexcom ONE+ / G7 is switched off. Select it as BG source in Config Builder first, then try again. This sensor already feeds the loop. Start it from Production, not as a pre-soak. Pairing… Connecting to sensor… From afd474032ecd9401086a0d19407ad2c04c004798 Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Wed, 4 Nov 2026 09:54:02 +0100 Subject: [PATCH 10/27] Dexcom ONE+ / G7: refuse the Dexcom Stelo (DX01) The Stelo reads every 15 minutes, not every 5, and is not made for insulin dosing. It was accepted as a G7-family name. It is now refused before every other rule, so a stored name, a stored address or the FEBC service cannot let one through, and the scan log says why. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../identity/OnePlusAdvCandidateTest.kt | 15 +++++++++++- .../scan/OnePlusBleScannerAndroidTest.kt | 4 ++-- .../scan/OnePlusBleScannerAndroid.kt | 24 ++++++++++++++++++- .../identity/OnePlusAdvCandidate.kt | 21 ++++++++++++---- 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt index d0764d63e7ff..ff89ed8819dd 100644 --- a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidateTest.kt @@ -8,7 +8,8 @@ class OnePlusAdvCandidateTest { @Test fun isG7FamilyName_matchesJugglucoPrefixes() { assertThat(OnePlusAdvCandidate.isG7FamilyName("DX02aS")).isTrue() - assertThat(OnePlusAdvCandidate.isG7FamilyName("DX01xx")).isTrue() + // DX01 is the Dexcom Stelo, refused on purpose. + assertThat(OnePlusAdvCandidate.isG7FamilyName("DX01xx")).isFalse() assertThat(OnePlusAdvCandidate.isG7FamilyName("DXCMab")).isTrue() assertThat(OnePlusAdvCandidate.isG7FamilyName("DexcomONE")).isFalse() assertThat(OnePlusAdvCandidate.isG7FamilyName("Dexcom65")).isFalse() @@ -134,4 +135,16 @@ class OnePlusAdvCandidateTest { const val STORED_MAC = "AA:BB:CC:DD:EE:FF" const val OTHER_MAC = "11:22:33:44:55:66" } + + @Test + fun `a Stelo is refused even with a stored name or address`() { + assertThat(OnePlusAdvCandidate.isUnsupportedStelo("DX01ab")).isTrue() + assertThat(OnePlusAdvCandidate.isUnsupportedStelo(" dx01ab")).isTrue() + assertThat(OnePlusAdvCandidate.isUnsupportedStelo("DX02ab")).isFalse() + assertThat(OnePlusAdvCandidate.isUnsupportedStelo("DXCMab")).isFalse() + assertThat(OnePlusAdvCandidate.isUnsupportedStelo(null)).isFalse() + val stored = OnePlusStoredSession(OnePlusSensorIdentity(pin = "1234"), lastMac = "AA:BB:CC:DD:EE:FF", lastDeviceName = "DX01ab") + assertThat(OnePlusAdvCandidate.isCandidate("DX01ab", "AA:BB:CC:DD:EE:FF", stored)).isFalse() + assertThat(OnePlusAdvCandidate.isCandidate("DX01ab", null, null)).isFalse() + } } diff --git a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt index bc17311c7732..46bc60e3730c 100644 --- a/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt +++ b/plugins/dexcom_oneplus/src/androidHostTest/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroidTest.kt @@ -9,10 +9,10 @@ import org.junit.jupiter.api.Test class OnePlusBleScannerAndroidTest { @Test - fun `nameMatches accepts DX02 DX01 DXCM family only`() { + fun `nameMatches accepts DX02 and DXCM only and never the DX01 Stelo`() { assertThat(OnePlusBleScannerAndroid.nameMatches("DXCM12")).isTrue() assertThat(OnePlusBleScannerAndroid.nameMatches("DX02aS")).isTrue() - assertThat(OnePlusBleScannerAndroid.nameMatches("DX01xx")).isTrue() + assertThat(OnePlusBleScannerAndroid.nameMatches("DX01xx")).isFalse() assertThat(OnePlusBleScannerAndroid.nameMatches("DexcomONE")).isFalse() assertThat(OnePlusBleScannerAndroid.nameMatches("Dexcom65")).isFalse() } diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt index e3de85c1ab66..b82904ab35d7 100644 --- a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt @@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicReference * Platform LE scanner for Dexcom ONE+ / G7-family ADV. * * Soft filters (Juggluco `isG7`): - * - Local name `DXCM` / `DX02` / `DX01`, and/or + * - Local name `DXCM` / `DX02` (never the `DX01` Stelo, see [OnePlusAdvCandidate.isUnsupportedStelo]), and/or * - Advertisement includes service UUID FEBC ([OnePlusGattUuids.Advertisement]) * **without** a G6-style `Dexcom*` marketing name. * - Optional [sessionHint] sticky-matches last MAC / ADV name / serial. @@ -50,6 +50,9 @@ class OnePlusBleScannerAndroid( private val slot: String = OnePlusLogMarkers.SLOT_PRODUCTION, ) : OnePlusBleScanner { + /** Stelo transmitters already logged as refused. */ + private val refusedStelo: MutableSet = ConcurrentHashMap.newKeySet() + private val appContext = context.applicationContext private val bluetoothManager = appContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager @@ -156,6 +159,10 @@ class OnePlusBleScannerAndroid( val device = result.device ?: return val addr = device.address ?: return val name = device.name ?: result.scanRecord?.deviceName + if (OnePlusAdvCandidate.isUnsupportedStelo(name)) { + noteRefusedStelo(addr) + return + } if (addr.uppercase() != target) { // FEBC-matched neighbour: keep it only if it looks like a G7-family transmitter // (never a G6 `Dexcom*` companion), so the diagnostic cannot cry wolf. @@ -366,10 +373,25 @@ class OnePlusBleScannerAndroid( } } + /** Logs a refused Stelo once per transmitter, so the scan log does not fill up with it. */ + private fun noteRefusedStelo(address: String) { + if (refusedStelo.add(address.uppercase())) { + OnePlusLog.i( + "${OnePlusLogMarkers.SCAN}: [$slot] Dexcom Stelo ***${address.takeLast(5)} refused: it reads only " + + "every 15 minutes and is not made for insulin dosing", + ) + } + } + private fun handle(result: ScanResult) { val device = result.device ?: return val address = device.address ?: return val name = device.name ?: result.scanRecord?.deviceName + // Before the FEBC rule: a Stelo advertises the same service. + if (OnePlusAdvCandidate.isUnsupportedStelo(name)) { + noteRefusedStelo(address) + return + } val hasAdvUuid = result.scanRecord?.serviceUuids?.any { it.uuid == OnePlusGattUuids.Advertisement } == true diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt index 079b8771e3ec..958decc85ac6 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt @@ -3,7 +3,8 @@ package app.aaps.plugins.dexcomoneplus.identity /** * Juggluco-aligned ADV name / candidate matching for ONE+ / G7 family. * - * Juggluco `isG7`: local name starts with `DX` + (`CM`|`02`|`01`). + * Juggluco `isG7`: local name starts with `DX` + (`CM`|`02`|`01`). `01` is the Dexcom Stelo, which is + * refused here on purpose, see [isUnsupportedStelo]. * Once a device name is known from a successful session, prefer exact match. * * Do **not** treat marketing names like `Dexcom65` / `DexcomONE` as ONE+ candidates — @@ -25,12 +26,23 @@ object OnePlusAdvCandidate { if (!n.startsWith("DX", ignoreCase = true)) return false val rest = n.substring(2, 4) return rest.equals("CM", ignoreCase = true) || - rest.equals("02", ignoreCase = true) || - rest.equals("01", ignoreCase = true) + rest.equals("02", ignoreCase = true) } /** - * Open-scan name filter: G7/ONE+ family only (`DX02` / `DX01` / `DXCM`). + * A Dexcom Stelo (`DX01`). It is refused on purpose: it gives a reading every 15 minutes, not every + * 5, and it is not made for insulin dosing. The loop computes its trends from readings 5 minutes + * apart. Checked before every other rule, so a stored name, a stored address or the FEBC service + * cannot let one through. + */ + fun isUnsupportedStelo(name: String?): Boolean = + name?.trim()?.startsWith(STELO_PREFIX, ignoreCase = true) == true + + /** Advertised name prefix of the Dexcom Stelo. */ + const val STELO_PREFIX = "DX01" + + /** + * Open-scan name filter: G7/ONE+ family only (`DX02` / `DXCM`). The Stelo (`DX01`) is not part of it. * Intentionally excludes `Dex*` marketing names (G6 / phone companions). */ fun nameMatchesSoft(name: String?): Boolean = isG7FamilyName(name) @@ -46,6 +58,7 @@ object OnePlusAdvCandidate { address: String?, session: OnePlusStoredSession?, ): Boolean { + if (isUnsupportedStelo(name)) return false val storedName = session?.lastDeviceName if (!storedName.isNullOrBlank() && name != null && name.equals(storedName, ignoreCase = true)) { return true From 10ca47ae0ff1744ddaf9346a05359c4251747837 Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 5 Nov 2026 00:44:51 +0100 Subject: [PATCH 11/27] Dexcom ONE+ / G7: scanner rules (competing apps, free slot first, refusal guard, backfill on disconnect) The start screen warns when the Dexcom app, xDrip+ or Juggluco is installed, because a sensor talks to one phone app at a time. The scan list puts sensors whose phone slot is free first; the stored sensor keeps its place. After a sensor refuses us, AAPS waits 15 minutes before it asks again and stops at 3 refusals in a row, before the sensor locks itself; only the user's Connect tries again. Backfill packets that were queued when the link dropped are now kept. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/androidMain/AndroidManifest.xml | 10 ++ .../OnePlusInstalledAppsAndroid.kt | 24 ++++ .../scan/OnePlusBleScannerAndroid.kt | 15 +- .../dexcomoneplus/OnePlusCgmDriverReal.kt | 68 +++++++++- .../dexcomoneplus/OnePlusCompetingApps.kt | 66 +++++++++ .../identity/OnePlusAdvCandidate.kt | 23 ++-- .../dexcomoneplus/identity/OnePlusAdvSlot.kt | 44 ++++++ .../identity/OnePlusSensorStore.kt | 29 ++++ .../dexcomoneplus/scan/OnePlusScanResult.kt | 5 + .../session/OnePlusAuthRefusals.kt | 128 ++++++++++++++++++ .../session/OnePlusBackfillSession.kt | 73 ++++++++-- .../session/OnePlusBleSession.kt | 70 +++++++++- .../session/OnePlusSessionAuth.kt | 14 +- .../session/OnePlusSessionAuthKeks.kt | 12 +- .../OnePlusCgmDriverRealSharedTest.kt | 27 ++++ .../dexcomoneplus/OnePlusCompetingAppsTest.kt | 39 ++++++ .../identity/OnePlusAdvSlotTest.kt | 74 ++++++++++ .../OnePlusSensorStoreRefusalsTest.kt | 67 +++++++++ .../dexcomoneplus/session/FakeOnePlusGatt.kt | 69 ++++++++++ .../session/OnePlusAuthRefusalPolicyTest.kt | 99 ++++++++++++++ .../session/OnePlusBackfillSessionTest.kt | 68 ++++++++++ .../session/OnePlusBleSessionRefusalTest.kt | 87 ++++++++++++ .../source/DexcomOnePlusPluginLifetimeTest.kt | 2 + .../compose/DexcomOnePlusStartRulesTest.kt | 25 ++++ .../compose/DexcomOnePlusStartScreenTest.kt | 27 +++- .../source/DexcomOnePlusAndroidHost.kt | 5 + .../aaps/plugins/source/DexcomOnePlusHost.kt | 11 ++ .../source/compose/DexcomOnePlusStartRules.kt | 15 +- .../compose/DexcomOnePlusStartScreen.kt | 44 ++++++ .../source/compose/DexcomOnePlusUiLabels.kt | 9 ++ .../src/androidMain/res/values/strings.xml | 5 + 31 files changed, 1220 insertions(+), 34 deletions(-) create mode 100644 plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusInstalledAppsAndroid.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingApps.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlot.kt create mode 100644 plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusals.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingAppsTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlotTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreRefusalsTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/FakeOnePlusGatt.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusalPolicyTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSessionTest.kt create mode 100644 plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionRefusalTest.kt diff --git a/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml b/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml index 12d22f0fe647..39aff2167f17 100644 --- a/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml +++ b/plugins/dexcom_oneplus/src/androidMain/AndroidManifest.xml @@ -8,4 +8,14 @@ android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" /> + + + + + + + + + diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusInstalledAppsAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusInstalledAppsAndroid.kt new file mode 100644 index 000000000000..99b024bdb64f --- /dev/null +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusInstalledAppsAndroid.kt @@ -0,0 +1,24 @@ +package app.aaps.plugins.dexcomoneplus + +import android.content.Context +import android.content.pm.PackageManager + +/** + * [OnePlusInstalledApps] on Android, through the `PackageManager`. + * + * From Android 11 an app sees only the packages it declares. The packages of + * [OnePlusCompetingApps.KNOWN] are declared in this module's manifest under ``; a package + * missing there would always read as "not installed". + */ +class OnePlusInstalledAppsAndroid(context: Context) : OnePlusInstalledApps { + + private val packageManager: PackageManager = context.applicationContext.packageManager + + override fun isInstalled(packageName: String): Boolean = + try { + packageManager.getPackageInfo(packageName, 0) + true + } catch (_: PackageManager.NameNotFoundException) { + false + } +} diff --git a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt index b82904ab35d7..bfcbc7af93fe 100644 --- a/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt +++ b/plugins/dexcom_oneplus/src/androidMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusBleScannerAndroid.kt @@ -14,6 +14,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusLog import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattUuids import app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvCandidate +import app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvSlot import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CountDownLatch @@ -407,14 +408,20 @@ class OnePlusBleScannerAndroid( val sticky = !hint?.lastMac.isNullOrBlank() || !hint?.lastDeviceName.isNullOrBlank() if (sticky && !candidate && febcOk && !nameMatches(name)) return - val hit = OnePlusScanResult(address = address, name = name, rssi = result.rssi) + // Android hands the manufacturer data over without the company id in front. + val slotHeld = OnePlusAdvSlot.phoneSlotHeld( + result.scanRecord?.getManufacturerSpecificData(OnePlusAdvSlot.DEXCOM_COMPANY_ID), + ) + val hit = OnePlusScanResult(address = address, name = name, rssi = result.rssi, phoneSlotHeld = slotHeld) .apply { seenElapsedMs = SystemClock.elapsedRealtime() } val previous = seen.put(address, hit) - if (previous == null || previous.rssi != hit.rssi || previous.name != hit.name) { - val score = OnePlusAdvCandidate.rankScore(name, address, hit.rssi, hint) + if (previous == null || previous.rssi != hit.rssi || previous.name != hit.name || + previous.phoneSlotHeld != hit.phoneSlotHeld + ) { + val score = OnePlusAdvCandidate.rankScore(name, address, hit.rssi, hint, slotHeld) OnePlusLog.d( "${OnePlusLogMarkers.SCAN}: [$slot] device name=${name ?: "?"} rssi=${hit.rssi} " + - "score=$score addr=***${address.takeLast(5)}", + "slotHeld=${slotHeld ?: "?"} score=$score addr=***${address.takeLast(5)}", ) listener?.onDevice(hit) } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt index 11a6d187e8d6..d7cdc430cf92 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverReal.kt @@ -14,6 +14,9 @@ import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanListener import app.aaps.plugins.dexcomoneplus.scan.OnePlusScanResult +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusalLedger +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusalPolicy +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusals import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSession import app.aaps.plugins.dexcomoneplus.session.OnePlusMacArbiter import app.aaps.plugins.dexcomoneplus.session.OnePlusBleSessionSkeleton @@ -340,6 +343,26 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { scanner.updateSessionHint(store?.load()) } + private val refusalPolicy = OnePlusAuthRefusalPolicy() + + /** + * The refusal count of the slot this instance owns **right now**, read and written through the + * live [sensorStore] for the same reason as [savedSharedKey]: a promotion rebinds the store + * under a running link. + */ + private val refusalLedger = object : OnePlusAuthRefusalLedger { + override fun load(): OnePlusAuthRefusals = sensorStore?.loadAuthRefusals() ?: OnePlusAuthRefusals() + + override fun save(refusals: OnePlusAuthRefusals) { + sensorStore?.saveAuthRefusals(refusals) + } + } + + /** True when the stored sensor refused us so often that only the user may start it again. */ + private fun refusedTooOften(address: String): Boolean = + refusalPolicy.decide(refusalLedger.load(), address, Clock.System.now().toEpochMilliseconds()) == + OnePlusAuthRefusalPolicy.Decision.Locked + override fun addWatcher(watcher: OnePlusGlucoseWatcher) { watchersLock.withLock { if (!watchers.contains(watcher)) watchers.add(watcher) @@ -398,6 +421,16 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { // A new pairing is a new sensor, or a new session on it. dropPendingCalibration("new pairing") lastReading = null + // The user pressed Connect. Another code or another sensor starts the refusal count again; + // the same pair gets one more try, still not sooner than the pause. See OnePlusAuthRefusalPolicy. + val previousPin = sensorStore?.load()?.identity?.pin + refusalLedger.save( + refusalPolicy.afterUserStart( + refusals = refusalLedger.load(), + address = deviceAddress, + codeChanged = previousPin == null || previousPin != pairingCode, + ), + ) sensorStore?.saveIdentity( OnePlusSensorIdentity( pin = pairingCode, @@ -466,6 +499,14 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { return false } val deviceAddress = stored?.lastMac ?: return false + // Never on our own after the sensor refused us too often: the next refusal could lock it. + if (refusedTooOften(deviceAddress)) { + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] auto-resume skipped — the sensor refused us " + + "${refusalLedger.load().count} times in a row; the user has to start it again", + ) + return false + } // The path that reproduced the collision on every plugin start for an install whose two // stores already held the same MAC. Claim before queueing anything. if (!OnePlusMacArbiter.claim(deviceAddress, arbiterOwner)) { @@ -596,8 +637,29 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] shutdown") } - override fun warmupState(): OnePlusWarmupState = - session?.warmupState() ?: OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + /** + * With no session, a sensor that refused us too often still says so, also after a restart: + * otherwise the screens would show "idle" and the user would not know why nothing comes in. + */ + override fun warmupState(): OnePlusWarmupState { + session?.let { return it.warmupState() } + // A status read must never throw: a store that cannot be read only hides the refusal note. + // The count names its own sensor, and a Connect to another sensor clears it, so the stored + // session does not have to be read here. + val locked = try { + val refusedMac = refusalLedger.load().address + refusedMac != null && refusedTooOften(refusedMac) + } catch (_: Throwable) { + false + } + if (locked) { + return OnePlusWarmupState( + phase = OnePlusWarmupState.Phase.FAILED, + message = OnePlusAuthRefusalPolicy.MESSAGE_LOCKED, + ) + } + return OnePlusWarmupState(phase = OnePlusWarmupState.Phase.IDLE) + } override fun isSessionUp(): Boolean = session?.isUp() == true @@ -662,6 +724,8 @@ class OnePlusCgmDriverReal(storeNamespace: String? = null) : OnePlusCgmDriver { onCalibrationState = { state, matchesSent -> onCalibrationState(state, matchesSent) }, calibrationSendCheck = { glucoseMgdl, bloodAtMs, nowMs -> calibrationSendCheck(glucoseMgdl, bloodAtMs, nowMs) }, onCalibrationNotSent = { reason -> onCalibrationNotSent(reason) }, + refusalLedger = refusalLedger, + refusalPolicy = refusalPolicy, ) return created } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingApps.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingApps.kt new file mode 100644 index 000000000000..e4c96cf1d5a1 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingApps.kt @@ -0,0 +1,66 @@ +package app.aaps.plugins.dexcomoneplus + +/** + * One app that connects to a Dexcom G7 / ONE+ itself. + * + * @property label the app's own product name. A name, not a sentence, so it is not translated. + */ +data class OnePlusCompetingApp(val packageName: String, val label: String) + +/** + * Answers "is this app installed?". Android asks its `PackageManager`. + * + * A host that cannot list the other apps on the phone has no instance of this at all, and the + * warning is absent there. It must never be an instance that always says "not installed", because + * that reads as "none found". + */ +fun interface OnePlusInstalledApps { + + fun isInstalled(packageName: String): Boolean +} + +/** + * The apps that fight with us for the sensor. + * + * A sensor talks to one phone app at a time. When the Dexcom app, xDrip+ or Juggluco is on the phone + * as well, it may take the sensor's phone slot, and then the sensor refuses us. The user should know + * before they start, so the start screen lists the ones that are installed, and the list is logged. + * + * The package names are the ones nightscout/AndroidAPS PR 5397 checks (`G7PairingViewModel`). + */ +object OnePlusCompetingApps { + + val KNOWN: List = listOf( + OnePlusCompetingApp("com.dexcom.g7", "Dexcom G7"), + OnePlusCompetingApp("com.dexcom.dexcomone", "Dexcom ONE"), + OnePlusCompetingApp("com.dexcom.one", "Dexcom ONE+"), + OnePlusCompetingApp("com.dexcom.stelo", "Dexcom Stelo"), + OnePlusCompetingApp("com.eveningoutpost.dexdrip", "xDrip+"), + OnePlusCompetingApp("tk.glucodata", "Juggluco"), + ) + + /** + * The known apps that are installed, in the order of [KNOWN], and one log line about them. + * + * A lookup that fails counts as "not installed" for that app only: one broken answer must not + * hide the others. + */ + fun installed(apps: OnePlusInstalledApps): List { + val found = KNOWN.filter { app -> + try { + apps.isInstalled(app.packageName) + } catch (_: Throwable) { + false + } + } + if (found.isEmpty()) { + OnePlusLog.i("${OnePlusLogMarkers.SCAN}: no other app that uses the sensor is installed") + } else { + OnePlusLog.w( + "${OnePlusLogMarkers.SCAN}: other apps that use the sensor are installed: " + + found.joinToString { it.packageName } + " (a sensor talks to one phone app at a time)", + ) + } + return found + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt index 958decc85ac6..8c2b31be4a1a 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvCandidate.kt @@ -122,29 +122,36 @@ object OnePlusAdvCandidate { * * Every part is a boost, never a filter — see the note on this object. Feed it the session from * [scanHintFor], not the raw store, or a new sensor is ranked with the old sensor's fingerprint. + * + * A sensor whose phone slot another phone holds ([phoneSlotHeld], from [OnePlusAdvSlot]) goes + * below the free ones, because it will refuse us and refusals in a row lock a sensor. The + * penalty is larger than any signal difference and smaller than the serial hint. It never + * applies to the stored sensor (sticky name or MAC match): the phone holding that slot is + * normally this one. */ fun rankScore( name: String?, address: String?, rssi: Int, session: OnePlusStoredSession?, + phoneSlotHeld: Boolean? = null, ): Int { var score = rssi - if (!session?.lastDeviceName.isNullOrBlank() && + val nameSticky = !session?.lastDeviceName.isNullOrBlank() && name.equals(session?.lastDeviceName, ignoreCase = true) - ) { - score += 10_000 - } - if (!session?.lastMac.isNullOrBlank() && + val macSticky = !session?.lastMac.isNullOrBlank() && address.equals(session?.lastMac, ignoreCase = true) - ) { - score += 5_000 - } + if (nameSticky) score += 10_000 + if (macSticky) score += 5_000 val serial = session?.identity?.serial if (!serial.isNullOrBlank() && name?.contains(serial, ignoreCase = true) == true) { score += 1_000 } if (isG7FamilyName(name)) score += 100 + if (phoneSlotHeld == true && !nameSticky && !macSticky) score -= SLOT_HELD_PENALTY return score } + + /** What a held phone slot costs in [rankScore]. More than any RSSI gap, less than the serial hint. */ + const val SLOT_HELD_PENALTY = 500 } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlot.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlot.kt new file mode 100644 index 000000000000..1ec7d601da7e --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlot.kt @@ -0,0 +1,44 @@ +package app.aaps.plugins.dexcomoneplus.identity + +/** + * Reads the "phone slot held" bit from a G7 / ONE+ advertisement. + * + * A G7 keeps one connection slot per kind of display. Two phones cannot both hold the phone slot, + * so a sensor whose phone slot is held by another phone refuses us, and refusals in a row make it + * lock itself for a while (see `OnePlusAuthRefusals`). The advertisement says whether the slot is + * held before anyone connects, so the scan list can offer free sensors first. + * + * The manufacturer data of company 0x00D0 (Dexcom) is + * `CRC16(serial) little endian (2 bytes) | types in use (1 byte) | ...`. + * "Types in use" has one bit per display type that held a slot in the last few minutes. The phone + * is display type 2, so its bit is `1 shl (2 - 1)`. + * + * Where this comes from: the layout and the phone bit are the ones nightscout/AndroidAPS PR 5397 + * reads (`G7Advertisement`, ported there from LoopKit G7SensorKit). Only the facts are used here, + * the code is our own. + * + * Android `ScanRecord.getManufacturerSpecificData(id)` gives the bytes **without** the company id, + * which is what [phoneSlotHeld] reads. + * + * Null always means "the advertisement did not say". It is never read as free or as held. + */ +object OnePlusAdvSlot { + + /** Bluetooth SIG company id of Dexcom. */ + const val DEXCOM_COMPANY_ID: Int = 0x00D0 + + /** Bit of the phone display type in the "types in use" byte. */ + const val PHONE_SLOT_MASK: Int = 0x02 + + private const val TYPES_IN_USE_OFFSET = 2 + + /** + * @param manufacturerData the Dexcom manufacturer data **without** the company id, as Android + * gives it. Null or too short gives null. + */ + fun phoneSlotHeld(manufacturerData: ByteArray?): Boolean? { + if (manufacturerData == null || manufacturerData.size <= TYPES_IN_USE_OFFSET) return null + val typesInUse = manufacturerData[TYPES_IN_USE_OFFSET].toInt() and 0xff + return typesInUse and PHONE_SLOT_MASK != 0 + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt index a845f130728a..c192e86c8077 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStore.kt @@ -2,6 +2,7 @@ package app.aaps.plugins.dexcomoneplus.identity import app.aaps.plugins.dexcomoneplus.OnePlusLog import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusals import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi @@ -206,6 +207,30 @@ class OnePlusSensorStore(private val prefs: OnePlusSensorPrefs) { prefs.edit { clear() } } + /** Refusals in a row of this slot's sensor, see [OnePlusAuthRefusals]. Empty when none recorded. */ + fun loadAuthRefusals(): OnePlusAuthRefusals = OnePlusAuthRefusals( + address = prefs.getString(KEY_REFUSAL_MAC)?.takeIf { it.isNotBlank() }, + count = prefs.getInt(KEY_REFUSAL_COUNT, 0), + lastAtMs = prefs.getLong(KEY_REFUSAL_AT, 0L), + lastWithSavedKey = prefs.getBoolean(KEY_REFUSAL_SAVED_KEY, false), + ) + + fun saveAuthRefusals(refusals: OnePlusAuthRefusals) { + prefs.edit { + if (refusals.count <= 0) { + remove(KEY_REFUSAL_MAC) + remove(KEY_REFUSAL_COUNT) + remove(KEY_REFUSAL_AT) + remove(KEY_REFUSAL_SAVED_KEY) + } else { + putString(KEY_REFUSAL_MAC, refusals.address) + putInt(KEY_REFUSAL_COUNT, refusals.count) + putLong(KEY_REFUSAL_AT, refusals.lastAtMs) + putBoolean(KEY_REFUSAL_SAVED_KEY, refusals.lastWithSavedKey) + } + } + } + /** * Adopt another sensor's stored session into this store — used on staging→production promotion so * the production driver durably resumes the promoted sensor after a restart. Copies identity / MAC @@ -296,5 +321,9 @@ class OnePlusSensorStore(private val prefs: OnePlusSensorPrefs) { private const val KEY_SLOT_PRESENT = "slot_present" private const val KEY_SLOT_EGV_COUNT = "slot_valid_egv_count" private const val KEY_SLOT_WARMUP_DONE = "slot_warmup_done" + private const val KEY_REFUSAL_MAC = "auth_refusal_mac" + private const val KEY_REFUSAL_COUNT = "auth_refusal_count" + private const val KEY_REFUSAL_AT = "auth_refusal_at_ms" + private const val KEY_REFUSAL_SAVED_KEY = "auth_refusal_saved_key" } } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt index 6a55062f4264..f15cf0cd732d 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/scan/OnePlusScanResult.kt @@ -4,11 +4,16 @@ import kotlin.concurrent.Volatile /** * LE advertisement hit for ONE+ / G7-family transmitters. + * + * @property phoneSlotHeld whether the advertisement says another phone holds the sensor's phone + * slot, or null when it did not say. See [app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvSlot]. + * Part of `equals` on purpose: a slot that became free must reach the list as a change. */ data class OnePlusScanResult( val address: String, val name: String?, val rssi: Int, + val phoneSlotHeld: Boolean? = null, ) { /** * The platform's monotonic clock in milliseconds when this ADV was last seen, for UI→driver diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusals.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusals.kt new file mode 100644 index 000000000000..1bd983bade01 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusals.kt @@ -0,0 +1,128 @@ +package app.aaps.plugins.dexcomoneplus.session + +/** + * How often a sensor has refused our authentication in a row, kept per sensor slot. + * + * A G7 / ONE+ locks itself for a while after repeated failed authentications: four refusals in a + * row lock the sensor (this is what nightscout/AndroidAPS PR 5397 and LoopKit G7SensorKit work + * around). A locked sensor sends no readings to anyone, so the loop loses its glucose. Our session + * loop retries on its own, and the plugin watchdog starts a new session when one ends, so without a + * count that survives both, a wrong code or a slot held by another phone could be tried until the + * sensor locks. + * + * Saved in the slot's private store, so an app restart does not start the count again. + * + * @property address the sensor the refusals came from. A count for another sensor is not this + * sensor's count. + * @property count refusals in a row since the last successful authentication. + * @property lastAtMs wall clock of the last refusal, 0 when none. + * @property lastWithSavedKey the last refusal was of a saved shared key (short auth), which is + * fixed without the user by running the full pairing once. + */ +data class OnePlusAuthRefusals( + val address: String? = null, + val count: Int = 0, + val lastAtMs: Long = 0L, + val lastWithSavedKey: Boolean = false, +) + +/** Where [OnePlusAuthRefusals] lives between sessions. The driver backs it with the slot store. */ +interface OnePlusAuthRefusalLedger { + + fun load(): OnePlusAuthRefusals + + fun save(refusals: OnePlusAuthRefusals) +} + +/** Keeps nothing. For tests and for sessions built without a store. */ +class OnePlusAuthRefusalLedgerInMemory(private var value: OnePlusAuthRefusals = OnePlusAuthRefusals()) : OnePlusAuthRefusalLedger { + + override fun load(): OnePlusAuthRefusals = value + + override fun save(refusals: OnePlusAuthRefusals) { + value = refusals + } +} + +/** + * The rule: never let the sensor reach the refusal that locks it. + * + * - After a refusal we wait [pauseMs] before we ask that sensor again. The one exception is a + * refused saved key: the next try is the full pairing with the code, which is what fixes it, so + * it may go at once. + * - After [MAX_REFUSALS_IN_A_ROW] refusals in a row we stop. That is one below the four that lock + * the sensor. Only the user can start again, from the start screen. + * - A successful authentication clears the count. + * + * Only refusals count. A dropped link, a timeout or a missing advertisement is not a refusal and + * keeps the normal retry policy. + */ +class OnePlusAuthRefusalPolicy( + private val pauseMs: Long = REFUSAL_PAUSE_MS, +) { + + sealed class Decision { + + /** The sensor may be asked now. */ + data object Allowed : Decision() + + /** The sensor refused us recently. Do not ask before [untilMs] (wall clock). */ + data class Wait(val untilMs: Long) : Decision() + + /** The sensor refused us too often. Do not ask again until the user starts it again. */ + data object Locked : Decision() + } + + fun decide(refusals: OnePlusAuthRefusals, address: String, nowMs: Long): Decision { + if (!isSameSensor(refusals, address) || refusals.count <= 0) return Decision.Allowed + if (refusals.count >= MAX_REFUSALS_IN_A_ROW) return Decision.Locked + if (refusals.lastWithSavedKey) return Decision.Allowed + val untilMs = refusals.lastAtMs + pauseMs + return if (nowMs >= untilMs) Decision.Allowed else Decision.Wait(untilMs) + } + + /** One more refusal from [address]. A refusal from another sensor starts its own count. */ + fun afterRefusal(refusals: OnePlusAuthRefusals, address: String, nowMs: Long, withSavedKey: Boolean): OnePlusAuthRefusals { + val previous = if (isSameSensor(refusals, address)) refusals.count else 0 + return OnePlusAuthRefusals( + address = address.uppercase(), + count = previous + 1, + lastAtMs = nowMs, + lastWithSavedKey = withSavedKey, + ) + } + + /** The sensor took our key: the count is over. */ + fun afterSuccess(): OnePlusAuthRefusals = OnePlusAuthRefusals() + + /** + * The user pressed Connect on the start screen. + * + * Another sensor or another code is a fresh start: the refusals were about the old pair. The same + * sensor with the same code gets one more try and no more, so the next refusal stops us again. + * The pause still applies to that try: pressing Connect again and again must not turn into + * refusals in a row, so even the user gets at most one try per pause. + */ + fun afterUserStart(refusals: OnePlusAuthRefusals, address: String, codeChanged: Boolean): OnePlusAuthRefusals { + if (codeChanged || !isSameSensor(refusals, address) || refusals.count <= 0) return OnePlusAuthRefusals() + return refusals.copy(count = refusals.count.coerceAtMost(MAX_REFUSALS_IN_A_ROW - 1)) + } + + private fun isSameSensor(refusals: OnePlusAuthRefusals, address: String): Boolean = + refusals.address != null && refusals.address.equals(address, ignoreCase = true) + + companion object { + + /** One below the four refusals in a row that lock a G7 / ONE+. */ + const val MAX_REFUSALS_IN_A_ROW = 3 + + /** The pause after a refusal. The same 15 minutes PR 5397 uses. */ + const val REFUSAL_PAUSE_MS = 15L * 60L * 1000L + + /** Warm-up message while we wait after a refusal. Mapped to plain text by the screens. */ + const val MESSAGE_PAUSED = "ONEPLUS_REFUSED_PAUSE" + + /** Warm-up message once we stopped. Mapped to plain text by the screens. */ + const val MESSAGE_LOCKED = "ONEPLUS_REFUSED_STOP" + } +} diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt index f7a432a12dd7..14d858eb6f24 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSession.kt @@ -93,23 +93,45 @@ class OnePlusBackfillSession( val stream = OnePlusBackFillStream() val deadline = Clock.System.now().toEpochMilliseconds() + COLLECT_TIMEOUT_MS var lastPacketMs = 0L - while (shouldContinue() && gatt.isConnected() && Clock.System.now().toEpochMilliseconds() < deadline) { - val wait = if (stream.hasData()) QUIET_TIMEOUT_MS else 1_000L - val packet = gatt.awaitBackfillNotify(wait) - if (!shouldContinue()) break - if (packet == null) { - if (stream.hasData() && lastPacketMs > 0L && + // What went wrong while collecting, if anything. Thrown again only after the records already + // received are delivered: a failure must not throw away readings we have in hand. + var collectFailure: Throwable? = null + try { + while (shouldContinue() && gatt.isConnected() && Clock.System.now().toEpochMilliseconds() < deadline) { + val wait = if (stream.hasData()) QUIET_TIMEOUT_MS else 1_000L + val packet = gatt.awaitBackfillNotify(wait) + // Kept before the stop check: a packet that arrived just as the link dropped is a + // real record, and it used to be thrown away here. + if (packet != null) { + stream.pushG7(packet) + lastPacketMs = Clock.System.now().toEpochMilliseconds() + OnePlusLog.d( + "${OnePlusLogMarkers.SESSION}: backfill chunk ${packet.size}b total=${stream.byteCount()}", + ) + } + if (!shouldContinue()) break + if (packet == null && + stream.hasData() && lastPacketMs > 0L && Clock.System.now().toEpochMilliseconds() - lastPacketMs >= QUIET_TIMEOUT_MS ) { break } - continue } - stream.pushG7(packet) - lastPacketMs = Clock.System.now().toEpochMilliseconds() - OnePlusLog.d( - "${OnePlusLogMarkers.SESSION}: backfill chunk ${packet.size}b total=${stream.byteCount()}", - ) + } catch (t: Throwable) { + collectFailure = t + } + // The link dropped in the middle of the backfill. The sensor does not always get to the end + // of it, but every packet that arrived before the drop is already in the client's queue, in + // front of its disconnect marker. Take those too, so they are stored now and not only at + // the next connection. PR 5397 flushes its backfill buffer on disconnect for the same reason. + if (!gatt.isConnected()) { + val drained = drainAfterLinkDrop(stream) + if (drained > 0) { + OnePlusLog.i( + "${OnePlusLogMarkers.SESSION}: backfill link dropped, kept $drained queued packet(s), " + + "total=${stream.byteCount()}b", + ) + } } val nowMs = Clock.System.now().toEpochMilliseconds() @@ -123,14 +145,41 @@ class OnePlusBackfillSession( OnePlusLog.i( "${OnePlusLogMarkers.SESSION}: backfill done samples=${samples.size} bytes=${stream.byteCount()}", ) + collectFailure?.let { throw it } return samples.size } + /** + * Reads what is still queued after the link dropped, without waiting for anything new: the + * queue ends with the client's disconnect marker, which reads as null. + * + * @return the number of packets taken. + */ + private fun drainAfterLinkDrop(stream: OnePlusBackFillStream): Int { + var taken = 0 + while (taken < MAX_DRAIN_PACKETS) { + val packet = try { + gatt.awaitBackfillNotify(DRAIN_POLL_MS) + } catch (_: Throwable) { + null + } ?: break + stream.pushG7(packet) + taken++ + } + return taken + } + companion object { const val CCCD_SETTLE_MS: Long = 200L const val ACK_TIMEOUT_MS: Long = 5_000L const val COLLECT_TIMEOUT_MS: Long = 15_000L const val QUIET_TIMEOUT_MS: Long = 3_000L + + /** The drain after a link drop only reads what is queued, so it waits next to nothing. */ + const val DRAIN_POLL_MS: Long = 1L + + /** The GATT client queues at most 64 backfill packets, so this is never the limit in practice. */ + const val MAX_DRAIN_PACKETS: Int = 64 /** Short window (Ob1 G5 default 3 h; G7 allows 24 h). */ const val DEFAULT_LOOKBACK_MS: Long = 3L * 60L * 60L * 1000L } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt index 13bd4d10e564..8163160717be 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSession.kt @@ -340,6 +340,12 @@ class OnePlusBleSessionSkeleton( }, /** A waiting value was dropped before any write, and why. */ private val onCalibrationNotSent: (OnePlusCalibrationOutcome.NotSent.Reason) -> Unit = {}, + /** + * Where the refusals in a row of this slot's sensor are kept. The driver backs it with the slot + * store, so the count outlives this session and an app restart. See [OnePlusAuthRefusals]. + */ + private val refusalLedger: OnePlusAuthRefusalLedger = OnePlusAuthRefusalLedgerInMemory(), + private val refusalPolicy: OnePlusAuthRefusalPolicy = OnePlusAuthRefusalPolicy(), ) : OnePlusBleSession { @Volatile @@ -611,7 +617,33 @@ class OnePlusBleSessionSkeleton( if (attempt == 0) OnePlusWarmupState.Phase.CONNECTING else OnePlusWarmupState.Phase.RECONNECTING setWarmup(OnePlusWarmupState(phase = connectingPhase, message = "connect_attempt_$attempt")) - val prep = preparedConnect ?: try { + // Before anything else, even the scan: a sensor that refused us must not be asked again too + // soon, nor at all once it refused enough times to lock itself. Normal link losses never + // reach this, they are not refusals. + var usablePrep = preparedConnect + when (val decision = refusalPolicy.decide(refusalLedger.load(), deviceAddress, nowMs())) { + OnePlusAuthRefusalPolicy.Decision.Locked -> { + failRefusedTooOften(refusalLedger.load().count) + return CycleOutcome.Fatal + } + + is OnePlusAuthRefusalPolicy.Decision.Wait -> { + val waitMs = decision.untilMs - nowMs() + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] the sensor refused us " + + "${refusalLedger.load().count} time(s) in a row, waiting ${waitMs / 1000}s before asking again " + + "(${OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW + 1} in a row lock it)", + ) + enterReconnecting(OnePlusAuthRefusalPolicy.MESSAGE_PAUSED) + if (!sleepWhileRunning(waitMs)) return CycleOutcome.Stopped + // A sighting from before the pause is long out of date. + usablePrep = null + } + + OnePlusAuthRefusalPolicy.Decision.Allowed -> Unit + } + + val prep = usablePrep ?: try { beforeConnect(deviceAddress, attempt, null) } catch (t: Throwable) { val msg = t.message ?: "ONEPLUS_BEFORE_CONNECT_FAILED" @@ -691,6 +723,9 @@ class OnePlusBleSessionSkeleton( } catch (_: Throwable) { } } + if (authResult.refusedBySensor && recordRefusal(deviceAddress, authResult.refusedSavedKey)) { + return CycleOutcome.Fatal + } onError(msg, false) // Retryable: the loop will re-attempt (short-auth reject wipes the key → full J-PAKE // next). Show RECONNECTING, NOT FAILED — the old FAILED flash made the user abandon @@ -699,6 +734,10 @@ class OnePlusBleSessionSkeleton( return if (running) CycleOutcome.RetryableFailure else CycleOutcome.Stopped } + if (refusalLedger.load().count > 0) { + OnePlusLog.i("${OnePlusLogMarkers.SESSION}: [$slot] the sensor accepted us, refusal count cleared") + refusalLedger.save(refusalPolicy.afterSuccess()) + } authResult.sharedKey?.let { key -> try { onAuthSuccess(deviceAddress, key) @@ -984,6 +1023,35 @@ class OnePlusBleSessionSkeleton( return null } + /** + * Counts one refusal from [deviceAddress]. + * + * @return true when that was the last refusal we allow: the session has then failed for good and + * the caller must stop. + */ + private fun recordRefusal(deviceAddress: String, withSavedKey: Boolean): Boolean { + val updated = refusalPolicy.afterRefusal(refusalLedger.load(), deviceAddress, nowMs(), withSavedKey) + refusalLedger.save(updated) + OnePlusLog.w( + "${OnePlusLogMarkers.SESSION}: [$slot] the sensor refused authentication " + + "${updated.count} time(s) in a row savedKey=$withSavedKey", + ) + if (refusalPolicy.decide(updated, deviceAddress, nowMs()) != OnePlusAuthRefusalPolicy.Decision.Locked) return false + failRefusedTooOften(updated.count) + return true + } + + /** Stops for good, before the refusal that would lock the sensor. Only the user starts again. */ + private fun failRefusedTooOften(count: Int) { + fail( + "${OnePlusAuthRefusalPolicy.MESSAGE_LOCKED}: the sensor refused us $count times in a row, " + + "stopped before it locks itself; check the code, close other apps that use the sensor, then start it again", + fatal = false, + ) + } + + private fun nowMs(): Long = Clock.System.now().toEpochMilliseconds() + private fun fail(message: String, fatal: Boolean) { running = false up = false diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt index 74b1765424df..de5168dcb8d3 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuth.kt @@ -27,6 +27,14 @@ data class AuthResult( * (short-auth rejected / bond failure / missing certs). */ val invalidateSharedKey: Boolean = false, + /** + * The sensor itself said no: its AuthStatus was not "authenticated", or its challenge did not + * match ours (wrong code or stale key). Counted by [OnePlusAuthRefusalPolicy], because refusals + * in a row lock a sensor. A lost link, a timeout or a bond problem is not a refusal. + */ + val refusedBySensor: Boolean = false, + /** The refused attempt used a saved shared key (short auth), not the full pairing with the code. */ + val refusedSavedKey: Boolean = false, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -34,7 +42,9 @@ data class AuthResult( return ok == other.ok && message == other.message && sharedKey.contentEquals(other.sharedKey) && - invalidateSharedKey == other.invalidateSharedKey + invalidateSharedKey == other.invalidateSharedKey && + refusedBySensor == other.refusedBySensor && + refusedSavedKey == other.refusedSavedKey } override fun hashCode(): Int { @@ -42,6 +52,8 @@ data class AuthResult( result = 31 * result + (message?.hashCode() ?: 0) result = 31 * result + (sharedKey?.contentHashCode() ?: 0) result = 31 * result + invalidateSharedKey.hashCode() + result = 31 * result + refusedBySensor.hashCode() + result = 31 * result + refusedSavedKey.hashCode() return result } } diff --git a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt index 021ee780baca..fc0f60b42b0b 100644 --- a/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt +++ b/plugins/dexcom_oneplus/src/commonMain/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusSessionAuthKeks.kt @@ -131,8 +131,16 @@ class OnePlusSessionAuthKeks( OnePlusKeksNotifySource.EXTRA_DATA -> plugin.receivedData(notify.payload) } } catch (se: KeksSecurityException) { + // libkeks throws this only for "Mismatch": the sensor's answer to our challenge does + // not match our key, so the code (or the saved key) is not this sensor's. That is a + // refusal for the lockout count. return finalizeAuthResult( - AuthResult(ok = false, message = "ONEPLUS_AUTH: ${se.message}"), + AuthResult( + ok = false, + message = "ONEPLUS_AUTH: ${se.message}", + refusedBySensor = true, + refusedSavedKey = usedShortAuthPreload, + ), plugin, ) } catch (ipe: KeksInvalidParameterException) { @@ -284,6 +292,8 @@ class OnePlusSessionAuthKeks( "ONEPLUS_AUTH: KEKS AuthStatus rejected auth=${status.authenticated}" }, invalidateSharedKey = true, + refusedBySensor = true, + refusedSavedKey = viaShort, ) } diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt index c20b9b77038f..0548368d1c44 100644 --- a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCgmDriverRealSharedTest.kt @@ -8,6 +8,8 @@ import app.aaps.plugins.dexcomoneplus.identity.OnePlusStoredSession import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusalPolicy +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusals import app.aaps.plugins.dexcomoneplus.session.OnePlusCpuLease import kotlin.test.Test import kotlin.test.assertEquals @@ -109,6 +111,31 @@ class OnePlusCgmDriverRealSharedTest { driver.shutdown() } + @Test + fun `a sensor that refused us too often is not resumed and says why`() { + val platform = FakePlatform() + val driver = OnePlusCgmDriverReal() + driver.attach(platform) + val store = assertNotNull(driver.sensorStore()) + // A session that would resume: code, MAC and key are all there. + store.saveIdentity(OnePlusSensorIdentity(pin = "1234")) + store.saveLastMac("AA:BB:CC:DD:EE:FF") + store.saveSharedKey(ByteArray(16) { it.toByte() }) + store.saveAuthRefusals( + OnePlusAuthRefusals( + address = "AA:BB:CC:DD:EE:FF", + count = OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW, + lastAtMs = nowMs(), + ), + ) + // No GATT client is asked for: the fake platform would throw if it were. + assertFalse(driver.resumeStoredSession()) + val state = driver.warmupState() + assertEquals(OnePlusWarmupState.Phase.FAILED, state.phase) + assertEquals(OnePlusAuthRefusalPolicy.MESSAGE_LOCKED, state.message) + driver.shutdown() + } + @Test fun `scan start and stop reach the scanner`() { val platform = FakePlatform() diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingAppsTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingAppsTest.kt new file mode 100644 index 000000000000..a4625706f507 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/OnePlusCompetingAppsTest.kt @@ -0,0 +1,39 @@ +package app.aaps.plugins.dexcomoneplus + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Which installed apps the start screen warns about. */ +class OnePlusCompetingAppsTest { + + @Test + fun `the Dexcom apps and xDrip and Juggluco are known`() { + val packages = OnePlusCompetingApps.KNOWN.map { it.packageName } + assertTrue("com.dexcom.g7" in packages) + assertTrue("com.dexcom.one" in packages) + assertTrue("com.eveningoutpost.dexdrip" in packages) + assertTrue("tk.glucodata" in packages) + } + + @Test + fun `only the installed ones are listed and in the known order`() { + val installed = setOf("tk.glucodata", "com.dexcom.g7") + val found = OnePlusCompetingApps.installed { it in installed } + assertEquals(listOf("Dexcom G7", "Juggluco"), found.map { it.label }) + } + + @Test + fun `nothing installed lists nothing`() { + assertEquals(emptyList(), OnePlusCompetingApps.installed { false }) + } + + @Test + fun `one failing lookup does not hide the others`() { + val found = OnePlusCompetingApps.installed { name -> + if (name == "com.dexcom.g7") error("lookup failed") + name == "com.eveningoutpost.dexdrip" + } + assertEquals(listOf("xDrip+"), found.map { it.label }) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlotTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlotTest.kt new file mode 100644 index 000000000000..c994b3e4187d --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusAdvSlotTest.kt @@ -0,0 +1,74 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The "phone slot held" bit of the advertisement, and what it does to the scan order. + */ +class OnePlusAdvSlotTest { + + /** CRC (2 bytes) | types in use | 0x04, as Android gives it (no company id). */ + private fun android(typesInUse: Int) = byteArrayOf(0x34, 0x12, typesInUse.toByte(), 0x04) + + @Test + fun `the phone bit set means the slot is held`() { + assertEquals(true, OnePlusAdvSlot.phoneSlotHeld(android(0x02))) + assertEquals(true, OnePlusAdvSlot.phoneSlotHeld(android(0x03))) + } + + @Test + fun `other display types do not hold the phone slot`() { + assertEquals(false, OnePlusAdvSlot.phoneSlotHeld(android(0x00))) + // Watch (type 3) and medical (type 1) have their own slots. + assertEquals(false, OnePlusAdvSlot.phoneSlotHeld(android(0x04))) + assertEquals(false, OnePlusAdvSlot.phoneSlotHeld(android(0x01))) + } + + @Test + fun `missing or short data says nothing`() { + assertNull(OnePlusAdvSlot.phoneSlotHeld(null)) + assertNull(OnePlusAdvSlot.phoneSlotHeld(byteArrayOf(0x34, 0x12))) + } + + @Test + fun `a free sensor ranks above a held one even with a weaker signal`() { + val free = OnePlusAdvCandidate.rankScore("DX02aa", "11:11:11:11:11:11", -95, null, phoneSlotHeld = false) + val held = OnePlusAdvCandidate.rankScore("DX02bb", "22:22:22:22:22:22", -35, null, phoneSlotHeld = true) + assertTrue(free > held) + } + + @Test + fun `an unknown slot ranks like a free one`() { + val unknown = OnePlusAdvCandidate.rankScore("DX02aa", "11:11:11:11:11:11", -60, null, phoneSlotHeld = null) + val free = OnePlusAdvCandidate.rankScore("DX02aa", "11:11:11:11:11:11", -60, null, phoneSlotHeld = false) + assertEquals(free, unknown) + } + + @Test + fun `the stored sensor keeps its place when its slot is held`() { + // Our own phone holds the slot of the sensor we already use. + val stored = OnePlusStoredSession( + identity = OnePlusSensorIdentity(pin = "1234"), + lastMac = "AA:AA:AA:AA:AA:AA", + lastDeviceName = "DX02st", + ) + val sticky = OnePlusAdvCandidate.rankScore("DX02st", "AA:AA:AA:AA:AA:AA", -90, stored, phoneSlotHeld = true) + val otherFree = OnePlusAdvCandidate.rankScore("DX02zz", "BB:BB:BB:BB:BB:BB", -40, stored, phoneSlotHeld = false) + assertTrue(sticky > otherFree) + val stickyFree = OnePlusAdvCandidate.rankScore("DX02st", "AA:AA:AA:AA:AA:AA", -90, stored, phoneSlotHeld = false) + assertEquals(stickyFree, sticky) + } + + @Test + fun `the serial hint still wins over a held slot`() { + val hint = OnePlusStoredSession(identity = OnePlusSensorIdentity(pin = "1234", serial = "ab12")) + val serialHeld = OnePlusAdvCandidate.rankScore("DX02ab12", "11:11:11:11:11:11", -90, hint, phoneSlotHeld = true) + val plainFree = OnePlusAdvCandidate.rankScore("DX02zz", "22:22:22:22:22:22", -40, hint, phoneSlotHeld = false) + assertTrue(serialHeld > plainFree) + assertFalse(OnePlusAdvCandidate.SLOT_HELD_PENALTY >= 1_000) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreRefusalsTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreRefusalsTest.kt new file mode 100644 index 000000000000..b785358ea64c --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/identity/OnePlusSensorStoreRefusalsTest.kt @@ -0,0 +1,67 @@ +package app.aaps.plugins.dexcomoneplus.identity + +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusals +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The refusal count is kept in the slot store, so it outlives a session and an app restart. */ +class OnePlusSensorStoreRefusalsTest { + + private class MemoryPrefs : OnePlusSensorPrefs { + val values = mutableMapOf() + override fun getString(key: String): String? = values[key] as? String + override fun getLong(key: String, defaultValue: Long): Long = values[key] as? Long ?: defaultValue + override fun getInt(key: String, defaultValue: Int): Int = values[key] as? Int ?: defaultValue + override fun getBoolean(key: String, defaultValue: Boolean): Boolean = values[key] as? Boolean ?: defaultValue + override fun contains(key: String): Boolean = values.containsKey(key) + override fun edit(block: OnePlusSensorPrefs.Editor.() -> Unit) { + object : OnePlusSensorPrefs.Editor { + override fun putString(key: String, value: String?) { + values[key] = value + } + + override fun putLong(key: String, value: Long) { + values[key] = value + } + + override fun putInt(key: String, value: Int) { + values[key] = value + } + + override fun putBoolean(key: String, value: Boolean) { + values[key] = value + } + + override fun remove(key: String) { + values.remove(key) + } + + override fun clear() { + values.clear() + } + }.block() + } + } + + @Test + fun `nothing stored reads as no refusals`() { + assertEquals(OnePlusAuthRefusals(), OnePlusSensorStore(MemoryPrefs()).loadAuthRefusals()) + } + + @Test + fun `a saved count reads back in a new store on the same file`() { + val prefs = MemoryPrefs() + val saved = OnePlusAuthRefusals(address = "AA:BB:CC:DD:EE:FF", count = 2, lastAtMs = 123L, lastWithSavedKey = true) + OnePlusSensorStore(prefs).saveAuthRefusals(saved) + assertEquals(saved, OnePlusSensorStore(prefs).loadAuthRefusals()) + } + + @Test + fun `a cleared count leaves no keys behind`() { + val prefs = MemoryPrefs() + val store = OnePlusSensorStore(prefs) + store.saveAuthRefusals(OnePlusAuthRefusals(address = "AA:BB:CC:DD:EE:FF", count = 3, lastAtMs = 1L)) + store.saveAuthRefusals(OnePlusAuthRefusals()) + assertEquals(emptyMap(), prefs.values) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/FakeOnePlusGatt.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/FakeOnePlusGatt.kt new file mode 100644 index 000000000000..e0c312a39508 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/FakeOnePlusGatt.kt @@ -0,0 +1,69 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusGattClient +import app.aaps.plugins.dexcomoneplus.gatt.OnePlusKeksNotify + +/** + * A GATT client with no radio behind it, for the session rules. + * + * [backfillPackets] is the client's backfill queue: what the sensor already sent and the session + * has not read yet. [dropLinkAfterBackfillReads] makes the link go down after that many reads, the + * way a real link drops in the middle of a backfill, with the rest still queued. + */ +internal class FakeOnePlusGatt( + val backfillPackets: ArrayDeque = ArrayDeque(), + private val dropLinkAfterBackfillReads: Int = Int.MAX_VALUE, +) : OnePlusGattClient { + + var connected = false + var connects = 0 + private set + private var backfillReads = 0 + val controlWrites = mutableListOf() + + override fun connect(deviceAddress: String, autoConnect: Boolean) { + connects++ + connected = true + } + + override fun disconnect() { + connected = false + } + + override fun isConnected(): Boolean = connected + + override fun writeAuthentication(payload: ByteArray?) = Unit + + override fun writeExtraData(payload: ByteArray?) = Unit + + override fun writeControl(payload: ByteArray?) { + payload?.let { controlWrites.add(it) } + } + + override fun enableControlNotifications() = Unit + + override fun enableControlIndications() = Unit + + override fun enableBackfillNotifications() = Unit + + override fun isBonded(): Boolean = true + + override fun createBond(): Boolean = true + + override fun removeBond(): Boolean = true + + override fun awaitBondComplete(timeoutMs: Long): Boolean = true + + override fun awaitKeksNotify(timeoutMs: Long): OnePlusKeksNotify? = null + + override fun awaitNotify(timeoutMs: Long): ByteArray? = null + + override fun awaitControlNotify(timeoutMs: Long): ByteArray? = null + + override fun awaitBackfillNotify(timeoutMs: Long): ByteArray? { + val packet = backfillPackets.removeFirstOrNull() + backfillReads++ + if (backfillReads >= dropLinkAfterBackfillReads) connected = false + return packet + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusalPolicyTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusalPolicyTest.kt new file mode 100644 index 000000000000..d9889b9d5d21 --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusAuthRefusalPolicyTest.kt @@ -0,0 +1,99 @@ +package app.aaps.plugins.dexcomoneplus.session + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * The rule that keeps a G7 / ONE+ from locking itself: four refusals in a row lock it, so we stop at + * three and wait between them. + */ +class OnePlusAuthRefusalPolicyTest { + + private val pause = 15L * 60L * 1000L + private val policy = OnePlusAuthRefusalPolicy(pauseMs = pause) + private val mac = "AA:BB:CC:DD:EE:FF" + private val t0 = 1_000_000_000L + + private fun refusedTimes(times: Int, savedKey: Boolean = false): OnePlusAuthRefusals { + var state = OnePlusAuthRefusals() + repeat(times) { i -> state = policy.afterRefusal(state, mac, t0 + i * pause, savedKey) } + return state + } + + @Test + fun `a sensor that never refused us may be asked`() { + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(OnePlusAuthRefusals(), mac, t0)) + } + + @Test + fun `after a refusal we wait the pause before asking again`() { + val state = policy.afterRefusal(OnePlusAuthRefusals(), mac, t0, withSavedKey = false) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Wait(t0 + pause), policy.decide(state, mac, t0 + 1_000L)) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(state, mac, t0 + pause)) + } + + @Test + fun `a refused saved key may go to the full pairing at once`() { + val state = policy.afterRefusal(OnePlusAuthRefusals(), mac, t0, withSavedKey = true) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(state, mac, t0 + 1L)) + } + + @Test + fun `we stop one refusal before the one that locks the sensor`() { + assertEquals(3, OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW) + val two = refusedTimes(2) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(two, mac, t0 + 10 * pause)) + val three = refusedTimes(3) + // However long we wait, three in a row is the end until the user starts again. + assertEquals(OnePlusAuthRefusalPolicy.Decision.Locked, policy.decide(three, mac, t0 + 1_000 * pause)) + } + + @Test + fun `a saved key refusal still counts toward the stop`() { + assertEquals(OnePlusAuthRefusalPolicy.Decision.Locked, policy.decide(refusedTimes(3, savedKey = true), mac, t0)) + } + + @Test + fun `a success clears the count`() { + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(policy.afterSuccess(), mac, t0)) + } + + @Test + fun `refusals of another sensor do not count for this sensor`() { + val other = refusedTimes(3) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(other, "11:22:33:44:55:66", t0)) + val first = policy.afterRefusal(other, "11:22:33:44:55:66", t0, withSavedKey = false) + assertEquals(1, first.count) + } + + @Test + fun `the address is matched without case`() { + val state = refusedTimes(3) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Locked, policy.decide(state, mac.lowercase(), t0)) + } + + @Test + fun `the user starting another code begins a fresh count`() { + val after = policy.afterUserStart(refusedTimes(3), mac, codeChanged = true) + assertEquals(OnePlusAuthRefusals(), after) + } + + @Test + fun `the user starting another sensor begins a fresh count`() { + val after = policy.afterUserStart(refusedTimes(3), "11:22:33:44:55:66", codeChanged = false) + assertEquals(OnePlusAuthRefusals(), after) + } + + @Test + fun `the same code on the same sensor gets one more try and not before the pause`() { + val locked = refusedTimes(3) + val after = policy.afterUserStart(locked, mac, codeChanged = false) + assertEquals(2, after.count) + // Still the pause after the last refusal: pressing Connect again and again is not a way round it. + assertEquals(OnePlusAuthRefusalPolicy.Decision.Wait(locked.lastAtMs + pause), policy.decide(after, mac, locked.lastAtMs)) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Allowed, policy.decide(after, mac, locked.lastAtMs + pause)) + // And the next refusal stops us again. + val again = policy.afterRefusal(after, mac, locked.lastAtMs + pause, withSavedKey = false) + assertEquals(OnePlusAuthRefusalPolicy.Decision.Locked, policy.decide(again, mac, locked.lastAtMs + 100 * pause)) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSessionTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSessionTest.kt new file mode 100644 index 000000000000..2ec5d7614dbf --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBackfillSessionTest.kt @@ -0,0 +1,68 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * A backfill that loses its link half way must still store every record that already arrived. + * + * The backfill session is shared code, so these run on the JVM host. + */ +class OnePlusBackfillSessionTest { + + /** One G7 backfill record: dexTime | glucose (12 bit) | state | flags | trend, little endian. */ + private fun record(dexTime: Int, mgdl: Int): ByteArray = byteArrayOf( + (dexTime and 0xff).toByte(), + ((dexTime shr 8) and 0xff).toByte(), + ((dexTime shr 16) and 0xff).toByte(), + ((dexTime shr 24) and 0xff).toByte(), + (mgdl and 0xff).toByte(), + ((mgdl shr 8) and 0x0f).toByte(), + 0x06, // Ok + 0x00, + 0x00, + ) + + private val currentDex = 100_000 + + private fun packets() = ArrayDeque( + listOf( + record(currentDex - 900, 120), + record(currentDex - 600, 125), + record(currentDex - 300, 130), + ), + ) + + private fun run(gatt: FakeOnePlusGatt): List { + val delivered = mutableListOf() + gatt.connected = true + OnePlusBackfillSession(gatt = gatt, onGlucose = { delivered.add(it) }) + .runOnce(currentDexTimeSeconds = currentDex, shouldContinue = { gatt.isConnected() }) + return delivered + } + + @Test + fun `records still queued when the link drops are stored too`() { + // The link goes down right after the first packet is read. Two more are already queued. + val gatt = FakeOnePlusGatt(backfillPackets = packets(), dropLinkAfterBackfillReads = 1) + val delivered = run(gatt) + assertEquals(listOf(120.0, 125.0, 130.0), delivered.map { it.mgdl }) + assertEquals(0, gatt.backfillPackets.size) + } + + @Test + fun `the drop does not change the values or their spacing`() { + val gatt = FakeOnePlusGatt(backfillPackets = packets(), dropLinkAfterBackfillReads = 1) + val delivered = run(gatt) + // 5 minutes apart on the sensor clock, 5 minutes apart here. + assertEquals(300_000L, delivered[1].timestampMs - delivered[0].timestampMs) + assertEquals(300_000L, delivered[2].timestampMs - delivered[1].timestampMs) + } + + @Test + fun `a link that drops before anything arrived stores nothing`() { + val gatt = FakeOnePlusGatt(dropLinkAfterBackfillReads = 1) + assertEquals(emptyList(), run(gatt)) + } +} diff --git a/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionRefusalTest.kt b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionRefusalTest.kt new file mode 100644 index 000000000000..c914c81dfccd --- /dev/null +++ b/plugins/dexcom_oneplus/src/commonTest/kotlin/app/aaps/plugins/dexcomoneplus/session/OnePlusBleSessionRefusalTest.kt @@ -0,0 +1,87 @@ +package app.aaps.plugins.dexcomoneplus.session + +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.oem.DeviceProfileRegistry +import app.aaps.plugins.dexcomoneplus.oem.OemDeviceProfile +import app.aaps.plugins.dexcomoneplus.reconnect.OnePlusReconnectPolicy +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The session loop and the refusal count together: a sensor that refuses us is never asked a + * fourth time, while an ordinary failure keeps the retry policy it always had. + */ +class OnePlusBleSessionRefusalTest { + + private val mac = "AA:BB:CC:DD:EE:FF" + + /** No waiting between attempts, and [maxAttempts] attempts in all. */ + private class QuickRetries(private val maxAttempts: Int) : OnePlusReconnectPolicy { + override fun shouldRetry(attempt: Int, profile: OemDeviceProfile): Boolean = attempt < maxAttempts + override fun nextDelayMs(attempt: Int, profile: OemDeviceProfile): Long = 0L + } + + /** Answers every handshake with [result] and counts them. */ + private class CountingAuth(private val result: AuthResult) : OnePlusSessionAuth { + var calls = 0 + override fun authenticate(pairingCode: String, savedSharedKey: ByteArray?): AuthResult { + calls++ + return result + } + } + + private fun session( + auth: OnePlusSessionAuth, + ledger: OnePlusAuthRefusalLedger, + states: MutableList, + ) = OnePlusBleSessionSkeleton( + gatt = FakeOnePlusGatt(), + auth = auth, + reconnectPolicy = QuickRetries(maxAttempts = 10), + profile = DeviceProfileRegistry.GenericFallback, + onWarmup = { states.add(it) }, + requestNewSensorStart = true, + refusalLedger = ledger, + // No pause, so the test does not wait 15 minutes between refusals. The count is what matters. + refusalPolicy = OnePlusAuthRefusalPolicy(pauseMs = 0L), + ) + + @Test + fun `three refusals in a row stop the session before the fourth`() { + val auth = CountingAuth(AuthResult(ok = false, message = "ONEPLUS_AUTH: refused", refusedBySensor = true)) + val ledger = OnePlusAuthRefusalLedgerInMemory() + val states = mutableListOf() + session(auth, ledger, states).startWithPairingCode(mac, "1234") + + assertEquals(OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW, auth.calls) + assertEquals(3, ledger.load().count) + val last = states.last() + assertEquals(OnePlusWarmupState.Phase.FAILED, last.phase) + assertTrue(last.message.orEmpty().startsWith(OnePlusAuthRefusalPolicy.MESSAGE_LOCKED)) + } + + @Test + fun `a sensor that already refused three times is not asked at all`() { + val auth = CountingAuth(AuthResult(ok = false, refusedBySensor = true)) + val ledger = OnePlusAuthRefusalLedgerInMemory(OnePlusAuthRefusals(address = mac, count = 3, lastAtMs = 1L)) + val states = mutableListOf() + session(auth, ledger, states).startWithPairingCode(mac, "1234") + + assertEquals(0, auth.calls) + assertEquals(OnePlusWarmupState.Phase.FAILED, states.last().phase) + } + + @Test + fun `an ordinary failure is not a refusal and keeps the retry budget`() { + // A timeout: not the sensor saying no. All ten attempts are used, as before this rule. + val auth = CountingAuth(AuthResult(ok = false, message = "ONEPLUS_AUTH: notify timeout step=0")) + val ledger = OnePlusAuthRefusalLedgerInMemory() + val states = mutableListOf() + session(auth, ledger, states).startWithPairingCode(mac, "1234") + + assertEquals(10, auth.calls) + assertEquals(0, ledger.load().count) + assertTrue(states.last().message.orEmpty().startsWith("ONEPLUS_RECONNECT_EXHAUSTED")) + } +} diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt index 0be2775318db..e70cf636da47 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt @@ -14,6 +14,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverStub import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseSample import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusInstalledApps import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore @@ -262,6 +263,7 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { stores.getOrPut(namespace) { OnePlusSensorStore(MemoryPrefs()) } override val stagingNamespace: String = "staging" + override val installedApps: OnePlusInstalledApps? = null override fun productionDriver(): OnePlusCgmDriver = driver.also { driverRequests++ } override fun stagingDriver(): OnePlusCgmDriver = driver.also { driverRequests++ } override fun existingProductionDriver(): OnePlusCgmDriver? = driver.takeIf { built } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt index 8f0ce070c2d9..b1d6e619bd6c 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRulesTest.kt @@ -105,6 +105,31 @@ class DexcomOnePlusStartRulesTest { assertEquals(devices.map { it.address }.toSet(), ranked.map { it.address }.toSet()) } + @Test + fun `a free sensor is offered before one another phone holds`() { + val heldNear = OnePlusScanResult(address = "AA:AA:AA:AA:AA:AA", name = "DX02aa", rssi = -40, phoneSlotHeld = true) + val freeFar = OnePlusScanResult(address = "BB:BB:BB:BB:BB:BB", name = "DX02bb", rssi = -90, phoneSlotHeld = false) + val ranked = DexcomOnePlusStartRules.rank(listOf(heldNear, freeFar), hint = null) + assertEquals(freeFar.address, ranked.first().address) + } + + @Test + fun `the stored sensor stays first even when its slot is held`() { + val mine = OnePlusScanResult(address = "AA:AA:AA:AA:AA:AA", name = null, rssi = -90, phoneSlotHeld = true) + val other = OnePlusScanResult(address = "BB:BB:BB:BB:BB:BB", name = null, rssi = -40, phoneSlotHeld = false) + val ranked = DexcomOnePlusStartRules.rank(listOf(other, mine), stored(mac = "AA:AA:AA:AA:AA:AA")) + assertEquals(mine.address, ranked.first().address) + } + + @Test + fun `the held label is shown for another sensor and not for the stored one`() { + val held = OnePlusScanResult(address = "AA:AA:AA:AA:AA:AA", name = null, rssi = -60, phoneSlotHeld = true) + assertTrue(DexcomOnePlusStartRules.showsSlotHeld(held, storedMac = null)) + assertTrue(DexcomOnePlusStartRules.showsSlotHeld(held, storedMac = "BB:BB:BB:BB:BB:BB")) + assertFalse(DexcomOnePlusStartRules.showsSlotHeld(held, storedMac = "aa:aa:aa:aa:aa:aa")) + assertFalse(DexcomOnePlusStartRules.showsSlotHeld(held.copy(phoneSlotHeld = null), storedMac = null)) + } + // ------------ adoptsAnotherSensor(): when the screen asks before overwriting ------------ @Test diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt index 0be1906b9d9b..b5893eaff0b5 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt @@ -12,6 +12,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverStub import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusInstalledApps import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorPrefs import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore @@ -46,13 +47,13 @@ class DexcomOnePlusStartScreenTest { private fun text(name: String): String = requireNotNull(SourceStringsValues.textOf(name, null)) { "no English text for $name" } - private fun render(twoSlots: Boolean) { + private fun render(twoSlots: Boolean, host: DexcomOnePlusHost = FakeHost()) { // MainApp does this in production. Without it every TextRef.Named draws as its raw name and // the assertions below read "the node is not displayed" without saying why. TextRefIdRegistry.register("source") { name -> SourceStringIds.idOf(name) } compose.setContent { DexcomOnePlusStartScreen( - host = FakeHost, + host = host, permissions = GrantedPermissions, onBack = {}, onEnsureDriver = { OnePlusCgmDriverStub.instance }, @@ -108,6 +109,26 @@ class DexcomOnePlusStartScreenTest { compose.onNodeWithText(idle, useUnmergedTree = true).assertExists() } + @Test + fun `an installed sensor app is named in a warning`() { + render(twoSlots = false, host = FakeHost(installedApps = { it == "com.eveningoutpost.dexdrip" })) + compose.onNodeWithText(text("dexcom_oneplus_competing_apps_title")).assertIsDisplayed() + compose.onNodeWithText("xDrip+").assertIsDisplayed() + } + + @Test + fun `no warning when no sensor app is installed`() { + render(twoSlots = false, host = FakeHost(installedApps = { false })) + compose.onNodeWithText(text("dexcom_oneplus_competing_apps_title")).assertDoesNotExist() + } + + @Test + fun `no warning at all on a phone that cannot list its apps`() { + // No answer is not the same as "none installed", so nothing is drawn. + render(twoSlots = false, host = FakeHost(installedApps = null)) + compose.onNodeWithText(text("dexcom_oneplus_competing_apps_title")).assertDoesNotExist() + } + /** A phone where the Bluetooth permission is already granted. */ private object GrantedPermissions : OnePlusBlePermissionGate { override fun granted(): Boolean = true @@ -115,7 +136,7 @@ class DexcomOnePlusStartScreenTest { } /** Everything the screen asks of the phone, answered without Bluetooth or a file. */ - private object FakeHost : DexcomOnePlusHost { + private class FakeHost(override val installedApps: OnePlusInstalledApps? = null) : DexcomOnePlusHost { override fun attachPlatform(driver: OnePlusCgmDriver) = Unit override fun slotStore(namespace: String?): OnePlusSensorStore = OnePlusSensorStore(MemoryPrefs()) diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt index b13912ff1f01..195844e8d710 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusAndroidHost.kt @@ -8,6 +8,8 @@ import app.aaps.plugins.dexcomoneplus.OnePlusAndroidPlatform import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusInstalledApps +import app.aaps.plugins.dexcomoneplus.OnePlusInstalledAppsAndroid import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner @@ -81,6 +83,9 @@ class DexcomOnePlusAndroidHost( override fun screenScanner(): OnePlusBleScanner = OnePlusBleScannerAndroid(appContext, sessionHint = null) + /** Android can list the installed apps it declares in its manifest ``. */ + override val installedApps: OnePlusInstalledApps by lazy { OnePlusInstalledAppsAndroid(appContext) } + override fun screenItems(plugin: DexcomOnePlusPlugin): List = listOf( DexcomOnePlusIntentKey.Status.withClick { open(DexcomOnePlusStatusActivity::class.java) }, DexcomOnePlusIntentKey.Start.withClick { open(DexcomOnePlusStartActivity::class.java) }, diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt index f7664dd81029..94f4804ec22d 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt @@ -2,7 +2,9 @@ package app.aaps.plugins.source import app.aaps.core.keys.interfaces.PreferenceItem import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver +import app.aaps.plugins.dexcomoneplus.OnePlusCompetingApps import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher +import app.aaps.plugins.dexcomoneplus.OnePlusInstalledApps import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner @@ -90,6 +92,15 @@ interface DexcomOnePlusHost { */ fun screenScanner(): OnePlusBleScanner + /** + * Tells which other apps are installed, for the start screen's warning about apps that fight + * with us for the sensor (see [OnePlusCompetingApps]). + * + * Null on a phone that cannot tell: then the warning is absent, never a "none found" it does + * not know. + */ + val installedApps: OnePlusInstalledApps? + /** * The entries that open this plugin's own screens, for the settings screen. * diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt index 299d74d3282d..6c4023b9abd2 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartRules.kt @@ -39,10 +39,21 @@ object DexcomOnePlusStartRules { /** * The scan list in the order the screen draws it: the sensor the code on screen points at - * first, then by how well each hit matches, then by signal. + * first, then by how well each hit matches, then free sensors before the ones another phone + * holds, then by signal. */ fun rank(devices: List, hint: OnePlusStoredSession?): List = - devices.sortedByDescending { OnePlusAdvCandidate.rankScore(it.name, it.address, it.rssi, hint) } + devices.sortedByDescending { + OnePlusAdvCandidate.rankScore(it.name, it.address, it.rssi, hint, it.phoneSlotHeld) + } + + /** + * Whether the row says "in use by another phone". + * + * Not for the stored sensor: the phone that holds its slot is normally this one. + */ + fun showsSlotHeld(device: OnePlusScanResult, storedMac: String?): Boolean = + device.phoneSlotHeld == true && storedMac?.equals(device.address, ignoreCase = true) != true /** * Signal strength as bars. diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt index b8ff85cbb0c4..9e3e5f45de83 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt @@ -56,6 +56,8 @@ import app.aaps.core.ui.compose.stringResource import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriverReal import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.OnePlusCompetingApp +import app.aaps.plugins.dexcomoneplus.OnePlusCompetingApps import app.aaps.plugins.dexcomoneplus.identity.OnePlusAdvCandidate import app.aaps.plugins.dexcomoneplus.identity.OnePlusGs1ApplicatorParser import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity @@ -118,6 +120,9 @@ fun DexcomOnePlusStartScreen( val sensorStore = remember(slot) { host.slotStore(OnePlusCgmDrivers.storeNamespace(slot)) } val storedSession = remember(slot) { sensorStore.load() } val scanner = remember { host.screenScanner() } + // Other apps that fight with us for the sensor. Looked up once per visit, and logged there. + // Null on a phone that cannot list its apps the card is then absent, not "none found". + val competingApps = remember { host.installedApps?.let { OnePlusCompetingApps.installed(it) }.orEmpty() } val focusManager = LocalFocusManager.current var applicatorInput by remember { mutableStateOf("") } @@ -403,6 +408,7 @@ fun DexcomOnePlusStartScreen( slot = slot, onSlotChange = { slot = it; errorText = null }, slotChoiceOffered = onStagingDriver != null, + competingApps = competingApps, permissions = permissions, applicatorInput = applicatorInput, parsedIdentity = parsedIdentity, @@ -461,6 +467,7 @@ fun DexcomOnePlusStartScreen( slot = slot, onSlotChange = { slot = it; errorText = null }, slotChoiceOffered = onStagingDriver != null, + competingApps = competingApps, permissions = permissions, applicatorInput = applicatorInput, parsedIdentity = parsedIdentity, @@ -562,6 +569,7 @@ private fun ColumnScope.FormPane( slot: SensorSlot, onSlotChange: (SensorSlot) -> Unit, slotChoiceOffered: Boolean, + competingApps: List, permissions: OnePlusBlePermissionGate, applicatorInput: String, parsedIdentity: OnePlusSensorIdentity?, @@ -607,6 +615,8 @@ private fun ColumnScope.FormPane( } } + if (competingApps.isNotEmpty()) CompetingAppsCard(competingApps) + if (!permissions.granted()) { Button( onClick = { permissions.request() }, @@ -652,6 +662,29 @@ private fun ColumnScope.FormPane( if (window.isTwoPane) HelpSection(slot = slot, slotChoiceOffered = slotChoiceOffered) } +/** + * Warns that another app on this phone may take the sensor from us. + * + * Open, not folded: it is about this phone, right now, and it explains a refusal before it happens. + * One line per app, so no list of names is joined in code. + */ +@Composable +private fun CompetingAppsCard(apps: List) { + CgmCard(tone = CgmCardTone.Warning) { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_competing_apps_title)) + Text( + text = stringResource(SourceStrings.dexcom_oneplus_competing_apps_message), + style = MaterialTheme.typography.bodyMedium, + ) + apps.forEach { app -> + Text( + text = app.label, + style = MaterialTheme.typography.bodyMedium, + ) + } + } +} + /** * The five help blocks that used to sit permanently open above the first control — about two * screens of scrolling before the user could reach Scan. Folded away, but the one that warns about @@ -770,6 +803,7 @@ private fun LazyListScope.deviceItems( device = device, selected = selectedAddress == device.address, lastUsed = storedMac?.equals(device.address, ignoreCase = true) == true, + slotHeld = DexcomOnePlusStartRules.showsSlotHeld(device, storedMac), onClick = { onDeviceClick(device) }, ) } @@ -781,6 +815,7 @@ private fun DeviceRow( device: OnePlusScanResult, selected: Boolean, lastUsed: Boolean, + slotHeld: Boolean, onClick: () -> Unit, ) { val shape = RoundedCornerShape(AapsSpacing.large) @@ -827,6 +862,15 @@ private fun DeviceRow( color = MaterialTheme.colorScheme.primary, ) } + // Ranked below the free sensors already; this says why, so the user does not pick it + // by mistake and get a refusal. + if (slotHeld) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_scan_slot_held), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.error, + ) + } } SignalBars(rssi = device.rssi) } diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt index 3e664cba045f..cc83ada7ac8a 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt @@ -3,6 +3,7 @@ package app.aaps.plugins.source.compose import androidx.compose.runtime.Composable import app.aaps.core.ui.compose.stringResource import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusalPolicy import app.aaps.plugins.source.SourceStrings /** @@ -39,6 +40,14 @@ object DexcomOnePlusUiLabels { stringResource(SourceStrings.dexcom_oneplus_msg_tx_session) raw == "egv_loop_exit" || raw == "disconnect" || raw == "shutdown" || raw == "cancelled" -> stringResource(SourceStrings.dexcom_oneplus_msg_session_down) + // Before the generic auth line: these two say what the user has to do. + raw.startsWith(OnePlusAuthRefusalPolicy.MESSAGE_LOCKED) -> + stringResource( + SourceStrings.dexcom_oneplus_error_refused_stopped, + OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW, + ) + raw.startsWith(OnePlusAuthRefusalPolicy.MESSAGE_PAUSED) -> + stringResource(SourceStrings.dexcom_oneplus_msg_refused_pause) raw.startsWith("ONEPLUS_AUTH") || raw.contains("bond", ignoreCase = true) -> stringResource(SourceStrings.dexcom_oneplus_error_auth_bond) raw.startsWith("ONEPLUS_GATT") || raw.startsWith("ONEPLUS_EGV") || diff --git a/plugins/source/src/androidMain/res/values/strings.xml b/plugins/source/src/androidMain/res/values/strings.xml index 2a9e4916f0a9..263aad2bace8 100644 --- a/plugins/source/src/androidMain/res/values/strings.xml +++ b/plugins/source/src/androidMain/res/values/strings.xml @@ -174,6 +174,8 @@ Sensor session detected on transmitter. Session ended or disconnected. Authentication or Bluetooth pairing failed. Accept the system pairing prompt and retry. + The sensor refused this phone %1$d times in a row. AAPS stopped trying, because one more refusal locks the sensor for a while. Check the pairing code, close the Dexcom app, xDrip+ or Juggluco if one of them uses the sensor, then start the sensor again. + The sensor refused this phone. AAPS waits 15 minutes before it asks again, because refusals in a row lock the sensor. Check the pairing code and close other apps that use the sensor. Connection or sensor session error. Check the Bluetooth connection and try again. If the problem continues, open the driver log on this screen. Warm-up complete — source active @@ -235,6 +237,9 @@ Sensors nearby Rescan last used + in use by another phone + Other sensor apps on this phone + These apps are installed and can connect to the sensor themselves. A sensor talks to one app at a time, so the sensor may refuse AAPS while one of them uses it. Close it or turn off its sensor connection before you start. Signal %1$d dBm No sensor found yet. Press Scan and keep the phone right next to the sensor. Connect adopts %1$s and opens warm-up. From bf4e30778f8698ec636f14625fd7bc05cf53275b Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 5 Nov 2026 00:58:20 +0100 Subject: [PATCH 12/27] Dexcom ONE+ / G7: status recap and driver log in the plugin tab, applicator barcode scan The plugin tab shows the readings list with a sensor button. It opens the status screen (pump overview with calibration, end of life and pre-soak cards) and from there the driver log of AndroidAPS.log, with a share button. The Status entry left the settings; the status Activity stays for the notification and the setup screens. The start screen can read the applicator code with the camera (CameraX + ZXing). Co-Authored-By: Claude Opus 5.5 (1M context) --- app/src/testFull/resources/prefs-schema.txt | 1 - plugins/dexcom_oneplus/NOTICE | 12 + plugins/source/build.gradle.kts | 8 + .../source/DexcomOnePlusInsertionDateTest.kt | 2 +- .../source/DexcomOnePlusPluginLifetimeTest.kt | 5 + .../DexcomOnePlusPluginVisibilityTest.kt | 2 +- .../source/DexcomOnePlusPromotionOrderTest.kt | 79 +- .../DexcomOnePlusSensorAgeRepairTest.kt | 2 +- .../DexcomOnePlusSensorCalibrationTest.kt | 2 +- .../compose/DexcomOnePlusStartScreenTest.kt | 7 + .../compose/DexcomOnePlusStatusStateTest.kt | 289 ++++++++ .../src/androidMain/AndroidManifest.xml | 6 + .../source/DexcomOnePlusAndroidHost.kt | 43 +- .../aaps/plugins/source/DexcomOnePlusHost.kt | 27 +- .../plugins/source/DexcomOnePlusPlugin.kt | 11 +- .../activities/DexcomOnePlusStartActivity.kt | 2 + .../activities/DexcomOnePlusStatusActivity.kt | 682 +----------------- .../source/compose/CameraApplicatorScanner.kt | 185 +++++ .../compose/DexcomOnePlusComposeContent.kt | 153 ++++ .../source/compose/DexcomOnePlusLogScreen.kt | 102 +++ .../compose/DexcomOnePlusStartScreen.kt | 24 + .../compose/DexcomOnePlusStatusOverview.kt | 362 ++++++++++ .../compose/DexcomOnePlusStatusState.kt | 276 +++++++ .../compose/DexcomOnePlusStatusSummary.kt | 75 -- .../compose/DexcomOnePlusStatusViewModel.kt | 166 +++++ .../source/compose/DexcomOnePlusUiLabels.kt | 56 +- .../compose/OnePlusApplicatorScanner.kt | 88 +++ .../src/androidMain/res/values/strings.xml | 14 +- .../source/compose/BgSourceComposeContent.kt | 17 +- .../source/keys/DexcomOnePlusIntentKey.kt | 8 +- 30 files changed, 1855 insertions(+), 851 deletions(-) create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusStateTest.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CameraApplicatorScanner.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusComposeContent.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusLogScreen.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusOverview.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusState.kt delete mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusViewModel.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusApplicatorScanner.kt diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index a5660ebdd6ac..a4459e18df6b 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -166,7 +166,6 @@ dexcom_oneplus_send_calibration_to_sensor|DexcomOnePlusBooleanKey|false dexcom_oneplus_staging_auto_promote_hours|DexcomOnePlusIntKey|true dexcom_oneplus_staging_auto_promote|DexcomOnePlusBooleanKey|false dexcom_oneplus_start|DexcomOnePlusIntentKey|false -dexcom_oneplus_status|DexcomOnePlusIntentKey|false dexcom_oneplus_warmup|DexcomOnePlusIntentKey|false dexcomg5_nsupload|BooleanKey|true diaconn_bt_selector|DiaconnIntentKey|false diff --git a/plugins/dexcom_oneplus/NOTICE b/plugins/dexcom_oneplus/NOTICE index 4c79d968690d..8fc3f640ffb1 100644 --- a/plugins/dexcom_oneplus/NOTICE +++ b/plugins/dexcom_oneplus/NOTICE @@ -151,6 +151,18 @@ The OEM device-profile abstraction (oem/) and the Android GATT plumbing bulk of gatt/OnePlusGattClientAndroid.kt are original AAPS implementation; only the protocol choreography within them is derived (see sections 1 and 2). +Ideas taken from AndroidAPS pull request #5397 (Dexcom G7 direct, author +t1dude), https://github.com/nightscout/AndroidAPS/pull/5397, commit +bec1b16ba20ec646d459a1c724ad41419985b117. That code is AndroidAPS code under the +same AGPL-3 license as this tree; none of its Trio (G7SensorKit, MIT) protocol +code or Trio sounds are used here. Written again on top of this driver, not +copied: + - :plugins:source CameraApplicatorScanner.kt: the applicator Data Matrix scan + (PR file cgm/dexcomg7/src/.../ui/G7BarcodeScanner.kt), in particular the + "callback returns true when the code was wanted, then stop" contract. The + camera code itself follows the client QR scanner of :plugins:sync + (QrScanner.android.kt). + ------------------------------------------------------------------------------- Reviewer verification points (not legal advice — maintainer/counsel to confirm) diff --git a/plugins/source/build.gradle.kts b/plugins/source/build.gradle.kts index 9e583dd358fb..26bd409a5b0a 100644 --- a/plugins/source/build.gradle.kts +++ b/plugins/source/build.gradle.kts @@ -52,6 +52,14 @@ kotlin { implementation(libs.androidx.compose.runtime) implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.work.runtime) + + // The camera that reads the Dexcom ONE+ / G7 applicator barcode on the start screen. + // The same CameraX and ZXing versions as the client set-up QR scanner of :plugins:sync. + implementation(libs.androidx.camera.camera2) + implementation(libs.androidx.camera.core) + implementation(libs.androidx.camera.lifecycle) + implementation(libs.androidx.camera.view) + implementation(libs.com.google.zxing.core) } } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt index 6a8f89a95fff..47b344f4bb6d 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusInsertionDateTest.kt @@ -66,7 +66,7 @@ class DexcomOnePlusInsertionDateTest : TestBase() { whenever(persistenceLayer.getTherapyEventDataFromToTime(any(), any())).thenReturn(emptyList()) whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())).thenReturn(emptyList()) plugin = DexcomOnePlusPlugin( - rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context) { error("the log is not read here") }, persistenceLayer, mock(), activePlugin, rxBus, ) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt index e70cf636da47..35969a86f93b 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginLifetimeTest.kt @@ -280,6 +280,11 @@ class DexcomOnePlusPluginLifetimeTest : TestBase() { override fun alert(message: String) = Unit override fun screenScanner(): OnePlusBleScanner = OnePlusBleScannerStub() override fun screenItems(plugin: DexcomOnePlusPlugin): List = emptyList() + override fun openScreen(screen: DexcomOnePlusHost.Screen) = Unit + override suspend fun driverLog(): DexcomOnePlusHost.DriverLog = + DexcomOnePlusHost.DriverLog(emptyList(), SourceStrings.dexcom_oneplus_log_note_file) + + override fun shareLog(text: String) = Unit } /** An empty slot store in memory. */ diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt index 33366db698db..5811912c1cfa 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPluginVisibilityTest.kt @@ -40,7 +40,7 @@ class DexcomOnePlusPluginVisibilityTest : TestBase() { @BeforeEach fun setup() { plugin = DexcomOnePlusPlugin( - rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context) { error("the log is not read here") }, persistenceLayer, mock(), activePlugin, rxBus ) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt index dd998dc46984..a22700c6523e 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusPromotionOrderTest.kt @@ -24,7 +24,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorIdentity import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore import app.aaps.plugins.dexcomoneplus.session.OnePlusMacArbiter -import app.aaps.plugins.source.activities.dexcomOnePlusPromotionMessage +import app.aaps.plugins.source.compose.DexcomOnePlusStatusState import app.aaps.shared.tests.AAPSLoggerTest import app.aaps.shared.tests.SharedPreferencesMock import app.aaps.shared.tests.TestBase @@ -83,7 +83,7 @@ class DexcomOnePlusPromotionOrderTest : TestBase() { whenever(persistenceLayer.insertCgmSourceData(any(), any(), any(), anyOrNull())) .thenReturn(PersistenceLayer.TransactionResult()) plugin = DexcomOnePlusPlugin( - rh, logger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + rh, logger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context) { error("the log is not read here") }, persistenceLayer, mock(), activePlugin, rxBus, ) plugin.promotionAlerter = { alerts += it } @@ -300,71 +300,16 @@ class DexcomOnePlusPromotionOrderTest : TestBase() { "Sensor promoted, but older calibration entries could not be ignored. " + "Remove fingerstick calibrations taken before this switch, then calibrate again if needed.", ) - assertThat( - dexcomOnePlusPromotionMessage( - result = PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT), - ok = "ok", - boundFailed = "bound", - followUpIdentityPresent = "follow", - followUpIdentityMissing = "missing", - rejectedAbsent = "absent", - rejectedNotSettled = "settling", - rejectedNoGlucose = "glucose", - rejectedNoRecentGlucose = "recent", - ), - ).isEqualTo("absent") - assertThat( - dexcomOnePlusPromotionMessage( - result = PromotionResult.OkBoundFailed, - ok = "ok", - boundFailed = "bound", - followUpIdentityPresent = "follow", - followUpIdentityMissing = "missing", - rejectedAbsent = "absent", - rejectedNotSettled = "settling", - rejectedNoGlucose = "glucose", - rejectedNoRecentGlucose = "recent", - ), - ).isEqualTo("bound") - assertThat( - dexcomOnePlusPromotionMessage( - result = PromotionResult.OkFollowUpFailed(productionIdentityPresent = true), - ok = "ok", - boundFailed = "bound", - followUpIdentityPresent = "follow", - followUpIdentityMissing = "missing", - rejectedAbsent = "absent", - rejectedNotSettled = "settling", - rejectedNoGlucose = "glucose", - rejectedNoRecentGlucose = "recent", - ), - ).isEqualTo("follow") - assertThat( - dexcomOnePlusPromotionMessage( - result = PromotionResult.OkFollowUpFailed(productionIdentityPresent = false), - ok = "ok", - boundFailed = "bound", - followUpIdentityPresent = "follow", - followUpIdentityMissing = "missing", - rejectedAbsent = "absent", - rejectedNotSettled = "settling", - rejectedNoGlucose = "glucose", - rejectedNoRecentGlucose = "recent", - ), - ).isEqualTo("missing") - assertThat( - dexcomOnePlusPromotionMessage( - result = PromotionResult.Ok, - ok = "ok", - boundFailed = "bound", - followUpIdentityPresent = "follow", - followUpIdentityMissing = "missing", - rejectedAbsent = "absent", - rejectedNotSettled = "settling", - rejectedNoGlucose = "glucose", - rejectedNoRecentGlucose = "recent", - ), - ).isEqualTo("ok") + assertThat(DexcomOnePlusStatusState.promotionMessage(PromotionResult.Rejected(PromotionRejectReason.STAGING_ABSENT))) + .isEqualTo(SourceStrings.dexcom_oneplus_staging_promote_rejected_absent) + assertThat(DexcomOnePlusStatusState.promotionMessage(PromotionResult.OkBoundFailed)) + .isEqualTo(SourceStrings.dexcom_oneplus_staging_promote_bound_failed) + assertThat(DexcomOnePlusStatusState.promotionMessage(PromotionResult.OkFollowUpFailed(productionIdentityPresent = true))) + .isEqualTo(SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed) + assertThat(DexcomOnePlusStatusState.promotionMessage(PromotionResult.OkFollowUpFailed(productionIdentityPresent = false))) + .isEqualTo(SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed_no_identity) + assertThat(DexcomOnePlusStatusState.promotionMessage(PromotionResult.Ok)) + .isEqualTo(SourceStrings.dexcom_oneplus_staging_promote_ok) } @Test diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt index 03d87e18efb7..57376b5c38ae 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAgeRepairTest.kt @@ -75,7 +75,7 @@ class DexcomOnePlusSensorAgeRepairTest : TestBase() { whenever(persistenceLayer.getTherapyEventDataIncludingInvalidFromTime(any(), any())) .thenReturn(emptyList()) plugin = DexcomOnePlusPlugin( - rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context) { error("the log is not read here") }, persistenceLayer, mock(), activePlugin, rxBus, ) DexcomOnePlusIngest.reset() diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt index e14798b1cc87..58d6a7cfa005 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorCalibrationTest.kt @@ -57,7 +57,7 @@ class DexcomOnePlusSensorCalibrationTest : TestBase() { whenever(context.applicationContext).thenReturn(context) whenever(rh.gs(any())).thenReturn("not sent") plugin = DexcomOnePlusPlugin( - rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context), persistenceLayer, + rh, aapsLogger, preferences, config, notificationManager, DexcomOnePlusAndroidHost(context) { error("the log is not read here") }, persistenceLayer, mock(), activePlugin, rxBus, ) } diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt index b5893eaff0b5..17195557f913 100644 --- a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreenTest.kt @@ -21,6 +21,7 @@ import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScannerStub import app.aaps.plugins.source.DexcomOnePlusHost import app.aaps.plugins.source.DexcomOnePlusPlugin import app.aaps.plugins.source.SourceStringIds +import app.aaps.plugins.source.SourceStrings import app.aaps.plugins.source.SourceStringsValues import org.junit.Rule import org.junit.Test @@ -66,6 +67,7 @@ class DexcomOnePlusStartScreenTest { onOpenPromote = {}, onStagingDriver = if (twoSlots) ({ error("not reached in this test") }) else null, onSensorSessionStarted = { _, _ -> }, + applicatorScanner = null, ) } } @@ -155,6 +157,11 @@ class DexcomOnePlusStartScreenTest { override fun alert(message: String) = Unit override fun screenScanner(): OnePlusBleScanner = OnePlusBleScannerStub() override fun screenItems(plugin: DexcomOnePlusPlugin): List = emptyList() + override fun openScreen(screen: DexcomOnePlusHost.Screen) = Unit + override suspend fun driverLog(): DexcomOnePlusHost.DriverLog = + DexcomOnePlusHost.DriverLog(emptyList(), SourceStrings.dexcom_oneplus_log_note_file) + + override fun shareLog(text: String) = Unit } /** An empty slot store in memory, so the screen starts with no sensor remembered. */ diff --git a/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusStateTest.kt b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusStateTest.kt new file mode 100644 index 000000000000..54f0018cddcc --- /dev/null +++ b/plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusStateTest.kt @@ -0,0 +1,289 @@ +package app.aaps.plugins.source.compose + +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.data.model.TrendArrow +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.interfaces.source.CgmStagingEvidence +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.ui.compose.StatusLevel +import app.aaps.core.ui.compose.pump.PumpInfoRow +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusalPolicy +import app.aaps.plugins.source.SourceStrings +import org.junit.jupiter.api.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** The ONE+ / G7 status screen state, without a phone or a driver. */ +class DexcomOnePlusStatusStateTest { + + /** Answers each text with its resource name and arguments, so a test reads which text it got. */ + private object NameResolver : TextResolver { + + override fun gs(ref: TextRef): String { + val named = ref as TextRef.Named + return if (named.args.isEmpty()) named.name + else named.name + named.args.joinToString(prefix = "(", postfix = ")", separator = "|") + } + + override fun gs(ref: TextRef, vararg args: Any?): String = + if (args.isEmpty()) gs(ref) else gs(ref) + args.joinToString(prefix = "(", postfix = ")", separator = "|") + + override fun gsNotLocalised(ref: TextRef): String = gs(ref) + } + + private val format = DexcomOnePlusStatusFormat( + rh = NameResolver, + glucose = { mgdl -> "${mgdl.toInt()} mg/dl" }, + time = { epochMs -> "t$epochMs" }, + age = { millis -> "${millis / 3_600_000L} h" }, + ) + + private var opened = "" + private val actions = DexcomOnePlusStatusActions( + onOpenStart = { opened = "start" }, + onOpenWarmup = { opened = "warmup" }, + onOpenLog = { opened = "log" }, + ) + + private fun input( + phase: OnePlusWarmupState.Phase = OnePlusWarmupState.Phase.READY, + sessionUp: Boolean = true, + lifecycle: CgmSensorLifecycle? = null, + newestGlucose: GV? = null, + calibrationOutcome: OnePlusCalibrationOutcome? = null, + calibrationWaiting: Boolean = false, + sendCalibrationToSensor: Boolean = false, + correctSensorStartEnabled: Boolean = false, + stagingState: StagingState = StagingState.ABSENT, + stagingEvidence: CgmStagingEvidence? = null, + driverMessage: String? = null, + ) = DexcomOnePlusStatusInput( + phase = phase, + driverMessage = driverMessage, + sessionUp = sessionUp, + lifecycle = lifecycle, + newestGlucose = newestGlucose, + calibrationOutcome = calibrationOutcome, + calibrationWaiting = calibrationWaiting, + sendCalibrationToSensor = sendCalibrationToSensor, + correctSensorStartEnabled = correctSensorStartEnabled, + stagingState = stagingState, + stagingEvidence = stagingEvidence, + nowMs = NOW, + ) + + private fun lifecycle(endOfLife: Boolean = false) = CgmSensorLifecycle( + startedAtEpochMs = NOW - 5 * HOUR, + ageMs = 5 * HOUR, + endOfLife = endOfLife, + ) + + private fun reading(source: SourceSensor) = GV( + timestamp = NOW - 60_000L, + raw = null, + value = 120.0, + trendArrow = TrendArrow.FLAT, + noise = null, + sourceSensor = source, + ) + + private fun rows(input: DexcomOnePlusStatusInput): List = + DexcomOnePlusStatusState.build(input, format, actions).overview.infoRows.map { it as PumpInfoRow } + + @Test + fun bannerIsGreenOnlyWhenReadyAndConnected() { + assertEquals(StatusLevel.NORMAL, DexcomOnePlusStatusState.bannerLevel(OnePlusWarmupState.Phase.READY, sessionUp = true)) + assertEquals(StatusLevel.WARNING, DexcomOnePlusStatusState.bannerLevel(OnePlusWarmupState.Phase.READY, sessionUp = false)) + assertEquals(StatusLevel.WARNING, DexcomOnePlusStatusState.bannerLevel(OnePlusWarmupState.Phase.WARMING, sessionUp = true)) + assertEquals(StatusLevel.CRITICAL, DexcomOnePlusStatusState.bannerLevel(OnePlusWarmupState.Phase.FAILED, sessionUp = false)) + assertEquals(StatusLevel.UNSPECIFIED, DexcomOnePlusStatusState.bannerLevel(OnePlusWarmupState.Phase.IDLE, sessionUp = false)) + } + + @Test + fun bannerShowsThePhase() { + val view = DexcomOnePlusStatusState.build(input(phase = OnePlusWarmupState.Phase.WARMING), format, actions) + assertEquals("dexcom_oneplus_phase_warming", view.overview.statusBanner?.text) + } + + @Test + fun ownReadingIsShown() { + val first = rows(input(newestGlucose = reading(SourceSensor.DEXCOM_ONEPLUS_NATIVE))).first() + assertEquals("dexcom_oneplus_row_last_reading", first.label) + assertEquals("dexcom_oneplus_reading_at(120 mg/dl|t${NOW - 60_000L})", first.value) + } + + @Test + fun readingOfAnotherSourceIsNotShownAsThisSensor() { + val first = rows(input(newestGlucose = reading(SourceSensor.LIBRE_3))).first() + assertEquals("dexcom_oneplus_production_no_reading", first.value) + } + + @Test + fun sessionDownIsAWarningRow() { + val session = rows(input(sessionUp = false)).single { it.label == "cgm_session_label" } + assertEquals("dexcom_oneplus_session_down", session.value) + assertEquals(StatusLevel.WARNING, session.level) + } + + @Test + fun sensorAgeRowWarnsNearTheEnd() { + assertNull(rows(input()).firstOrNull { it.label == "dexcom_oneplus_row_sensor_age" }) + val young = rows(input(lifecycle = lifecycle())).single { it.label == "dexcom_oneplus_row_sensor_age" } + assertEquals("5 h", young.value) + assertEquals(StatusLevel.UNSPECIFIED, young.level) + val old = rows(input(lifecycle = lifecycle(endOfLife = true))).single { it.label == "dexcom_oneplus_row_sensor_age" } + assertEquals(StatusLevel.WARNING, old.level) + } + + @Test + fun driverCodesAreNeverShownRaw() { + val message = rows(input(driverMessage = "ONEPLUS_GATT_133")).last() + assertEquals("dexcom_oneplus_row_message", message.label) + assertEquals("dexcom_oneplus_error_connection", message.value) + } + + @Test + fun refusalLinesSayWhatToDo() { + val stopped = rows(input(driverMessage = OnePlusAuthRefusalPolicy.MESSAGE_LOCKED)).last() + assertEquals("dexcom_oneplus_error_refused_stopped(${OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW})", stopped.value) + val paused = rows(input(driverMessage = OnePlusAuthRefusalPolicy.MESSAGE_PAUSED)).last() + assertEquals("dexcom_oneplus_msg_refused_pause", paused.value) + } + + @Test + fun buttonsOpenStartWarmupAndLog() { + val overview = DexcomOnePlusStatusState.build(input(), format, actions).overview + assertEquals(listOf("dexcom_oneplus_start_action", "dexcom_oneplus_step_warmup"), overview.primaryActions.map { it.label }) + assertEquals(listOf("cgm_driver_log_open"), overview.managementActions.map { it.label }) + overview.primaryActions[0].onClick() + assertEquals("start", opened) + overview.primaryActions[1].onClick() + assertEquals("warmup", opened) + overview.managementActions[0].onClick() + assertEquals("log", opened) + } + + @Test + fun calibrationCardOnlyWhileValuesGoToTheSensor() { + assertNull(DexcomOnePlusStatusState.build(input(), format, actions).calibration) + val card = assertNotNull( + DexcomOnePlusStatusState.build( + input(sendCalibrationToSensor = true, calibrationOutcome = OnePlusCalibrationOutcome.Refused("0x01")), + format, + actions, + ).calibration, + ) + assertEquals(SourceStrings.dexcom_oneplus_calibration_refused, card.outcome) + assertEquals("0x01", card.detail) + assertNull(card.notSentReason) + assertTrue(card.warning) + } + + @Test + fun unknownCalibrationAnswerIsNotSoftened() { + val card = DexcomOnePlusStatusState.build( + input(sendCalibrationToSensor = true, calibrationOutcome = OnePlusCalibrationOutcome.Unknown(" ")), + format, + actions, + ).calibration + assertEquals(SourceStrings.dexcom_oneplus_calibration_unknown, card?.outcome) + assertNull(card?.detail) + assertFalse(card?.warning ?: true) + } + + @Test + fun droppedCalibrationSaysWhyAndWarns() { + val card = assertNotNull( + DexcomOnePlusStatusState.build( + input( + sendCalibrationToSensor = true, + calibrationOutcome = OnePlusCalibrationOutcome.NotSent(OnePlusCalibrationOutcome.NotSent.Reason.SENSOR_CHANGED), + ), + format, + actions, + ).calibration, + ) + assertEquals(SourceStrings.dexcom_oneplus_calibration_dropped, card.outcome) + assertEquals(SourceStrings.dexcom_oneplus_calibration_dropped_sensor_changed, card.notSentReason) + assertTrue(card.warning) + } + + @Test + fun droppedCalibrationReasonIsHiddenWhileANewValueWaits() { + val card = DexcomOnePlusStatusState.build( + input( + sendCalibrationToSensor = true, + calibrationWaiting = true, + calibrationOutcome = OnePlusCalibrationOutcome.NotSent(OnePlusCalibrationOutcome.NotSent.Reason.TOO_OLD), + ), + format, + actions, + ).calibration + assertEquals(SourceStrings.dexcom_oneplus_calibration_waiting, card?.outcome) + assertNull(card?.notSentReason) + } + + @Test + fun sensorRequestIsReadFromTheDriverLine() { + assertEquals(SourceStrings.dexcom_oneplus_calibration_state_needs_first, DexcomOnePlusStatusState.calibrationRequest("NeedsFirstCalibration")) + assertNull(DexcomOnePlusStatusState.calibrationRequest("auth_ok")) + assertNull(DexcomOnePlusStatusState.calibrationRequest(null)) + } + + @Test + fun endOfLifePromptOnlyWithoutAPreSoakSensor() { + assertTrue(DexcomOnePlusStatusState.build(input(lifecycle = lifecycle(endOfLife = true)), format, actions).endOfLifePrompt) + assertFalse(DexcomOnePlusStatusState.build(input(lifecycle = lifecycle()), format, actions).endOfLifePrompt) + assertFalse( + DexcomOnePlusStatusState.build( + input(lifecycle = lifecycle(endOfLife = true), stagingState = StagingState.WARMUP), + format, + actions, + ).endOfLifePrompt, + ) + } + + @Test + fun promoteOfferFollowsTheSlotState() { + fun offer(state: StagingState, evidence: CgmStagingEvidence? = null) = + DexcomOnePlusStatusState.build(input(stagingState = state, stagingEvidence = evidence), format, actions).staging.promote + + assertEquals(DexcomOnePlusPromoteOffer.NONE, offer(StagingState.ABSENT)) + assertEquals(DexcomOnePlusPromoteOffer.NORMAL, offer(StagingState.READY)) + assertEquals(DexcomOnePlusPromoteOffer.NONE, offer(StagingState.SETTLING)) + val alive = CgmStagingEvidence(validCount = 100, lastValueMgdl = 110.0, lastValueAtEpochMs = NOW - 60_000L) + assertEquals(DexcomOnePlusPromoteOffer.EARLY, offer(StagingState.SETTLING, alive)) + val silent = alive.copy(lastValueAtEpochMs = NOW - 2 * HOUR) + assertEquals(DexcomOnePlusPromoteOffer.NONE, offer(StagingState.SETTLING, silent)) + } + + @Test + fun insertionDateActionOnlyWithTheSwitchAndASession() { + assertNull(DexcomOnePlusStatusState.build(input(lifecycle = lifecycle()), format, actions).correctInsertionStartMs) + assertNull(DexcomOnePlusStatusState.build(input(correctSensorStartEnabled = true), format, actions).correctInsertionStartMs) + assertEquals( + NOW - 5 * HOUR, + DexcomOnePlusStatusState.build(input(correctSensorStartEnabled = true, lifecycle = lifecycle()), format, actions).correctInsertionStartMs, + ) + } + + @Test + fun scannedTextMustBeAnApplicatorCode() { + assertTrue(acceptApplicatorScan("1234")) + assertFalse(acceptApplicatorScan("https://example.org")) + } + + private companion object { + + const val HOUR = 3_600_000L + const val NOW = 1_800_000_000_000L + } +} diff --git a/plugins/source/src/androidMain/AndroidManifest.xml b/plugins/source/src/androidMain/AndroidManifest.xml index 7296b96efe8b..7c891708d939 100644 --- a/plugins/source/src/androidMain/AndroidManifest.xml +++ b/plugins/source/src/androidMain/AndroidManifest.xml @@ -4,6 +4,12 @@ + + + + ()) @SingleIn(AppScope::class) @Inject class DexcomOnePlusAndroidHost( private val context: Context, + // A function, not the type: the plugin tests build this host around a bare Context, and they + // never open the log screen. + private val loggerUtils: () -> LoggerUtils, ) : DexcomOnePlusHost { /** @@ -86,12 +94,39 @@ class DexcomOnePlusAndroidHost( /** Android can list the installed apps it declares in its manifest ``. */ override val installedApps: OnePlusInstalledApps by lazy { OnePlusInstalledAppsAndroid(appContext) } + /** + * Start and Warm-up stay in the settings, as before. Status is not here any more: it is the + * sensor button of the plugin tab, and the status Activity is still what the notification and + * the start and warm-up screens open. + */ override fun screenItems(plugin: DexcomOnePlusPlugin): List = listOf( - DexcomOnePlusIntentKey.Status.withClick { open(DexcomOnePlusStatusActivity::class.java) }, DexcomOnePlusIntentKey.Start.withClick { open(DexcomOnePlusStartActivity::class.java) }, DexcomOnePlusIntentKey.Warmup.withClick { open(DexcomOnePlusWarmupActivity::class.java) }, ) + override fun openScreen(screen: DexcomOnePlusHost.Screen) = when (screen) { + DexcomOnePlusHost.Screen.START -> open(DexcomOnePlusStartActivity::class.java) + DexcomOnePlusHost.Screen.WARMUP -> open(DexcomOnePlusWarmupActivity::class.java) + } + + /** The ONE+ lines of `AndroidAPS.log`, as the driver log Activity reads them. */ + override suspend fun driverLog(): DexcomOnePlusHost.DriverLog { + val lines = withContext(Dispatchers.IO) { + DriverLogReader.read(loggerUtils().logDirectory, setOf(OnePlusLogMarkers.TAG)) + } + return DexcomOnePlusHost.DriverLog(lines = lines, note = SourceStrings.dexcom_oneplus_log_note_file) + } + + override fun shareLog(text: String) { + val send = Intent(Intent.ACTION_SEND) + .setType("text/plain") + .putExtra(Intent.EXTRA_TEXT, text) + appContext.startActivity( + Intent.createChooser(send, appContext.getString(R.string.cgm_driver_log_share)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + } + private fun open(screen: Class<*>) { context.startActivity( Intent(context, screen).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt index 94f4804ec22d..911cf414ee67 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusHost.kt @@ -1,6 +1,7 @@ package app.aaps.plugins.source import app.aaps.core.keys.interfaces.PreferenceItem +import app.aaps.core.keys.interfaces.TextRef import app.aaps.plugins.dexcomoneplus.OnePlusCgmDriver import app.aaps.plugins.dexcomoneplus.OnePlusCompetingApps import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher @@ -13,9 +14,9 @@ import app.aaps.plugins.dexcomoneplus.scan.OnePlusBleScanner * Everything [DexcomOnePlusPlugin] needs from the phone it runs on. * * The plugin keeps the sensor slots, the pre-soak rules, the promotion gates and the ingest path. - * What needs an Android `Context` is asked here: the driver registry, how the three setup screens - * are opened, the foreground service and the status-bar notification. Each of those is named one - * by one, the same way `OnePlusPlatform` names what the driver needs, so the plugin never has to + * What needs an Android `Context` is asked here: the driver registry, how the start and warm-up + * screens are opened, where the driver log is read from, the foreground service and the status-bar + * notification. Each of those is named one by one, the same way `OnePlusPlatform` names what the driver needs, so the plugin never has to * know what a `Context` is and the tests can replace the host with a fake. * * ⚠️ Nothing here may answer with something that pretends to work. A CGM plugin that is switched on @@ -108,4 +109,24 @@ interface DexcomOnePlusHost { * the plugin builds the host, so a host that asked for the plugin would be a loop. */ fun screenItems(plugin: DexcomOnePlusPlugin): List + + /** The screens of this plugin that the status screen opens through the host. */ + enum class Screen { START, WARMUP } + + /** Opens [screen]. */ + fun openScreen(screen: Screen) + + /** + * What the log screen shows. + * + * @param lines the driver lines, oldest first. + * @param note one sentence that says where the lines come from and how long they are kept. + */ + data class DriverLog(val lines: List, val note: TextRef) + + /** Reads the newest driver lines. A host that reads a file does so off the main thread itself. */ + suspend fun driverLog(): DriverLog + + /** Hands the log text to another app, for the share button of the log screen. */ + fun shareLog(text: String) } diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt index 6e5f0f3276c8..399869c05aeb 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusPlugin.kt @@ -43,7 +43,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusGlucoseWatcher import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.identity.OnePlusSensorStore import app.aaps.plugins.dexcomoneplus.session.OnePlusCalibrationGate -import app.aaps.plugins.source.compose.BgSourceComposeContent +import app.aaps.plugins.source.compose.DexcomOnePlusComposeContent import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey import app.aaps.plugins.source.keys.DexcomOnePlusIntKey import app.aaps.plugins.source.keys.DexcomOnePlusIntentKey @@ -106,8 +106,10 @@ class DexcomOnePlusPlugin @Inject constructor( pluginDescription = PluginDescription() .mainType(PluginType.BGSOURCE) // No `showInList` call: the plugin is listed in every build, like the other BG sources. - .composeContent { plugin -> - BgSourceComposeContent( + // The readings list every BG source shows, with a sensor button in its toolbar that opens the + // status screen and from there the driver log. + .composeContent { _ -> + DexcomOnePlusComposeContent( title = rh.gs(SourceStrings.dexcom_oneplus_native), ) } @@ -358,7 +360,8 @@ class DexcomOnePlusPlugin @Inject constructor( key = "dexcom_oneplus_settings", title = SourceStrings.dexcom_oneplus_native, summary = SourceStrings.dexcom_oneplus_plugin_summary, - // The three screen buttons come from the host, because opening a screen needs a Context. + // The start and warm-up buttons come from the host, because opening a screen needs a Context. + // Status is the sensor button of the plugin tab instead. items = host.screenItems(this) + listOf( DexcomOnePlusBooleanKey.SendCalibrationToSensor, DexcomOnePlusBooleanKey.AutoPromote, diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt index 5ef536a09c6d..4a583af2788b 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStartActivity.kt @@ -16,6 +16,7 @@ import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers import app.aaps.plugins.source.DexcomOnePlusHost import app.aaps.plugins.source.DexcomOnePlusPlugin import app.aaps.plugins.source.OnePlusBlePermissionHelper +import app.aaps.plugins.source.compose.CameraApplicatorScanner import app.aaps.plugins.source.compose.DexcomOnePlusStartScreen import app.aaps.plugins.source.compose.OnePlusBlePermissionGate import dev.zacsweers.metro.Inject @@ -97,6 +98,7 @@ class DexcomOnePlusStartActivity : MetroAppCompatActivity() { onSensorSessionStarted = { address, previousMac -> dexcomOnePlusPlugin.onSensorSessionStarted(address, previousMac) }, + applicatorScanner = CameraApplicatorScanner, ) } } diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt index bf1eef2c3ddb..b61c95c606c6 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/activities/DexcomOnePlusStatusActivity.kt @@ -3,699 +3,71 @@ package app.aaps.plugins.source.activities import android.content.Intent import android.os.Bundle import androidx.activity.compose.setContent -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.List -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState -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.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import app.aaps.core.data.model.GV -import app.aaps.core.interfaces.db.PersistenceLayer -import app.aaps.core.interfaces.profile.ProfileUtil -import app.aaps.core.interfaces.resources.ResourceHelper -import app.aaps.core.interfaces.source.CgmSensorLifecycle -import app.aaps.core.interfaces.source.CgmStagingEvidence -import app.aaps.core.interfaces.source.PromotionRejectReason -import app.aaps.core.interfaces.source.PromotionResult -import app.aaps.core.interfaces.source.StagingState -import app.aaps.core.interfaces.utils.DateUtil import app.aaps.core.keys.interfaces.Preferences -import app.aaps.core.ui.CoreUiStrings -import app.aaps.core.ui.compose.AapsSpacing import app.aaps.core.ui.compose.AapsTheme import app.aaps.core.ui.compose.LocalPreferences import app.aaps.core.ui.compose.MetroAppCompatActivity -import app.aaps.core.ui.compose.dialogs.DatePickerModal -import app.aaps.core.ui.compose.dialogs.TimePickerModal -import app.aaps.core.ui.compose.stringResource as coreStringResource -import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome -import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.core.ui.compose.metroViewModel import app.aaps.plugins.dexcomoneplus.OnePlusLogMarkers -import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationState -import app.aaps.plugins.source.DexcomOnePlusCalibrationText -import app.aaps.plugins.source.DexcomOnePlusPlugin -import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection -import app.aaps.plugins.source.DexcomOnePlusStaging import app.aaps.plugins.source.R -import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey -import app.aaps.plugins.source.compose.CgmCard -import app.aaps.plugins.source.compose.CgmCardHeader -import app.aaps.plugins.source.compose.CgmCardTone -import app.aaps.plugins.source.compose.CgmKeyValueRow -import app.aaps.plugins.source.compose.CgmLazyColumn import app.aaps.plugins.source.compose.CgmScaffold -import app.aaps.plugins.source.compose.CgmStateChip -import app.aaps.plugins.source.compose.CgmStepTimeline -import app.aaps.plugins.source.compose.CgmUiState -import app.aaps.plugins.source.compose.DexcomOnePlusProductionCard -import app.aaps.plugins.source.compose.DexcomOnePlusUiLabels -import app.aaps.plugins.source.compose.formatSensorAge -import app.aaps.plugins.source.compose.toUiState +import app.aaps.plugins.source.compose.DexcomOnePlusStatusActions +import app.aaps.plugins.source.compose.DexcomOnePlusStatusOverview +import app.aaps.plugins.source.compose.DexcomOnePlusStatusViewModel import dev.zacsweers.metro.Inject -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.launch -import java.util.Calendar -import java.util.TimeZone /** - * Daily status of the native Dexcom ONE+ / G7 source. + * Daily status of the native Dexcom ONE+ / G7 source, as a window of its own. * - * The screen answers two questions that used to share one flat list of text lines: what is the - * sensor feeding the loop doing, and what is the pre-soak sensor doing. Each gets its own card, so - * a reading belongs to a visible subject. Everything sits in one scrolling list — the old - * non-scrolling column pushed the promote button, the one action that switches the loop's glucose - * source, past the bottom edge as soon as a staging sensor was present. + * The screen itself is [DexcomOnePlusStatusOverview]; the plugin tab shows the same one behind its + * sensor button. This Activity stays for the places that cannot open the plugin tab: the session + * notification, and the start and warm-up screens, which are Activities themselves. The status is + * no longer an entry of the settings, so it is not reachable there twice. */ class DexcomOnePlusStatusActivity : MetroAppCompatActivity() { - @Inject lateinit var dexcomOnePlusPlugin: DexcomOnePlusPlugin @Inject lateinit var preferences: Preferences - @Inject lateinit var profileUtil: ProfileUtil - @Inject lateinit var dateUtil: DateUtil - @Inject lateinit var rh: ResourceHelper - @Inject lateinit var persistenceLayer: PersistenceLayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Other apps may not draw over this screen: an overlay could hide what a tap really does, here on a // sensor (start, calibration, pre-soak, switch). Same as ComposeMainActivity. Needs HIDE_OVERLAY_WINDOWS. window.setHideOverlayWindows(true) - dexcomOnePlusPlugin.syncDriverFromPrefs() setContent { CompositionLocalProvider(LocalPreferences provides preferences) { AapsTheme { - DexcomOnePlusStatusScreen( - onBack = { finish() }, - onOpenStart = { - startActivity(Intent(this, DexcomOnePlusStartActivity::class.java)) - }, - onOpenWarmup = { - startActivity(Intent(this, DexcomOnePlusWarmupActivity::class.java)) - }, - onOpenLog = { - startActivity( - CgmDriverLogActivity.intent(this, setOf(OnePlusLogMarkers.TAG)) - ) - }, - stagingStateFlow = dexcomOnePlusPlugin.stagingState, - stagingEvidenceFlow = dexcomOnePlusPlugin.stagingEvidence, - lifecycleFlow = dexcomOnePlusPlugin.lifecycle, - formatGlucose = { mgdl -> profileUtil.fromMgdlToStringWithUnits(mgdl) }, - formatTime = { epochMs -> dateUtil.timeString(epochMs) }, - formatAge = { millis -> formatSensorAge(millis, rh) }, - lastGlucose = { persistenceLayer.getLastGlucoseValue() }, - onCancelStaging = { dexcomOnePlusPlugin.cancelStaging() }, - onPromote = { allowEarly -> dexcomOnePlusPlugin.promoteStagingToProduction(allowEarly) }, - isPluginStopped = { dexcomOnePlusPlugin.isStopped() }, - onCorrectSensorStart = { startMs -> dexcomOnePlusPlugin.correctProductionSensorStart(startMs) }, - ) - } - } - } - } -} - -/** How often the screen goes back to the database for the newest reading. */ -private const val GLUCOSE_REFRESH_MILLIS = 30_000L - -/** - * Text shown after Promote. Refusal means nothing was written. [PromotionResult.OkBoundFailed] - * means the exchange is kept and the calibration bound threw. [PromotionResult.OkFollowUpFailed] - * means a later step threw; the wording follows [PromotionResult.OkFollowUpFailed.productionIdentityPresent], - * which the plugin read from the production store. - */ -internal fun dexcomOnePlusPromotionMessage( - result: PromotionResult, - ok: String, - boundFailed: String, - followUpIdentityPresent: String, - followUpIdentityMissing: String, - rejectedAbsent: String, - rejectedNotSettled: String, - rejectedNoGlucose: String, - rejectedNoRecentGlucose: String, -): String = when (result) { - PromotionResult.Ok -> ok - PromotionResult.OkBoundFailed -> boundFailed - is PromotionResult.OkFollowUpFailed -> - if (result.productionIdentityPresent) followUpIdentityPresent else followUpIdentityMissing - is PromotionResult.Rejected -> when (result.reason) { - PromotionRejectReason.STAGING_ABSENT -> rejectedAbsent - PromotionRejectReason.STAGING_NOT_SETTLED -> rejectedNotSettled - PromotionRejectReason.STAGING_NO_VALID_GLUCOSE -> rejectedNoGlucose - PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE -> rejectedNoRecentGlucose - } -} - -@Composable -private fun DexcomOnePlusStatusScreen( - onBack: () -> Unit, - onOpenStart: () -> Unit, - onOpenWarmup: () -> Unit, - onOpenLog: () -> Unit, - stagingStateFlow: StateFlow, - stagingEvidenceFlow: StateFlow, - lifecycleFlow: StateFlow, - formatGlucose: (Double) -> String, - formatTime: (Long) -> String, - formatAge: (Long) -> String, - lastGlucose: suspend () -> GV?, - onCancelStaging: () -> Unit, - onPromote: suspend (Boolean) -> PromotionResult, - /** True while the plugin is switched off: Promote is then refused with a message. */ - isPluginStopped: () -> Boolean, - onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, -) { - // Not `remember`-ed: a promotion swaps which driver instance `default()` hands out (see - // OnePlusCgmDrivers.promoteStagingInstance), and a `remember`-ed reference kept polling the - // retired instance for the rest of this screen's life, showing a status stuck at whatever - // phase it had before the promotion. - var state by remember { mutableStateOf(OnePlusCgmDrivers.default().warmupState()) } - var sessionUp by remember { mutableStateOf(OnePlusCgmDrivers.default().isSessionUp()) } - var newestGlucose by remember { mutableStateOf(null) } - var calibrationOutcome by remember { mutableStateOf(null) } - var calibrationWaiting by remember { mutableStateOf(false) } - // The card exists only while values are sent to the sensor. With the setting off the value - // never leaves the phone, so there is nothing to report. The switch is on by default. - val preferences = LocalPreferences.current - val sendCalibrationToSensor = remember(preferences) { - preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor) - } - val correctSensorStartEnabled = preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart) - val stagingState by stagingStateFlow.collectAsState() - val stagingEvidence by stagingEvidenceFlow.collectAsState() - val lifecycle by lifecycleFlow.collectAsState() - val scope = rememberCoroutineScope() - var showPromoteConfirm by remember { mutableStateOf(false) } - var promoteEarly by remember { mutableStateOf(false) } - var promoteResultText by remember { mutableStateOf(null) } - var now by remember { mutableStateOf(System.currentTimeMillis()) } - // Offer the early way out only while the sensor is proving itself right now — see canPromoteEarly. - val earlyPromoteOffered = stagingState != StagingState.ABSENT && DexcomOnePlusStaging.canPromoteEarly( - validEgvCount = stagingEvidence?.validCount ?: 0, - lastValueAtEpochMs = stagingEvidence?.lastValueAtEpochMs, - nowMs = now, - ) - - // Promotion result → user message (resolved here so the coroutine has no Composable context). - val promoteOk = stringResource(R.string.dexcom_oneplus_staging_promote_ok) - val promoteBoundFailed = stringResource(R.string.dexcom_oneplus_staging_promote_bound_failed) - val promoteFollowUpFailed = stringResource(R.string.dexcom_oneplus_staging_promote_follow_up_failed) - val promoteFollowUpNoIdentity = stringResource(R.string.dexcom_oneplus_staging_promote_follow_up_failed_no_identity) - val promoteRejectedAbsent = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_absent) - val promotePluginStopped = stringResource(R.string.dexcom_oneplus_plugin_stopped) - val promoteRejectedNotSettled = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_not_settled) - val promoteRejectedNoGlucose = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_no_glucose) - val promoteRejectedNoRecentGlucose = stringResource(R.string.dexcom_oneplus_staging_promote_rejected_no_recent_glucose) - - LaunchedEffect(Unit) { - while (true) { - val driver = OnePlusCgmDrivers.default() - state = driver.warmupState() - sessionUp = driver.isSessionUp() - calibrationOutcome = driver.lastCalibrationOutcome() - calibrationWaiting = driver.calibrationPending() - now = System.currentTimeMillis() - delay(1_000L) - } - } - // A reading arrives every five minutes, so the database is asked far less often than the driver - // state is polled. - LaunchedEffect(Unit) { - while (true) { - newestGlucose = lastGlucose() - delay(GLUCOSE_REFRESH_MILLIS) - } - } - - CgmScaffold( - title = stringResource(R.string.dexcom_oneplus_status_title), - onNavigate = onBack, - actions = { - IconButton(onClick = onOpenLog) { - Icon( - imageVector = Icons.AutoMirrored.Filled.List, - contentDescription = stringResource(R.string.cgm_driver_log_open), - ) - } - }, - ) { - CgmLazyColumn { - item(key = "production") { - ProductionCard( - phaseLabel = DexcomOnePlusUiLabels.phaseLabel(state.phase), - phaseState = state.phase.toUiState(), - sessionUp = sessionUp, - message = DexcomOnePlusUiLabels.userMessage(state.message), - lifecycle = lifecycle, - newestGlucose = newestGlucose, - formatGlucose = formatGlucose, - formatTime = formatTime, - formatAge = formatAge, - correctSensorStartEnabled = correctSensorStartEnabled, - onCorrectSensorStart = onCorrectSensorStart, - ) - } - if (sendCalibrationToSensor) { - item(key = "sensorCalibration") { - SensorCalibrationCard( - outcome = calibrationOutcome, - waiting = calibrationWaiting, - driverMessage = state.message, - ) - } - } - // Prompt for a pre-soak exactly when it is useful: the sensor in use is near its end and - // no replacement is warming up yet. - if (lifecycle?.endOfLife == true && stagingState == StagingState.ABSENT) { - item(key = "endOfLife") { - CgmCard(tone = CgmCardTone.Warning) { - CgmCardHeader(stringResource(R.string.dexcom_oneplus_end_of_life_title)) - Text( - text = stringResource(R.string.dexcom_oneplus_end_of_life_text), - style = MaterialTheme.typography.bodyMedium, + val viewModel: DexcomOnePlusStatusViewModel = metroViewModel() + val actions = remember { + DexcomOnePlusStatusActions( + onOpenStart = { startActivity(Intent(this, DexcomOnePlusStartActivity::class.java)) }, + onOpenWarmup = { startActivity(Intent(this, DexcomOnePlusWarmupActivity::class.java)) }, + // The full driver log window, as before. + onOpenLog = { startActivity(CgmDriverLogActivity.intent(this, setOf(OnePlusLogMarkers.TAG))) }, ) - OutlinedButton(onClick = onOpenStart) { - Text(stringResource(R.string.dexcom_oneplus_start_presoak)) - } - } - } - } - item(key = "staging") { - StagingCard( - stagingState = stagingState, - stagingEvidence = stagingEvidence, - earlyPromoteOffered = earlyPromoteOffered, - formatGlucose = formatGlucose, - formatTime = formatTime, - onPromoteClick = { early -> - promoteEarly = early - showPromoteConfirm = true - }, - onCancelStaging = { - onCancelStaging() - promoteResultText = null - }, - onOpenStart = onOpenStart, - ) - } - promoteResultText?.let { message -> - item(key = "promoteResult") { - Text( - text = message, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - item(key = "actions") { - CgmCard { - CgmCardHeader(stringResource(R.string.cgm_actions_heading)) - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(AapsSpacing.medium), - ) { - OutlinedButton(onClick = onOpenStart, modifier = Modifier.weight(1f)) { - Text(stringResource(R.string.dexcom_oneplus_start_action)) - } - OutlinedButton(onClick = onOpenWarmup, modifier = Modifier.weight(1f)) { - Text(stringResource(R.string.dexcom_oneplus_step_warmup)) - } - } - OutlinedButton(onClick = onOpenLog, modifier = Modifier.fillMaxWidth()) { - Text(stringResource(R.string.cgm_driver_log_open)) } - } - } - } - } - - if (showPromoteConfirm) { - AlertDialog( - onDismissRequest = { showPromoteConfirm = false }, - title = { - Text( - if (promoteEarly) stringResource(R.string.dexcom_oneplus_staging_promote_early_confirm_title) - else stringResource(R.string.dexcom_oneplus_staging_promote_confirm_title), - ) - }, - text = { - Text( - if (promoteEarly) stringResource(R.string.dexcom_oneplus_staging_promote_early_confirm_message) - else stringResource(R.string.dexcom_oneplus_staging_promote_confirm_message), - ) - }, - confirmButton = { - TextButton( - onClick = { - showPromoteConfirm = false - val allowEarly = promoteEarly - if (isPluginStopped()) { - promoteResultText = promotePluginStopped - return@TextButton - } - scope.launch { - promoteResultText = dexcomOnePlusPromotionMessage( - result = onPromote(allowEarly), - ok = promoteOk, - boundFailed = promoteBoundFailed, - followUpIdentityPresent = promoteFollowUpFailed, - followUpIdentityMissing = promoteFollowUpNoIdentity, - rejectedAbsent = promoteRejectedAbsent, - rejectedNotSettled = promoteRejectedNotSettled, - rejectedNoGlucose = promoteRejectedNoGlucose, - rejectedNoRecentGlucose = promoteRejectedNoRecentGlucose, - ) - } - }, - ) { - Text(stringResource(R.string.dexcom_oneplus_staging_promote_confirm)) - } - }, - dismissButton = { - TextButton(onClick = { showPromoteConfirm = false }) { - Text(stringResource(R.string.dexcom_oneplus_staging_promote_dismiss)) - } - }, - ) - } -} - -/** - * The sensor that feeds the loop: [DexcomOnePlusProductionCard], with the "correct insertion date" - * action under it. - */ -@Composable -private fun ProductionCard( - phaseLabel: String, - phaseState: CgmUiState, - sessionUp: Boolean, - message: String, - lifecycle: CgmSensorLifecycle?, - newestGlucose: GV?, - formatGlucose: (Double) -> String, - formatTime: (Long) -> String, - formatAge: (Long) -> String, - correctSensorStartEnabled: Boolean, - onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, -) { - DexcomOnePlusProductionCard( - phaseLabel = phaseLabel, - phaseState = phaseState, - sessionUp = sessionUp, - message = message, - lifecycle = lifecycle, - newestGlucose = newestGlucose, - formatGlucose = formatGlucose, - formatTime = formatTime, - formatAge = formatAge, - ) { - // Hidden while the setting is off. The function also refuses before any write. - if (correctSensorStartEnabled) { - lifecycle?.startedAtEpochMs?.let { startedAt -> - CorrectInsertionDateAction( - currentStartMs = startedAt, - formatTime = formatTime, - onCorrectSensorStart = onCorrectSensorStart, - ) - } - } - } -} - -/** - * "The sensor went in earlier than the app thinks." - * - * Shown only while [DexcomOnePlusBooleanKey.CorrectSensorStart] is on. - */ -@Composable -private fun CorrectInsertionDateAction( - currentStartMs: Long, - formatTime: (Long) -> String, - onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, -) { - val scope = rememberCoroutineScope() - var showDatePicker by remember { mutableStateOf(false) } - var pickedDateMs by remember { mutableStateOf(null) } - var refusal by remember { mutableStateOf(null) } - - OutlinedButton(onClick = { showDatePicker = true }) { - Text(stringResource(R.string.dexcom_oneplus_correct_insertion_date)) - } - - if (showDatePicker) { - DatePickerModal( - initialDateMillis = currentStartMs, - onDateSelected = { pickedDateMs = it }, - onDismiss = { showDatePicker = false }, - ) - } - pickedDateMs?.let { dayMs -> - val current = remember(currentStartMs) { Calendar.getInstance().apply { timeInMillis = currentStartMs } } - TimePickerModal( - initialHour = current.get(Calendar.HOUR_OF_DAY), - initialMinute = current.get(Calendar.MINUTE), - onTimeSelected = { hour, minute -> - val day = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { timeInMillis = dayMs } - val chosen = Calendar.getInstance().apply { - set(day.get(Calendar.YEAR), day.get(Calendar.MONTH), day.get(Calendar.DAY_OF_MONTH), hour, minute, 0) - set(Calendar.MILLISECOND, 0) - } - scope.launch { - val verdict = onCorrectSensorStart(chosen.timeInMillis) - if (verdict != DexcomOnePlusSensorStartCorrection.Verdict.Accepted) refusal = verdict - } - }, - onDismiss = { pickedDateMs = null }, - ) - } - refusal?.let { verdict -> - AlertDialog( - onDismissRequest = { refusal = null }, - title = { Text(stringResource(R.string.dexcom_oneplus_correct_insertion_date)) }, - text = { - Text( - stringResource( - when (verdict) { - DexcomOnePlusSensorStartCorrection.Verdict.InFuture -> - R.string.dexcom_oneplus_insertion_date_future - DexcomOnePlusSensorStartCorrection.Verdict.TooOld -> - R.string.dexcom_oneplus_insertion_date_too_old - DexcomOnePlusSensorStartCorrection.Verdict.Accepted, - DexcomOnePlusSensorStartCorrection.Verdict.NoSession, - DexcomOnePlusSensorStartCorrection.Verdict.Disabled, - -> R.string.dexcom_oneplus_insertion_date_no_session + CgmScaffold( + title = stringResource(R.string.dexcom_oneplus_status_title), + onNavigate = { finish() }, + actions = { + IconButton(onClick = actions.onOpenLog) { + Icon( + imageVector = Icons.AutoMirrored.Filled.List, + contentDescription = stringResource(R.string.cgm_driver_log_open), + ) + } }, - formatTime(currentStartMs), - ), - ) - }, - confirmButton = { - TextButton(onClick = { refusal = null }) { Text(coreStringResource(CoreUiStrings.ok)) } - }, - ) - } -} - -/** - * What became of a finger prick value handed to the sensor itself. - * - * On screen only while [DexcomOnePlusBooleanKey.SendCalibrationToSensor] is on, which is the - * default. The texts come from [DexcomOnePlusCalibrationText]. - * - * [OnePlusCalibrationOutcome.Unknown] is not softened: the value was written and the answer was - * lost or unreadable, so it is neither a failure of the app nor a success. - * [OnePlusCalibrationOutcome.NotSent] says the opposite: nothing reached the sensor, and the value - * may be entered again. - */ -@Composable -private fun SensorCalibrationCard( - outcome: OnePlusCalibrationOutcome?, - waiting: Boolean, - driverMessage: String?, -) { - val warning = outcome is OnePlusCalibrationOutcome.Refused || outcome is OnePlusCalibrationOutcome.NotSent - val tone = if (warning) CgmCardTone.Warning else CgmCardTone.Neutral - CgmCard(tone = tone) { - CgmCardHeader(stringResource(R.string.dexcom_oneplus_calibration_heading)) - sensorCalibrationRequest(driverMessage)?.let { request -> - Text( - text = request, - style = MaterialTheme.typography.bodyMedium, - ) - } - Text( - text = coreStringResource(DexcomOnePlusCalibrationText.status(outcome, waiting)), - style = MaterialTheme.typography.bodyMedium, - ) - if (!waiting && outcome is OnePlusCalibrationOutcome.NotSent) { - Text( - text = coreStringResource(DexcomOnePlusCalibrationText.notSentReason(outcome.reason)), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - val detail = when (outcome) { - is OnePlusCalibrationOutcome.Accepted -> outcome.detail - is OnePlusCalibrationOutcome.Refused -> outcome.detail - is OnePlusCalibrationOutcome.Unknown -> outcome.detail - else -> null - } - detail?.takeIf { it.isNotBlank() }?.let { text -> - Text( - text = stringResource(R.string.dexcom_oneplus_calibration_detail, text), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} - -/** - * What the sensor itself is asking for, read back out of the driver status line. - * - * Null when the line is about something else, which it is most of the time. - */ -@Composable -private fun sensorCalibrationRequest(driverMessage: String?): String? { - val state = OnePlusCalibrationState.entries.firstOrNull { it.name == driverMessage } ?: return null - return when (state) { - OnePlusCalibrationState.NeedsCalibration -> - stringResource(R.string.dexcom_oneplus_calibration_state_needs) - OnePlusCalibrationState.NeedsFirstCalibration -> - stringResource(R.string.dexcom_oneplus_calibration_state_needs_first) - OnePlusCalibrationState.NeedsSecondCalibration -> - stringResource(R.string.dexcom_oneplus_calibration_state_needs_second) - OnePlusCalibrationState.CalibrationSent -> - stringResource(R.string.dexcom_oneplus_calibration_state_sent) - else -> null - } -} - -/** - * The collect-only second sensor. - * - * Promotion stays the only full width button in the card it belongs to, so it does not compete with - * the navigation buttons that used to sit above it at the same visual weight. - */ -@Composable -private fun StagingCard( - stagingState: StagingState, - stagingEvidence: CgmStagingEvidence?, - earlyPromoteOffered: Boolean, - formatGlucose: (Double) -> String, - formatTime: (Long) -> String, - onPromoteClick: (Boolean) -> Unit, - onCancelStaging: () -> Unit, - onOpenStart: () -> Unit, -) { - val stagingStateLabel = when (stagingState) { - StagingState.ABSENT -> stringResource(R.string.dexcom_oneplus_staging_state_absent) - StagingState.WARMUP -> stringResource(R.string.dexcom_oneplus_staging_state_warmup) - StagingState.SETTLING -> stringResource(R.string.dexcom_oneplus_staging_state_settling) - StagingState.READY -> stringResource(R.string.dexcom_oneplus_staging_state_ready) - } - CgmCard { - CgmCardHeader(stringResource(R.string.dexcom_oneplus_staging_heading_short)) { - CgmStateChip(state = stagingState.toUiState(), label = stagingStateLabel) - } - if (stagingState == StagingState.ABSENT) { - // An empty state that explains what the slot is for and offers the way in, instead of - // just reporting "None". - Text( - text = stringResource(R.string.dexcom_oneplus_staging_none_short), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - OutlinedButton(onClick = onOpenStart) { - Text(stringResource(R.string.dexcom_oneplus_start_presoak)) - } - } else { - CgmStepTimeline( - labels = listOf( - stringResource(R.string.dexcom_oneplus_staging_state_warmup), - stringResource(R.string.dexcom_oneplus_staging_state_settling), - stringResource(R.string.dexcom_oneplus_staging_state_ready), - ), - reached = when (stagingState) { - StagingState.ABSENT -> -1 - StagingState.WARMUP -> 0 - StagingState.SETTLING -> 1 - StagingState.READY -> 2 - }, - ) - // Evidence the staging sensor is really alive: without it the user only sees a state - // label and cannot tell "settling with data" from "settling with a dead radio". - CgmKeyValueRow( - label = stringResource(R.string.dexcom_oneplus_staging_readings_label), - value = (stagingEvidence?.validCount ?: 0).toString(), - ) - val lastValue = stagingEvidence?.lastValueMgdl - val lastAt = stagingEvidence?.lastValueAtEpochMs - if (lastValue != null && lastAt != null) { - CgmKeyValueRow( - label = stringResource(R.string.dexcom_oneplus_staging_last_label), - value = stringResource( - R.string.dexcom_oneplus_staging_last_reading, - formatGlucose(lastValue), - formatTime(lastAt), - ), - ) - } else { - Text( - text = stringResource(R.string.dexcom_oneplus_staging_no_reading_yet), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - if (stagingState == StagingState.READY) { - Button( - onClick = { onPromoteClick(false) }, - modifier = Modifier.fillMaxWidth(), - ) { - Text(stringResource(R.string.dexcom_oneplus_staging_promote)) - } - } else if (earlyPromoteOffered) { - // Way out when the production sensor stops before the soak ends. Deliberately an - // outlined button with its own warning dialog: it gives up sensor quality, so it - // must never look like the normal path. - Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.small)) { - OutlinedButton( - onClick = { onPromoteClick(true) }, - modifier = Modifier.fillMaxWidth(), ) { - Text(stringResource(R.string.dexcom_oneplus_staging_promote_early)) + DexcomOnePlusStatusOverview(viewModel = viewModel, actions = actions) } - Text( - text = stringResource(R.string.dexcom_oneplus_staging_promote_early_hint), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) } } - TextButton(onClick = onCancelStaging, modifier = Modifier.fillMaxWidth()) { - Text(stringResource(R.string.dexcom_oneplus_staging_cancel)) - } } } } diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CameraApplicatorScanner.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CameraApplicatorScanner.kt new file mode 100644 index 000000000000..4c5d1f48facc --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/CameraApplicatorScanner.kt @@ -0,0 +1,185 @@ +package app.aaps.plugins.source.compose + +import android.Manifest +import android.content.pm.PackageManager +import android.util.Size +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.camera.core.CameraSelector +import androidx.camera.core.ImageAnalysis +import androidx.camera.core.ImageProxy +import androidx.camera.core.Preview +import androidx.camera.core.resolutionselector.ResolutionSelector +import androidx.camera.core.resolutionselector.ResolutionStrategy +import androidx.camera.lifecycle.ProcessCameraProvider +import androidx.camera.view.PreviewView +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.viewinterop.AndroidView +import androidx.core.content.ContextCompat +import androidx.lifecycle.compose.LocalLifecycleOwner +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.SourceStrings +import com.google.zxing.BarcodeFormat +import com.google.zxing.BinaryBitmap +import com.google.zxing.DecodeHintType +import com.google.zxing.MultiFormatReader +import com.google.zxing.NotFoundException +import com.google.zxing.PlanarYUVLuminanceSource +import com.google.zxing.common.HybridBinarizer +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean + +/** + * The applicator scanner on Android: a CameraX preview, each frame read by ZXing. + * + * Built the same way as the client set-up QR scanner of `:plugins:sync`, which already runs + * without Google Play services. The camera permission is asked here, the first time the scan + * opens, and not in the setup wizard: only a person who scans needs it. + */ +object CameraApplicatorScanner : OnePlusApplicatorScanner { + + @Composable + override fun CameraView(onScanned: (String) -> Boolean, modifier: Modifier) { + val context = LocalContext.current + var granted by remember { + mutableStateOf(ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) + } + var refused by remember { mutableStateOf(false) } + val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { allowed -> + granted = allowed + refused = !allowed + } + LaunchedEffect(Unit) { if (!granted) launcher.launch(Manifest.permission.CAMERA) } + + if (granted) { + CameraPreview(onScanned = onScanned, modifier = modifier) + } else { + Box(modifier = modifier.padding(AapsSpacing.xxLarge), contentAlignment = Alignment.Center) { + if (refused) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large), + ) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_applicator_scan_camera_refused), + style = MaterialTheme.typography.bodyMedium, + textAlign = TextAlign.Center, + ) + Button(onClick = { launcher.launch(Manifest.permission.CAMERA) }) { + Text(stringResource(SourceStrings.dexcom_oneplus_applicator_scan_retry)) + } + } + } + } + } + } +} + +@Composable +private fun CameraPreview(onScanned: (String) -> Boolean, modifier: Modifier) { + val lifecycleOwner = LocalLifecycleOwner.current + val currentOnScanned by rememberUpdatedState(onScanned) + val analysisExecutor: ExecutorService = remember { Executors.newSingleThreadExecutor() } + // Set once a code was taken, so the frames still in flight do not deliver it a second time. + val done = remember { AtomicBoolean(false) } + var cameraProvider by remember { mutableStateOf(null) } + DisposableEffect(Unit) { + onDispose { + cameraProvider?.unbindAll() + analysisExecutor.shutdown() + } + } + AndroidView( + modifier = modifier, + factory = { viewContext -> + val previewView = PreviewView(viewContext).apply { scaleType = PreviewView.ScaleType.FILL_CENTER } + val mainExecutor = ContextCompat.getMainExecutor(viewContext) + val providerFuture = ProcessCameraProvider.getInstance(viewContext) + providerFuture.addListener({ + val provider = providerFuture.get() + cameraProvider = provider + val preview = Preview.Builder().build().also { it.surfaceProvider = previewView.surfaceProvider } + val analysis = ImageAnalysis.Builder() + .setResolutionSelector( + ResolutionSelector.Builder() + .setResolutionStrategy(ResolutionStrategy(Size(1280, 720), ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER)) + .build() + ) + .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST) + .build() + .also { analysis -> + analysis.setAnalyzer(analysisExecutor, ApplicatorCodeAnalyzer { text -> + mainExecutor.execute { + if (!done.get() && currentOnScanned(text)) done.set(true) + } + }) + } + provider.unbindAll() + provider.bindToLifecycle(lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, analysis) + }, mainExecutor) + previewView + } + ) +} + +/** + * Looks for the applicator code in the brightness plane of each camera frame. Runs on the + * analysis thread. + * + * The applicator carries a GS1 Data Matrix. QR is read as well, so a code that was printed again + * as a QR code still works; the start screen checks the text with the parser either way. + */ +private class ApplicatorCodeAnalyzer(private val onDecoded: (String) -> Unit) : ImageAnalysis.Analyzer { + + private val reader = MultiFormatReader().apply { + setHints( + mapOf( + DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.DATA_MATRIX, BarcodeFormat.QR_CODE), + DecodeHintType.TRY_HARDER to true, + ) + ) + } + + override fun analyze(image: ImageProxy) { + try { + val plane = image.planes.firstOrNull() ?: return + val buffer = plane.buffer.duplicate().apply { rewind() } + // The last row is often shorter than the stride, so the block is padded to full rows. + val bytes = ByteArray(plane.rowStride * image.height) + buffer.get(bytes, 0, minOf(buffer.remaining(), bytes.size)) + val source = PlanarYUVLuminanceSource(bytes, plane.rowStride, image.height, 0, 0, image.width, image.height, false) + val text = try { + reader.decodeWithState(BinaryBitmap(HybridBinarizer(source))).text + } catch (_: NotFoundException) { + null + } finally { + reader.reset() + } + if (!text.isNullOrEmpty()) onDecoded(text) + } catch (_: Exception) { + // A frame that cannot be read (a damaged code, a checksum error): the next frame is tried. + } finally { + image.close() + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusComposeContent.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusComposeContent.kt new file mode 100644 index 000000000000..89d02f2ba7f1 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusComposeContent.kt @@ -0,0 +1,153 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.RowScope +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Share +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.navigationevent.NavigationEventInfo +import androidx.navigationevent.compose.NavigationBackHandler +import androidx.navigationevent.compose.rememberNavigationEventState +import app.aaps.core.ui.CoreUiStrings +import app.aaps.core.ui.compose.ComposablePluginContent +import app.aaps.core.ui.compose.ToolbarConfig +import app.aaps.core.ui.compose.icons.IcPluginByoda +import app.aaps.core.ui.compose.metroViewModel +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.DexcomOnePlusHost +import app.aaps.plugins.source.SourceStrings + +/** How much text a share may carry, so a long session cannot break the send. */ +private const val MAX_SHARED_CHARACTERS = 200_000 + +/** The screens of the ONE+ / G7 plugin tab. */ +private enum class DexcomOnePlusTabScreen { READINGS, STATUS, LOG } + +/** + * The plugin tab of the native Dexcom ONE+ / G7 source. + * + * It opens on the readings list every BG source shows. A sensor button in its toolbar opens the + * sensor status, and the status leads on to the driver log. Back, the toolbar arrow or the system + * gesture, goes up one screen. Starting a sensor and the warm-up countdown are opened through + * [DexcomOnePlusHost.openScreen], because those screens are Activities of their own. + */ +internal class DexcomOnePlusComposeContent( + private val title: String, +) : ComposablePluginContent { + + @Composable + override fun Render( + setToolbarConfig: (ToolbarConfig) -> Unit, + onNavigateBack: () -> Unit, + onSettings: (() -> Unit)?, + ) { + var screen by remember { mutableStateOf(DexcomOnePlusTabScreen.READINGS) } + val sensorLabel = stringResource(SourceStrings.dexcom_oneplus_status_title) + val readings = remember(title) { + BgSourceComposeContent(title = title) { + IconButton(onClick = { screen = DexcomOnePlusTabScreen.STATUS }) { + Icon(IcPluginByoda, contentDescription = sensorLabel) + } + } + } + + when (screen) { + DexcomOnePlusTabScreen.READINGS -> readings.Render(setToolbarConfig, onNavigateBack, onSettings) + + DexcomOnePlusTabScreen.STATUS -> { + val viewModel: DexcomOnePlusStatusViewModel = metroViewModel() + val actions = remember(viewModel) { + DexcomOnePlusStatusActions( + onOpenStart = { viewModel.host.openScreen(DexcomOnePlusHost.Screen.START) }, + onOpenWarmup = { viewModel.host.openScreen(DexcomOnePlusHost.Screen.WARMUP) }, + onOpenLog = { screen = DexcomOnePlusTabScreen.LOG }, + ) + } + val backLabel = stringResource(CoreUiStrings.back) + val settingsLabel = stringResource(CoreUiStrings.settings) + LaunchedEffect(Unit) { + setToolbarConfig( + ToolbarConfig( + title = sensorLabel, + navigationIcon = { + IconButton(onClick = { screen = DexcomOnePlusTabScreen.READINGS }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = backLabel) + } + }, + actions = settingsAction(onSettings, settingsLabel), + ), + ) + } + BackToScreen { screen = DexcomOnePlusTabScreen.READINGS } + DexcomOnePlusStatusOverview(viewModel = viewModel, actions = actions) + } + + DexcomOnePlusTabScreen.LOG -> { + val viewModel: DexcomOnePlusStatusViewModel = metroViewModel() + val host = viewModel.host + var reloads by remember { mutableIntStateOf(0) } + var lines by remember { mutableStateOf(emptyList()) } + val logTitle = stringResource(SourceStrings.cgm_driver_log_title) + val backLabel = stringResource(CoreUiStrings.back) + val refreshLabel = stringResource(SourceStrings.cgm_driver_log_refresh) + val shareLabel = stringResource(SourceStrings.cgm_driver_log_share) + LaunchedEffect(Unit) { + setToolbarConfig( + ToolbarConfig( + title = logTitle, + navigationIcon = { + IconButton(onClick = { screen = DexcomOnePlusTabScreen.STATUS }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = backLabel) + } + }, + actions = { + IconButton(onClick = { reloads++ }) { + Icon(Icons.Filled.Refresh, contentDescription = refreshLabel) + } + IconButton( + enabled = lines.isNotEmpty(), + onClick = { host.shareLog(lines.joinToString("\n").takeLast(MAX_SHARED_CHARACTERS)) }, + ) { + Icon(Icons.Filled.Share, contentDescription = shareLabel) + } + }, + ), + ) + } + BackToScreen { screen = DexcomOnePlusTabScreen.STATUS } + DexcomOnePlusLogScreen(host = host, reloads = reloads, onLinesChanged = { lines = it }) + } + } + } + + private fun settingsAction(onSettings: (() -> Unit)?, label: String): @Composable RowScope.() -> Unit = { + onSettings?.let { action -> + IconButton(onClick = action) { + Icon(Icons.Filled.Settings, contentDescription = label) + } + } + } +} + +/** + * The system back gesture goes one screen up inside the tab, the same way the toolbar arrow does, + * instead of leaving the plugin. + */ +@Composable +private fun BackToScreen(onBack: () -> Unit) { + NavigationBackHandler( + state = rememberNavigationEventState(NavigationEventInfo.None), + isBackEnabled = true, + onBackCompleted = onBack, + ) +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusLogScreen.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusLogScreen.kt new file mode 100644 index 000000000000..ad1a9c2114f2 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusLogScreen.kt @@ -0,0 +1,102 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontFamily +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.DexcomOnePlusHost +import app.aaps.plugins.source.SourceStrings +import kotlinx.coroutines.delay + +/** How often the log screen reads the lines again while it is open. */ +private const val LOG_REFRESH_MILLIS = 5_000L + +/** + * What the ONE+ / G7 driver wrote, read only. + * + * The lines come from [DexcomOnePlusHost.driverLog], the driver lines of `AndroidAPS.log`. + * [DexcomOnePlusHost.DriverLog.note] says where they come from, so a person knows what they are + * reading. The screen follows the end of the log while + * the person is there and stops following once they scroll up. + * + * [reloads] is bumped by the refresh button in the toolbar. + */ +@Composable +fun DexcomOnePlusLogScreen( + host: DexcomOnePlusHost, + reloads: Int, + onLinesChanged: (List) -> Unit, + modifier: Modifier = Modifier, +) { + var log by remember { mutableStateOf(null) } + val listState = rememberLazyListState() + + LaunchedEffect(reloads) { + while (true) { + val read = host.driverLog() + log = read + onLinesChanged(read.lines) + delay(LOG_REFRESH_MILLIS) + } + } + val lines = log?.lines.orEmpty() + LaunchedEffect(lines.size) { + val last = listState.layoutInfo.visibleItemsInfo.lastOrNull()?.index + val following = last == null || last >= lines.size - 3 + if (following && lines.isNotEmpty()) listState.scrollToItem(lines.lastIndex) + } + + Column( + modifier = modifier + .fillMaxSize() + .padding(horizontal = AapsSpacing.medium), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.small), + ) { + log?.let { current -> + Text( + text = stringResource(current.note), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + if (lines.isEmpty()) { + Text(stringResource(SourceStrings.cgm_driver_log_empty)) + } else { + Text( + text = stringResource(SourceStrings.cgm_driver_log_count, lines.size), + style = MaterialTheme.typography.labelMedium, + ) + SelectionContainer { + LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { + items(lines) { line -> + // Long lines wrap rather than run off the side: a driver line can be a + // whole hex frame, and a phone is narrow. + Text( + text = line, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + modifier = Modifier.fillMaxWidth(), + ) + } + } + } + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt index 9e3e5f45de83..8e88ea581f60 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStartScreen.kt @@ -106,6 +106,11 @@ fun DexcomOnePlusStartScreen( * Called with (MAC of the started sensor, MAC stored before this start). */ onSensorSessionStarted: (String, String?) -> Unit, + /** + * Reads the applicator barcode with the camera, or null when the screen offers no camera scan. + * Null leaves the scan button out, so the code is typed. + */ + applicatorScanner: OnePlusApplicatorScanner?, ) { val window = rememberCgmWindow() val scope = rememberCoroutineScope() @@ -415,6 +420,7 @@ fun DexcomOnePlusStartScreen( errorText = errorText, serialNone = serialNone, storedMac = storedSession?.lastMac, + applicatorScanner = applicatorScanner, onApplicatorChange = { text -> applicatorInput = text parsedIdentity = OnePlusGs1ApplicatorParser.parse(text) @@ -474,6 +480,7 @@ fun DexcomOnePlusStartScreen( errorText = errorText, serialNone = serialNone, storedMac = storedSession?.lastMac, + applicatorScanner = applicatorScanner, onApplicatorChange = { text -> applicatorInput = text parsedIdentity = OnePlusGs1ApplicatorParser.parse(text) @@ -576,8 +583,10 @@ private fun ColumnScope.FormPane( errorText: String?, serialNone: String, storedMac: String?, + applicatorScanner: OnePlusApplicatorScanner?, onApplicatorChange: (String) -> Unit, ) { + var scanning by remember { mutableStateOf(false) } CgmStepper( currentStep = currentStep, labels = listOf( @@ -650,6 +659,21 @@ private fun ColumnScope.FormPane( minLines = 2, isError = errorText != null && parsedIdentity == null, ) + applicatorScanner?.let { scanner -> + OutlinedButton(onClick = { scanning = true }, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(SourceStrings.dexcom_oneplus_applicator_scan)) + } + if (scanning) { + OnePlusApplicatorScanDialog( + scanner = scanner, + onCode = { code -> + scanning = false + onApplicatorChange(code) + }, + onDismiss = { scanning = false }, + ) + } + } storedMac?.let { mac -> Text( text = stringResource(SourceStrings.dexcom_oneplus_last_mac_hint, mac), diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusOverview.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusOverview.kt new file mode 100644 index 000000000000..97f9e51065d9 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusOverview.kt @@ -0,0 +1,362 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +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.compose.ui.Modifier +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.ui.CoreUiStrings +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.dialogs.DatePickerModal +import app.aaps.core.ui.compose.dialogs.TimePickerModal +import app.aaps.core.ui.compose.pump.PumpOverviewScreen +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection +import app.aaps.plugins.source.SourceStrings +import kotlinx.coroutines.launch +import java.util.Calendar +import java.util.TimeZone + +/** + * The ONE+ / G7 status screen body. + * + * It is the shared pump overview: a banner with the phase, the facts of the sensor that feeds the + * loop, and the buttons to start a sensor, follow the warm-up and read the driver log. Below the + * facts come the cards the status screen always had: the "correct insertion date" action, + * calibration, end of life, and the pre-soak sensor with its Promote button. + * + * No frame of its own: the plugin tab gives it the toolbar, and the status Activity wraps it in + * `CgmScaffold`. + */ +@Composable +fun DexcomOnePlusStatusOverview( + viewModel: DexcomOnePlusStatusViewModel, + actions: DexcomOnePlusStatusActions, + modifier: Modifier = Modifier, +) { + val input by viewModel.input.collectAsState() + val promoteResult by viewModel.promoteResult.collectAsState() + val current = input ?: return + val view = remember(current, actions) { DexcomOnePlusStatusState.build(current, viewModel.format, actions) } + var promoteAsked by remember { mutableStateOf(null) } + + PumpOverviewScreen( + state = view.overview, + modifier = modifier, + customContent = { + Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium)) { + view.correctInsertionStartMs?.let { startedAt -> + CorrectInsertionDateAction( + currentStartMs = startedAt, + formatTime = viewModel.format.time, + onCorrectSensorStart = { viewModel.correctSensorStart(it) }, + ) + } + view.calibration?.let { SensorCalibrationCard(it) } + if (view.endOfLifePrompt) EndOfLifeCard(onOpenStart = actions.onOpenStart) + StagingCard( + card = view.staging, + formatGlucose = viewModel.format.glucose, + formatTime = viewModel.format.time, + onPromoteClick = { early -> promoteAsked = early }, + onCancelStaging = { viewModel.cancelStaging() }, + onOpenStart = actions.onOpenStart, + ) + promoteResult?.let { message -> + Text( + text = stringResource(message), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + }, + ) + + promoteAsked?.let { early -> + PromoteConfirmDialog( + early = early, + onConfirm = { + promoteAsked = null + viewModel.promote(early) + }, + onDismiss = { promoteAsked = null }, + ) + } +} + +@Composable +private fun PromoteConfirmDialog(early: Boolean, onConfirm: () -> Unit, onDismiss: () -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + stringResource( + if (early) SourceStrings.dexcom_oneplus_staging_promote_early_confirm_title + else SourceStrings.dexcom_oneplus_staging_promote_confirm_title, + ), + ) + }, + text = { + Text( + stringResource( + if (early) SourceStrings.dexcom_oneplus_staging_promote_early_confirm_message + else SourceStrings.dexcom_oneplus_staging_promote_confirm_message, + ), + ) + }, + confirmButton = { + TextButton(onClick = onConfirm) { Text(stringResource(SourceStrings.dexcom_oneplus_staging_promote_confirm)) } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text(stringResource(SourceStrings.dexcom_oneplus_staging_promote_dismiss)) } + }, + ) +} + +/** The sensor in use is near its end and no replacement is warming up yet. */ +@Composable +private fun EndOfLifeCard(onOpenStart: () -> Unit) { + CgmCard(tone = CgmCardTone.Warning) { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_end_of_life_title)) + Text( + text = stringResource(SourceStrings.dexcom_oneplus_end_of_life_text), + style = MaterialTheme.typography.bodyMedium, + ) + OutlinedButton(onClick = onOpenStart) { + Text(stringResource(SourceStrings.dexcom_oneplus_start_presoak)) + } + } +} + +/** + * "The sensor went in earlier than the app thinks." + * + * Shown only while `DexcomOnePlusBooleanKey.CorrectSensorStart` is on. The picked day comes from + * the date picker as UTC midnight; the time is the phone's local time, as on the old status screen. + */ +@Composable +private fun CorrectInsertionDateAction( + currentStartMs: Long, + formatTime: (Long) -> String, + onCorrectSensorStart: suspend (Long) -> DexcomOnePlusSensorStartCorrection.Verdict, +) { + val scope = rememberCoroutineScope() + var showDatePicker by remember { mutableStateOf(false) } + var pickedDateMs by remember { mutableStateOf(null) } + var refusal by remember { mutableStateOf(null) } + + OutlinedButton(onClick = { showDatePicker = true }) { + Text(stringResource(SourceStrings.dexcom_oneplus_correct_insertion_date)) + } + + if (showDatePicker) { + DatePickerModal( + initialDateMillis = currentStartMs, + onDateSelected = { pickedDateMs = it }, + onDismiss = { showDatePicker = false }, + ) + } + pickedDateMs?.let { dayMs -> + val current = remember(currentStartMs) { Calendar.getInstance().apply { timeInMillis = currentStartMs } } + TimePickerModal( + initialHour = current.get(Calendar.HOUR_OF_DAY), + initialMinute = current.get(Calendar.MINUTE), + onTimeSelected = { hour, minute -> + val day = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply { timeInMillis = dayMs } + val chosen = Calendar.getInstance().apply { + set(day.get(Calendar.YEAR), day.get(Calendar.MONTH), day.get(Calendar.DAY_OF_MONTH), hour, minute, 0) + set(Calendar.MILLISECOND, 0) + } + scope.launch { + val verdict = onCorrectSensorStart(chosen.timeInMillis) + if (verdict != DexcomOnePlusSensorStartCorrection.Verdict.Accepted) refusal = verdict + } + }, + onDismiss = { pickedDateMs = null }, + ) + } + refusal?.let { verdict -> + AlertDialog( + onDismissRequest = { refusal = null }, + title = { Text(stringResource(SourceStrings.dexcom_oneplus_correct_insertion_date)) }, + text = { + Text( + stringResource( + when (verdict) { + DexcomOnePlusSensorStartCorrection.Verdict.InFuture -> + SourceStrings.dexcom_oneplus_insertion_date_future + DexcomOnePlusSensorStartCorrection.Verdict.TooOld -> + SourceStrings.dexcom_oneplus_insertion_date_too_old + DexcomOnePlusSensorStartCorrection.Verdict.Accepted, + DexcomOnePlusSensorStartCorrection.Verdict.NoSession, + DexcomOnePlusSensorStartCorrection.Verdict.Disabled, + -> SourceStrings.dexcom_oneplus_insertion_date_no_session + }, + formatTime(currentStartMs), + ), + ) + }, + confirmButton = { + TextButton(onClick = { refusal = null }) { Text(stringResource(CoreUiStrings.ok)) } + }, + ) + } +} + +/** What became of a finger prick value handed to the sensor itself. */ +@Composable +private fun SensorCalibrationCard(card: DexcomOnePlusCalibrationCard) { + CgmCard(tone = if (card.warning) CgmCardTone.Warning else CgmCardTone.Neutral) { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_calibration_heading)) + card.request?.let { request -> + Text(text = stringResource(request), style = MaterialTheme.typography.bodyMedium) + } + Text(text = stringResource(card.outcome), style = MaterialTheme.typography.bodyMedium) + card.notSentReason?.let { reason -> + Text( + text = stringResource(reason), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + card.detail?.let { detail -> + Text( + text = stringResource(SourceStrings.dexcom_oneplus_calibration_detail, detail), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** + * The collect-only second sensor. + * + * Promotion stays the only full width button in the card it belongs to, so it does not compete with + * the buttons of the screen at the same visual weight. + */ +@Composable +private fun StagingCard( + card: DexcomOnePlusStagingCard, + formatGlucose: (Double) -> String, + formatTime: (Long) -> String, + onPromoteClick: (Boolean) -> Unit, + onCancelStaging: () -> Unit, + onOpenStart: () -> Unit, +) { + val stateLabel = stringResource( + when (card.state) { + StagingState.ABSENT -> SourceStrings.dexcom_oneplus_staging_state_absent + StagingState.WARMUP -> SourceStrings.dexcom_oneplus_staging_state_warmup + StagingState.SETTLING -> SourceStrings.dexcom_oneplus_staging_state_settling + StagingState.READY -> SourceStrings.dexcom_oneplus_staging_state_ready + }, + ) + CgmCard { + CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_staging_heading_short)) { + CgmStateChip(state = card.state.toUiState(), label = stateLabel) + } + if (card.state == StagingState.ABSENT) { + // An empty state that explains what the slot is for and offers the way in, instead of + // just reporting "None". + Text( + text = stringResource(SourceStrings.dexcom_oneplus_staging_none_short), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + OutlinedButton(onClick = onOpenStart) { + Text(stringResource(SourceStrings.dexcom_oneplus_start_presoak)) + } + } else { + StagingDetails(card, formatGlucose, formatTime, onPromoteClick, onCancelStaging) + } + } +} + +/** The pre-soak card while a sensor is in the slot: progress, evidence, promote and cancel. */ +@Composable +private fun ColumnScope.StagingDetails( + card: DexcomOnePlusStagingCard, + formatGlucose: (Double) -> String, + formatTime: (Long) -> String, + onPromoteClick: (Boolean) -> Unit, + onCancelStaging: () -> Unit, +) { + CgmStepTimeline( + labels = listOf( + stringResource(SourceStrings.dexcom_oneplus_staging_state_warmup), + stringResource(SourceStrings.dexcom_oneplus_staging_state_settling), + stringResource(SourceStrings.dexcom_oneplus_staging_state_ready), + ), + reached = when (card.state) { + StagingState.ABSENT -> -1 + StagingState.WARMUP -> 0 + StagingState.SETTLING -> 1 + StagingState.READY -> 2 + }, + ) + // Evidence the staging sensor is really alive: without it the user only sees a state label + // and cannot tell "settling with data" from "settling with a dead radio". + CgmKeyValueRow( + label = stringResource(SourceStrings.dexcom_oneplus_staging_readings_label), + value = card.validCount.toString(), + ) + val lastValue = card.lastValueMgdl + val lastAt = card.lastValueAtMs + if (lastValue != null && lastAt != null) { + CgmKeyValueRow( + label = stringResource(SourceStrings.dexcom_oneplus_staging_last_label), + value = stringResource(SourceStrings.dexcom_oneplus_reading_at, formatGlucose(lastValue), formatTime(lastAt)), + ) + } else { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_staging_no_reading_yet), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + when (card.promote) { + DexcomOnePlusPromoteOffer.NORMAL -> Button( + onClick = { onPromoteClick(false) }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(SourceStrings.dexcom_oneplus_staging_promote)) + } + + // Deliberately an outlined button with its own warning dialog: it gives up sensor + // quality, so it must never look like the normal path. + DexcomOnePlusPromoteOffer.EARLY -> Column(verticalArrangement = Arrangement.spacedBy(AapsSpacing.small)) { + OutlinedButton( + onClick = { onPromoteClick(true) }, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(SourceStrings.dexcom_oneplus_staging_promote_early)) + } + Text( + text = stringResource(SourceStrings.dexcom_oneplus_staging_promote_early_hint), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + DexcomOnePlusPromoteOffer.NONE -> Unit + } + TextButton(onClick = onCancelStaging, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(SourceStrings.dexcom_oneplus_staging_cancel)) + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusState.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusState.kt new file mode 100644 index 000000000000..ded9d11b5526 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusState.kt @@ -0,0 +1,276 @@ +package app.aaps.plugins.source.compose + +import app.aaps.core.data.model.GV +import app.aaps.core.data.model.SourceSensor +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.source.CgmSensorLifecycle +import app.aaps.core.interfaces.source.CgmStagingEvidence +import app.aaps.core.interfaces.source.PromotionRejectReason +import app.aaps.core.interfaces.source.PromotionResult +import app.aaps.core.interfaces.source.StagingState +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.ui.compose.ScreenAction +import app.aaps.core.ui.compose.StatusLevel +import app.aaps.core.ui.compose.pump.PumpInfoRow +import app.aaps.core.ui.compose.pump.PumpOverviewUiState +import app.aaps.core.ui.compose.pump.StatusBanner +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.dexcomoneplus.parse.OnePlusCalibrationState +import app.aaps.plugins.source.DexcomOnePlusCalibrationText +import app.aaps.plugins.source.DexcomOnePlusStaging +import app.aaps.plugins.source.SourceStrings + +/** + * Everything the ONE+ / G7 status screen shows, read at one moment. + * + * The view model fills it from the driver, the plugin and the database; [DexcomOnePlusStatusState] + * turns it into what is drawn. Kept as plain data so the mapping is tested without a phone. + */ +data class DexcomOnePlusStatusInput( + val phase: OnePlusWarmupState.Phase, + val driverMessage: String?, + val sessionUp: Boolean, + val lifecycle: CgmSensorLifecycle?, + /** The newest reading in the database, from any source. Only this driver's own is shown. */ + val newestGlucose: GV?, + val calibrationOutcome: OnePlusCalibrationOutcome?, + val calibrationWaiting: Boolean, + /** `DexcomOnePlusBooleanKey.SendCalibrationToSensor`. */ + val sendCalibrationToSensor: Boolean, + /** `DexcomOnePlusBooleanKey.CorrectSensorStart`. */ + val correctSensorStartEnabled: Boolean, + val stagingState: StagingState, + val stagingEvidence: CgmStagingEvidence?, + val nowMs: Long, +) + +/** How the plain values of [DexcomOnePlusStatusInput] are written for a person. */ +class DexcomOnePlusStatusFormat( + val rh: TextResolver, + val glucose: (Double) -> String, + val time: (Long) -> String, + val age: (Long) -> String, +) + +/** What the three buttons at the bottom of the status screen do. */ +class DexcomOnePlusStatusActions( + val onOpenStart: () -> Unit, + val onOpenWarmup: () -> Unit, + val onOpenLog: () -> Unit, +) + +/** Which promote button the pre-soak card shows. */ +enum class DexcomOnePlusPromoteOffer { + + /** No button: the sensor is not ready and cannot be promoted early either. */ + NONE, + + /** The normal promote button: the pre-soak is over. */ + NORMAL, + + /** The early way out, with its own warning: the sensor is proving itself right now. */ + EARLY, +} + +/** The finger prick card. Shown only while values are sent to the sensor. */ +data class DexcomOnePlusCalibrationCard( + /** What the sensor itself asks for, or null. */ + val request: TextRef?, + val outcome: TextRef, + /** Why a value was dropped before it was written, or null when none was dropped. */ + val notSentReason: TextRef?, + /** The raw answer of the sensor, or null. */ + val detail: String?, + val warning: Boolean, +) + +/** The pre-soak card: the second sensor slot. */ +data class DexcomOnePlusStagingCard( + val state: StagingState, + val validCount: Int, + val lastValueMgdl: Double?, + val lastValueAtMs: Long?, + val promote: DexcomOnePlusPromoteOffer, +) + +/** + * What the status screen draws. + * + * [overview] is the shared pump overview: the banner, the facts of the sensor that feeds the loop, + * and the buttons. The rest are the cards that follow it, in this order: calibration, end of life, + * pre-soak. Keeping the pre-soak in its own card is on purpose: a reading must belong to a visible + * subject, and the promote button is the one action here that changes the loop's glucose source. + */ +data class DexcomOnePlusStatusView( + val overview: PumpOverviewUiState, + val calibration: DexcomOnePlusCalibrationCard?, + val endOfLifePrompt: Boolean, + val staging: DexcomOnePlusStagingCard, + /** Start time the "correct insertion date" action works on, or null when the action is hidden. */ + val correctInsertionStartMs: Long?, +) + +/** Turns a [DexcomOnePlusStatusInput] into a [DexcomOnePlusStatusView]. Pure: no clock, no driver. */ +object DexcomOnePlusStatusState { + + fun build( + input: DexcomOnePlusStatusInput, + format: DexcomOnePlusStatusFormat, + actions: DexcomOnePlusStatusActions, + ): DexcomOnePlusStatusView { + val rh = format.rh + val overview = PumpOverviewUiState( + statusBanner = StatusBanner( + text = rh.gs(DexcomOnePlusUiLabels.phaseLabelRef(input.phase)), + level = bannerLevel(input.phase, input.sessionUp), + ), + infoRows = productionRows(input, format), + primaryActions = listOf( + ScreenAction(label = rh.gs(SourceStrings.dexcom_oneplus_start_action), onClick = actions.onOpenStart), + ScreenAction(label = rh.gs(SourceStrings.dexcom_oneplus_step_warmup), onClick = actions.onOpenWarmup), + ), + managementActions = listOf( + ScreenAction(label = rh.gs(SourceStrings.cgm_driver_log_open), onClick = actions.onOpenLog), + ), + ) + return DexcomOnePlusStatusView( + overview = overview, + calibration = if (input.sendCalibrationToSensor) calibrationCard(input) else null, + // Offer a pre-soak exactly when it is useful: the sensor in use is near its end and no + // replacement is warming up yet. + endOfLifePrompt = input.lifecycle?.endOfLife == true && input.stagingState == StagingState.ABSENT, + staging = stagingCard(input), + // Hidden while the setting is off. The plugin also refuses before any write. + correctInsertionStartMs = input.lifecycle?.startedAtEpochMs?.takeIf { input.correctSensorStartEnabled }, + ) + } + + /** Green only when the sensor is ready and the link is up; red only when the driver gave up. */ + fun bannerLevel(phase: OnePlusWarmupState.Phase, sessionUp: Boolean): StatusLevel = when (phase) { + OnePlusWarmupState.Phase.READY -> if (sessionUp) StatusLevel.NORMAL else StatusLevel.WARNING + OnePlusWarmupState.Phase.FAILED -> StatusLevel.CRITICAL + OnePlusWarmupState.Phase.IDLE -> StatusLevel.UNSPECIFIED + OnePlusWarmupState.Phase.PAIRING, + OnePlusWarmupState.Phase.CONNECTING, + OnePlusWarmupState.Phase.RECONNECTING, + OnePlusWarmupState.Phase.WARMING -> StatusLevel.WARNING + } + + private fun productionRows(input: DexcomOnePlusStatusInput, format: DexcomOnePlusStatusFormat): List { + val rh = format.rh + // Only this driver's own readings: the newest value in the database can come from another + // source, and labelling someone else's reading as this sensor's would be a lie. + val own = input.newestGlucose?.takeIf { it.sourceSensor == SourceSensor.DEXCOM_ONEPLUS_NATIVE } + val rows = mutableListOf( + PumpInfoRow( + label = rh.gs(SourceStrings.dexcom_oneplus_row_last_reading), + value = if (own != null) { + rh.gs(SourceStrings.dexcom_oneplus_reading_at, format.glucose(own.value), format.time(own.timestamp)) + } else { + rh.gs(SourceStrings.dexcom_oneplus_production_no_reading) + }, + ), + PumpInfoRow( + label = rh.gs(SourceStrings.cgm_session_label), + value = rh.gs(if (input.sessionUp) SourceStrings.dexcom_oneplus_session_up else SourceStrings.dexcom_oneplus_session_down), + level = if (input.sessionUp) StatusLevel.NORMAL else StatusLevel.WARNING, + ), + ) + input.lifecycle?.ageMs?.let { age -> + rows += PumpInfoRow( + label = rh.gs(SourceStrings.dexcom_oneplus_row_sensor_age), + value = format.age(age), + level = if (input.lifecycle.endOfLife) StatusLevel.WARNING else StatusLevel.UNSPECIFIED, + ) + } + rows += PumpInfoRow( + label = rh.gs(SourceStrings.dexcom_oneplus_row_message), + value = rh.gs(DexcomOnePlusUiLabels.userMessageRef(input.driverMessage)), + ) + return rows + } + + /** + * The texts come from [DexcomOnePlusCalibrationText], as for the plugin. + * + * [OnePlusCalibrationOutcome.Unknown] is not softened: the value was written and the answer was + * lost or unreadable, so it is neither a failure of the app nor a success. + * [OnePlusCalibrationOutcome.NotSent] says the opposite: nothing reached the sensor, and the + * value may be entered again. + */ + private fun calibrationCard(input: DexcomOnePlusStatusInput): DexcomOnePlusCalibrationCard { + val outcome = input.calibrationOutcome + val detail = when (outcome) { + is OnePlusCalibrationOutcome.Accepted -> outcome.detail + is OnePlusCalibrationOutcome.Refused -> outcome.detail + is OnePlusCalibrationOutcome.Unknown -> outcome.detail + else -> null + } + val notSentReason = (outcome as? OnePlusCalibrationOutcome.NotSent) + ?.takeIf { !input.calibrationWaiting } + ?.let { DexcomOnePlusCalibrationText.notSentReason(it.reason) } + return DexcomOnePlusCalibrationCard( + request = calibrationRequest(input.driverMessage), + outcome = DexcomOnePlusCalibrationText.status(outcome, input.calibrationWaiting), + notSentReason = notSentReason, + detail = detail?.takeIf { it.isNotBlank() }, + warning = outcome is OnePlusCalibrationOutcome.Refused || outcome is OnePlusCalibrationOutcome.NotSent, + ) + } + + /** What the sensor itself is asking for, read back out of the driver status line, or null. */ + fun calibrationRequest(driverMessage: String?): TextRef? { + val state = OnePlusCalibrationState.entries.firstOrNull { it.name == driverMessage } ?: return null + return when (state) { + OnePlusCalibrationState.NeedsCalibration -> SourceStrings.dexcom_oneplus_calibration_state_needs + OnePlusCalibrationState.NeedsFirstCalibration -> SourceStrings.dexcom_oneplus_calibration_state_needs_first + OnePlusCalibrationState.NeedsSecondCalibration -> SourceStrings.dexcom_oneplus_calibration_state_needs_second + OnePlusCalibrationState.CalibrationSent -> SourceStrings.dexcom_oneplus_calibration_state_sent + else -> null + } + } + + private fun stagingCard(input: DexcomOnePlusStatusInput): DexcomOnePlusStagingCard { + val evidence = input.stagingEvidence + val promote = when { + input.stagingState == StagingState.ABSENT -> DexcomOnePlusPromoteOffer.NONE + input.stagingState == StagingState.READY -> DexcomOnePlusPromoteOffer.NORMAL + // The way out when the production sensor stops before the soak ends - see canPromoteEarly. + DexcomOnePlusStaging.canPromoteEarly( + validEgvCount = evidence?.validCount ?: 0, + lastValueAtEpochMs = evidence?.lastValueAtEpochMs, + nowMs = input.nowMs, + ) -> DexcomOnePlusPromoteOffer.EARLY + else -> DexcomOnePlusPromoteOffer.NONE + } + return DexcomOnePlusStagingCard( + state = input.stagingState, + validCount = evidence?.validCount ?: 0, + lastValueMgdl = evidence?.lastValueMgdl, + lastValueAtMs = evidence?.lastValueAtEpochMs, + promote = promote, + ) + } + + /** + * Text shown after Promote. Refusal means nothing was written. [PromotionResult.OkBoundFailed] + * means the exchange is kept and the calibration bound threw. [PromotionResult.OkFollowUpFailed] + * means a later step threw; the wording follows + * [PromotionResult.OkFollowUpFailed.productionIdentityPresent], which the plugin read from the + * production store. + */ + fun promotionMessage(result: PromotionResult): TextRef = when (result) { + PromotionResult.Ok -> SourceStrings.dexcom_oneplus_staging_promote_ok + PromotionResult.OkBoundFailed -> SourceStrings.dexcom_oneplus_staging_promote_bound_failed + is PromotionResult.OkFollowUpFailed -> + if (result.productionIdentityPresent) SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed + else SourceStrings.dexcom_oneplus_staging_promote_follow_up_failed_no_identity + is PromotionResult.Rejected -> when (result.reason) { + PromotionRejectReason.STAGING_ABSENT -> SourceStrings.dexcom_oneplus_staging_promote_rejected_absent + PromotionRejectReason.STAGING_NOT_SETTLED -> SourceStrings.dexcom_oneplus_staging_promote_rejected_not_settled + PromotionRejectReason.STAGING_NO_VALID_GLUCOSE -> SourceStrings.dexcom_oneplus_staging_promote_rejected_no_glucose + PromotionRejectReason.STAGING_NO_RECENT_GLUCOSE -> SourceStrings.dexcom_oneplus_staging_promote_rejected_no_recent_glucose + } + } +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt deleted file mode 100644 index c00383454f5c..000000000000 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusSummary.kt +++ /dev/null @@ -1,75 +0,0 @@ -package app.aaps.plugins.source.compose - -import androidx.compose.foundation.layout.ColumnScope -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import app.aaps.core.data.model.GV -import app.aaps.core.data.model.SourceSensor -import app.aaps.core.interfaces.source.CgmSensorLifecycle -import app.aaps.core.ui.compose.stringResource -import app.aaps.plugins.source.SourceStrings - -/** - * The card for the sensor that feeds the loop. - * - * Accented so it is never confused with the pre-soak card. [extra] is for the actions below the - * facts - the "correct insertion date" action of the status screen. - */ -@Composable -fun DexcomOnePlusProductionCard( - phaseLabel: String, - phaseState: CgmUiState, - sessionUp: Boolean, - message: String, - lifecycle: CgmSensorLifecycle?, - newestGlucose: GV?, - formatGlucose: (Double) -> String, - formatTime: (Long) -> String, - formatAge: (Long) -> String, - extra: @Composable ColumnScope.() -> Unit = {}, -) { - CgmCard(accent = true) { - CgmCardHeader(stringResource(SourceStrings.dexcom_oneplus_production_heading)) { - CgmStateChip(state = phaseState, label = phaseLabel) - } - // Only this driver's own readings are shown here: the newest value in the database can come - // from another source, and labelling someone else's reading as this sensor's would be a lie. - val ownReading = newestGlucose?.takeIf { it.sourceSensor == SourceSensor.DEXCOM_ONEPLUS_NATIVE } - if (ownReading != null) { - Text( - text = stringResource( - SourceStrings.dexcom_oneplus_staging_last_reading, - formatGlucose(ownReading.value), - formatTime(ownReading.timestamp), - ), - style = MaterialTheme.typography.titleMedium, - ) - } else { - Text( - text = stringResource(SourceStrings.dexcom_oneplus_production_no_reading), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - CgmKeyValueRow( - label = stringResource(SourceStrings.cgm_session_label), - value = stringResource( - if (sessionUp) SourceStrings.dexcom_oneplus_session_up else SourceStrings.dexcom_oneplus_session_down, - ), - ) - lifecycle?.ageMs?.let { age -> - Text( - text = stringResource(SourceStrings.dexcom_oneplus_sensor_age, formatAge(age)), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Text( - text = message, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - extra() - } -} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusViewModel.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusViewModel.kt new file mode 100644 index 000000000000..8c00c328bd8f --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusStatusViewModel.kt @@ -0,0 +1,166 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.runtime.Stable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import app.aaps.core.data.model.GV +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.interfaces.resources.TextResolver +import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.plugins.dexcomoneplus.OnePlusCalibrationOutcome +import app.aaps.plugins.dexcomoneplus.OnePlusCgmDrivers +import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState +import app.aaps.plugins.source.DexcomOnePlusHost +import app.aaps.plugins.source.DexcomOnePlusPlugin +import app.aaps.plugins.source.DexcomOnePlusSensorStartCorrection +import app.aaps.plugins.source.SourceStrings +import app.aaps.plugins.source.keys.DexcomOnePlusBooleanKey +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesIntoMap +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.binding +import dev.zacsweers.metrox.viewmodel.ViewModelKey +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +/** How often the screen goes back to the driver. */ +private const val DRIVER_REFRESH_MILLIS = 1_000L + +/** How often the screen goes back to the database. A reading arrives every five minutes. */ +private const val GLUCOSE_REFRESH_MILLIS = 30_000L + +/** + * State of the ONE+ / G7 status screen, for the plugin tab and for the status Activity. + * + * It reads what the status Activity used to read itself: the driver every second, the newest + * reading every 30 seconds, and the slot flows of the plugin as they change. It only reads, + * except for the three actions the person starts by hand: promote, cancel the pre-soak, and + * correct the insertion date. All three are the plugin's own functions, with their own checks. + */ +@ContributesIntoMap(AppScope::class, binding = binding()) +@ViewModelKey +@Stable +@Inject +class DexcomOnePlusStatusViewModel( + private val plugin: DexcomOnePlusPlugin, + internal val host: DexcomOnePlusHost, + private val preferences: Preferences, + private val persistenceLayer: PersistenceLayer, + private val dateUtil: DateUtil, + private val profileUtil: ProfileUtil, + internal val rh: TextResolver, +) : ViewModel() { + + /** What the driver says right now. */ + private data class DriverReading( + val state: OnePlusWarmupState, + val sessionUp: Boolean, + val calibrationOutcome: OnePlusCalibrationOutcome?, + val calibrationWaiting: Boolean, + val sendCalibrationToSensor: Boolean, + val correctSensorStartEnabled: Boolean, + val nowMs: Long, + ) + + init { + // As the status Activity did when it opened: the driver in use follows the engineering + // switch before the screen reads it. + plugin.syncDriverFromPrefs() + } + + private val driverTicks: Flow = flow { + while (true) { + // Asked again every time: a promotion swaps which instance `default()` hands out, and a + // kept reference would show the retired one for the rest of the screen's life. + val driver = OnePlusCgmDrivers.default() + emit( + DriverReading( + state = driver.warmupState(), + sessionUp = driver.isSessionUp(), + calibrationOutcome = driver.lastCalibrationOutcome(), + calibrationWaiting = driver.calibrationPending(), + sendCalibrationToSensor = preferences.get(DexcomOnePlusBooleanKey.SendCalibrationToSensor), + correctSensorStartEnabled = preferences.get(DexcomOnePlusBooleanKey.CorrectSensorStart), + nowMs = dateUtil.now(), + ), + ) + delay(DRIVER_REFRESH_MILLIS) + } + } + + private val glucoseTicks: Flow = flow { + while (true) { + emit(persistenceLayer.getLastGlucoseValue()) + delay(GLUCOSE_REFRESH_MILLIS) + } + } + + val input: StateFlow = combine( + driverTicks, + glucoseTicks, + plugin.stagingState, + plugin.stagingEvidence, + plugin.lifecycle, + ) { driver, glucose, stagingState, stagingEvidence, lifecycle -> + DexcomOnePlusStatusInput( + phase = driver.state.phase, + driverMessage = driver.state.message, + sessionUp = driver.sessionUp, + lifecycle = lifecycle, + newestGlucose = glucose, + calibrationOutcome = driver.calibrationOutcome, + calibrationWaiting = driver.calibrationWaiting, + sendCalibrationToSensor = driver.sendCalibrationToSensor, + correctSensorStartEnabled = driver.correctSensorStartEnabled, + stagingState = stagingState, + stagingEvidence = stagingEvidence, + nowMs = driver.nowMs, + ) + }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000L), null) + + private val _promoteResult = MutableStateFlow(null) + + /** What the last promotion did, or null before one was asked for. */ + val promoteResult: StateFlow = _promoteResult.asStateFlow() + + val format: DexcomOnePlusStatusFormat = DexcomOnePlusStatusFormat( + rh = rh, + glucose = { mgdl -> profileUtil.fromMgdlToStringWithUnits(mgdl) }, + time = { epochMs -> dateUtil.timeString(epochMs) }, + age = { millis -> formatSensorAge(millis, rh) }, + ) + + /** + * Promotes the pre-soak sensor. [allowEarly] is the early way out, after its own warning. + * + * Refused with a message while the plugin is switched off, before anything is asked of it. + */ + fun promote(allowEarly: Boolean) { + if (plugin.isStopped()) { + _promoteResult.value = SourceStrings.dexcom_oneplus_plugin_stopped + return + } + viewModelScope.launch { + _promoteResult.value = DexcomOnePlusStatusState.promotionMessage(plugin.promoteStagingToProduction(allowEarly)) + } + } + + fun cancelStaging() { + plugin.cancelStaging() + _promoteResult.value = null + } + + suspend fun correctSensorStart(startMs: Long): DexcomOnePlusSensorStartCorrection.Verdict = + plugin.correctProductionSensorStart(startMs) +} diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt index cc83ada7ac8a..b573848bf6c0 100644 --- a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/DexcomOnePlusUiLabels.kt @@ -1,6 +1,8 @@ package app.aaps.plugins.source.compose import androidx.compose.runtime.Composable +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.keys.interfaces.TextRef.Companion.withArgs import app.aaps.core.ui.compose.stringResource import app.aaps.plugins.dexcomoneplus.OnePlusWarmupState import app.aaps.plugins.dexcomoneplus.session.OnePlusAuthRefusalPolicy @@ -9,53 +11,55 @@ import app.aaps.plugins.source.SourceStrings /** * Localized labels for ONE+ Status / Warm-up screens. * Driver [OnePlusWarmupState.message] codes stay English for logcat; UI maps them here. + * + * The [TextRef] forms are for code outside Compose (the status state builder), the Composable + * forms for the screens. Both give the same text. */ object DexcomOnePlusUiLabels { - @Composable - fun phaseLabel(phase: OnePlusWarmupState.Phase): String = when (phase) { - OnePlusWarmupState.Phase.IDLE -> stringResource(SourceStrings.dexcom_oneplus_phase_idle) - OnePlusWarmupState.Phase.PAIRING -> stringResource(SourceStrings.dexcom_oneplus_phase_pairing) - OnePlusWarmupState.Phase.CONNECTING -> stringResource(SourceStrings.dexcom_oneplus_phase_connecting) - OnePlusWarmupState.Phase.RECONNECTING -> stringResource(SourceStrings.dexcom_oneplus_phase_reconnecting) - OnePlusWarmupState.Phase.WARMING -> stringResource(SourceStrings.dexcom_oneplus_phase_warming) - OnePlusWarmupState.Phase.READY -> stringResource(SourceStrings.dexcom_oneplus_phase_ready) - OnePlusWarmupState.Phase.FAILED -> stringResource(SourceStrings.dexcom_oneplus_phase_failed) + fun phaseLabelRef(phase: OnePlusWarmupState.Phase): TextRef = when (phase) { + OnePlusWarmupState.Phase.IDLE -> SourceStrings.dexcom_oneplus_phase_idle + OnePlusWarmupState.Phase.PAIRING -> SourceStrings.dexcom_oneplus_phase_pairing + OnePlusWarmupState.Phase.CONNECTING -> SourceStrings.dexcom_oneplus_phase_connecting + OnePlusWarmupState.Phase.RECONNECTING -> SourceStrings.dexcom_oneplus_phase_reconnecting + OnePlusWarmupState.Phase.WARMING -> SourceStrings.dexcom_oneplus_phase_warming + OnePlusWarmupState.Phase.READY -> SourceStrings.dexcom_oneplus_phase_ready + OnePlusWarmupState.Phase.FAILED -> SourceStrings.dexcom_oneplus_phase_failed } + @Composable + fun phaseLabel(phase: OnePlusWarmupState.Phase): String = stringResource(phaseLabelRef(phase)) + /** * Maps driver/log message codes to user-facing copy. Unknown technical codes are not shown raw. */ - @Composable - fun userMessage(raw: String?): String { - if (raw.isNullOrBlank()) { - return stringResource(SourceStrings.dexcom_oneplus_status_message_none) - } + fun userMessageRef(raw: String?): TextRef { + if (raw.isNullOrBlank()) return SourceStrings.dexcom_oneplus_status_message_none return when { raw == "pairing" || raw.startsWith("pairing_attempt_") -> - stringResource(SourceStrings.dexcom_oneplus_msg_pairing) + SourceStrings.dexcom_oneplus_msg_pairing raw == "auth_ok" -> - stringResource(SourceStrings.dexcom_oneplus_msg_auth_ok) + SourceStrings.dexcom_oneplus_msg_auth_ok raw == "tx_time_session" -> - stringResource(SourceStrings.dexcom_oneplus_msg_tx_session) + SourceStrings.dexcom_oneplus_msg_tx_session raw == "egv_loop_exit" || raw == "disconnect" || raw == "shutdown" || raw == "cancelled" -> - stringResource(SourceStrings.dexcom_oneplus_msg_session_down) + SourceStrings.dexcom_oneplus_msg_session_down // Before the generic auth line: these two say what the user has to do. raw.startsWith(OnePlusAuthRefusalPolicy.MESSAGE_LOCKED) -> - stringResource( - SourceStrings.dexcom_oneplus_error_refused_stopped, - OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW, - ) + SourceStrings.dexcom_oneplus_error_refused_stopped.withArgs(OnePlusAuthRefusalPolicy.MAX_REFUSALS_IN_A_ROW) raw.startsWith(OnePlusAuthRefusalPolicy.MESSAGE_PAUSED) -> - stringResource(SourceStrings.dexcom_oneplus_msg_refused_pause) + SourceStrings.dexcom_oneplus_msg_refused_pause raw.startsWith("ONEPLUS_AUTH") || raw.contains("bond", ignoreCase = true) -> - stringResource(SourceStrings.dexcom_oneplus_error_auth_bond) + SourceStrings.dexcom_oneplus_error_auth_bond raw.startsWith("ONEPLUS_GATT") || raw.startsWith("ONEPLUS_EGV") || raw.startsWith("ONEPLUS_CONTROL") || raw.startsWith("ONEPLUS_SESSION") || raw.startsWith("ONEPLUS_RECONNECT") || raw.startsWith("ONEPLUS_BACKFILL") || raw.startsWith("ONEPLUS_TIME") || raw.startsWith("ONEPLUS_PAIR") -> - stringResource(SourceStrings.dexcom_oneplus_error_connection) - else -> stringResource(SourceStrings.dexcom_oneplus_status_message_generic) + SourceStrings.dexcom_oneplus_error_connection + else -> SourceStrings.dexcom_oneplus_status_message_generic } } + + @Composable + fun userMessage(raw: String?): String = stringResource(userMessageRef(raw)) } diff --git a/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusApplicatorScanner.kt b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusApplicatorScanner.kt new file mode 100644 index 000000000000..d09d68b000f5 --- /dev/null +++ b/plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/compose/OnePlusApplicatorScanner.kt @@ -0,0 +1,88 @@ +package app.aaps.plugins.source.compose + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import app.aaps.core.ui.CoreUiStrings +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.core.ui.compose.stringResource +import app.aaps.plugins.dexcomoneplus.identity.OnePlusGs1ApplicatorParser +import app.aaps.plugins.source.SourceStrings + +/** + * Reads the Data Matrix on a Dexcom ONE+ / G7 applicator with the camera. + * + * The dialog and the check of the text are here; the camera itself is [CameraApplicatorScanner], + * a CameraX preview read by ZXing. A caller that passes no scanner (the screen tests) gets no scan + * button: the code is typed, as before. + */ +interface OnePlusApplicatorScanner { + + /** + * The camera view, filling [modifier]. + * + * @param onScanned called with every decoded text. It returns true when the text was a valid + * applicator code, and the scanner then stops reading. + */ + @Composable + fun CameraView(onScanned: (String) -> Boolean, modifier: Modifier) +} + +/** + * Accepts [text] as an applicator code only when the driver's parser can read it. + * + * Any other barcode in front of the camera (a box label, a QR code) is ignored, so the field is + * never filled with something that is not a pairing code. + */ +internal fun acceptApplicatorScan(text: String): Boolean = OnePlusGs1ApplicatorParser.parse(text) != null + +/** The camera, a short hint and a way out, over the start screen. */ +@Composable +internal fun OnePlusApplicatorScanDialog( + scanner: OnePlusApplicatorScanner, + onCode: (String) -> Unit, + onDismiss: () -> Unit, +) { + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(AapsSpacing.large), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.medium), + ) { + Text( + text = stringResource(SourceStrings.dexcom_oneplus_applicator_scan_hint), + style = MaterialTheme.typography.bodyMedium, + ) + Box(modifier = Modifier.weight(1f).fillMaxWidth()) { + scanner.CameraView( + onScanned = { text -> + val ok = acceptApplicatorScan(text) + if (ok) onCode(text) + ok + }, + modifier = Modifier.fillMaxSize(), + ) + } + OutlinedButton(onClick = onDismiss, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(CoreUiStrings.cancel)) + } + } + } + } +} diff --git a/plugins/source/src/androidMain/res/values/strings.xml b/plugins/source/src/androidMain/res/values/strings.xml index 263aad2bace8..33bc5a380d26 100644 --- a/plugins/source/src/androidMain/res/values/strings.xml +++ b/plugins/source/src/androidMain/res/values/strings.xml @@ -60,7 +60,6 @@ Sensor Name Address - Actions Bluetooth session Sensor driver log Refresh @@ -90,7 +89,6 @@ Native Dexcom ONE+ and G7 Bluetooth in AAPS. Apply the sensor, enter the pairing code immediately, then wait ~30 min warm-up before loop glucose. Status, connect with pairing code, and warm-up ONE+ / G7 status - Session phase and connection status Start sensor Apply sensor → enter code now → connect → ~30 min warm-up How to start:\n1. Apply the sensor on your body.\n2. Paste the applicator Data Matrix (GS1) or enter the 4-digit pairing code — do not wait until after warm-up.\n3. Stop Dexcom, xDrip, and Juggluco Direct (only one Bluetooth master).\n4. Allow Bluetooth, Scan, select the highlighted sensor, then Connect / follow.\n5. Accept the Android Bluetooth pairing prompt if shown.\n6. Warm-up ~30 min for a new sensor; attaching to a running sensor can deliver EGVs sooner. @@ -207,7 +205,6 @@ Warming up Settling Ready to promote - Last reading: %1$s at %2$s No reading yet. The staging sensor is still warming up or out of range. Cancel staging Promote to production @@ -246,10 +243,17 @@ Try connecting again Start another sensor Status - Production sensor Pre-soak sensor - Started %1$s ago No reading received yet. + Last reading + %1$s at %2$s + Sensor age + Last message + These are the lines of this driver in the app log file. They are kept when the app restarts. + Scan the applicator code + Hold the code on the sensor applicator in front of the camera. The field is filled as soon as the code is read. + The app may not use the camera, so the code cannot be scanned. You can still type it. + Ask again Readings collected Last reading Sensor is near its end diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/BgSourceComposeContent.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/BgSourceComposeContent.kt index 6bfa402f2118..b5a634f0fa4c 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/BgSourceComposeContent.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/compose/BgSourceComposeContent.kt @@ -1,5 +1,6 @@ package app.aaps.plugins.source.compose +import androidx.compose.foundation.layout.RowScope import androidx.compose.runtime.Composable import app.aaps.core.ui.compose.ComposablePluginContent import app.aaps.core.ui.compose.ToolbarConfig @@ -9,9 +10,13 @@ import app.aaps.core.ui.compose.metroViewModel * Compose content provider for BG Source plugins. * This class is shared by all BG source plugins (Dexcom, xDrip, etc.) since they all * use the same UI to display blood glucose readings. + * + * [extraActions] puts toolbar buttons in front of the list's own ones, for a source that has + * screens of its own (Dexcom ONE+ / G7 opens its sensor status from there). */ internal class BgSourceComposeContent( - private val title: String + private val title: String, + private val extraActions: (@Composable RowScope.() -> Unit)? = null, ) : ComposablePluginContent { @Composable @@ -21,11 +26,19 @@ internal class BgSourceComposeContent( onSettings: (() -> Unit)? ) { val viewModel: BgSourceViewModel = metroViewModel() + val extra = extraActions BgSourceScreen( viewModel = viewModel, title = title, - setToolbarConfig = setToolbarConfig, + setToolbarConfig = if (extra == null) setToolbarConfig else { config -> + setToolbarConfig( + config.copy(actions = { + extra() + config.actions(this) + }) + ) + }, onNavigateBack = onNavigateBack, onSettings = onSettings ) diff --git a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt index a57c366bfb5e..3cf09f3a0eb5 100644 --- a/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt +++ b/plugins/source/src/commonMain/kotlin/app/aaps/plugins/source/keys/DexcomOnePlusIntentKey.kt @@ -21,11 +21,9 @@ enum class DexcomOnePlusIntentKey( override val exportable: Boolean = false ) : IntentPreferenceKey { - Status( - key = "dexcom_oneplus_status", - title = SourceStrings.dexcom_oneplus_status_title, - summary = SourceStrings.dexcom_oneplus_status_summary - ), + // No Status entry: the status screen is the sensor button of the plugin tab. The status + // Activity is still opened by the notification and by the start and warm-up screens. + Start( key = "dexcom_oneplus_start", title = SourceStrings.dexcom_oneplus_start_title, From f76433c5f1f4b8e4a7c6185feecd830035d1862b Mon Sep 17 00:00:00 2001 From: mtr93600 Date: Thu, 5 Nov 2026 01:19:19 +0100 Subject: [PATCH 13/27] CGM alarms: one alarm layer for BG sources, used by Dexcom ONE+ / G7 13 CGM alarms (urgent low, urgent low soon, low, fall rate, high, rise rate, sensor failed, sensor ended, sensor ending soon, signal loss, sensor issue, second sensor ready, warm-up done), each with its own switch, level, delay, repeat, sound (AAPS or Trio sound) and a test button. What a user notices: - An alarm that is not acknowledged comes back every 5 minutes. After Acknowledge it stays quiet for its repeat time. - The mute timer never silences urgent low. "Hypo treated" holds the low alarms for 20 minutes. - The glucose alarms are off by default. The sensor alarms work only for a BG source that reports its sensor state (Dexcom ONE+ / G7 for now). - The watch shows the alarms with an Acknowledge button that goes back to the phone. New EventData messages are added at the end. Alarms only notify: they never change glucose values, timestamps or dosing. Trio sounds are MIT, see core/ui/SOUNDS.md. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/src/main/AndroidManifest.xml | 10 + app/src/main/kotlin/app/aaps/MainApp.kt | 4 + .../app/aaps/di/metro/AppReceiversBindings.kt | 17 + .../kotlin/app/aaps/di/metro/AppRootGraph.kt | 2 + .../kotlin/app/aaps/di/metro/MetroGraphs.kt | 2 + .../aaps/di/metro/ReceiverInjectorsTest.kt | 14 + .../aaps/di/metro/GraphScopeStabilityTest.kt | 1 + app/src/testFull/resources/prefs-schema.txt | 47 +++ .../interfaces/rx/weardata/EventDataTest.kt | 23 ++ .../core/interfaces/alerts/CgmAlarmType.kt | 63 +++ .../core/interfaces/alerts/LocalAlertUtils.kt | 51 +++ .../interfaces/notifications/AlarmAction.kt | 24 ++ .../interfaces/notifications/AlarmSound.kt | 95 ++++- .../notifications/NotificationId.kt | 28 +- .../core/interfaces/rx/weardata/EventData.kt | 25 ++ .../core/interfaces/source/CgmSensorAlerts.kt | 179 +++++++++ .../source/CgmSensorAlertRulesTest.kt | 101 +++++ .../src/androidMain/res/values/strings.xml | 60 +++ .../kotlin/app/aaps/core/keys/BooleanKey.kt | 16 + .../kotlin/app/aaps/core/keys/IntKey.kt | 189 +++++++++ .../kotlin/app/aaps/core/keys/StringKey.kt | 118 ++++++ .../app/aaps/core/keys/UnitDoubleKey.kt | 18 + core/ui/SOUNDS.md | 73 ++++ .../app/aaps/core/ui/AlarmSoundResources.kt | 54 ++- .../res/raw/trio_acoustic_dcr_harsh.m4a | Bin 0 -> 55080 bytes .../res/raw/trio_acoustic_dcr_medium.m4a | Bin 0 -> 50878 bytes .../res/raw/trio_acoustic_dcr_mild.m4a | Bin 0 -> 46858 bytes .../res/raw/trio_acoustic_dts_harsh.m4a | Bin 0 -> 52226 bytes .../res/raw/trio_acoustic_dts_medium.m4a | Bin 0 -> 52975 bytes .../res/raw/trio_acoustic_dts_mild.m4a | Bin 0 -> 41319 bytes .../res/raw/trio_acoustic_hg_harsh.m4a | Bin 0 -> 57088 bytes .../res/raw/trio_acoustic_hg_medium.m4a | Bin 0 -> 57253 bytes .../res/raw/trio_acoustic_hg_mild.m4a | Bin 0 -> 51492 bytes .../res/raw/trio_acoustic_lg_harsh.m4a | Bin 0 -> 59211 bytes .../res/raw/trio_acoustic_lg_medium.m4a | Bin 0 -> 57749 bytes .../res/raw/trio_acoustic_lg_mild.m4a | Bin 0 -> 52319 bytes .../res/raw/trio_acoustic_lgs_harsh.m4a | Bin 0 -> 47068 bytes .../res/raw/trio_acoustic_lgs_medium.m4a | Bin 0 -> 50912 bytes .../res/raw/trio_acoustic_lgs_mild.m4a | Bin 0 -> 43710 bytes .../res/raw/trio_acoustic_ulg_harsh.m4a | Bin 0 -> 105494 bytes .../res/raw/trio_acoustic_ulg_medium.m4a | Bin 0 -> 107463 bytes .../res/raw/trio_acoustic_ulg_mild.m4a | Bin 0 -> 100040 bytes .../res/raw/trio_electronic_dcr_harsh.m4a | Bin 0 -> 57997 bytes .../res/raw/trio_electronic_dcr_medium.m4a | Bin 0 -> 45916 bytes .../res/raw/trio_electronic_dcr_mild.m4a | Bin 0 -> 38533 bytes .../res/raw/trio_electronic_dts_harsh.m4a | Bin 0 -> 86848 bytes .../res/raw/trio_electronic_dts_medium.m4a | Bin 0 -> 70121 bytes .../res/raw/trio_electronic_dts_mild.m4a | Bin 0 -> 61152 bytes .../res/raw/trio_electronic_hg_harsh.m4a | Bin 0 -> 73202 bytes .../res/raw/trio_electronic_hg_medium.m4a | Bin 0 -> 60819 bytes .../res/raw/trio_electronic_hg_mild.m4a | Bin 0 -> 48849 bytes .../res/raw/trio_electronic_lg_harsh.m4a | Bin 0 -> 73232 bytes .../res/raw/trio_electronic_lg_medium.m4a | Bin 0 -> 61043 bytes .../res/raw/trio_electronic_lg_mild.m4a | Bin 0 -> 49926 bytes .../res/raw/trio_electronic_lgs_harsh.m4a | Bin 0 -> 67658 bytes .../res/raw/trio_electronic_lgs_medium.m4a | Bin 0 -> 56935 bytes .../res/raw/trio_electronic_lgs_mild.m4a | Bin 0 -> 43921 bytes .../res/raw/trio_electronic_ulg_harsh.m4a | Bin 0 -> 127936 bytes .../res/raw/trio_electronic_ulg_medium.m4a | Bin 0 -> 113385 bytes .../res/raw/trio_electronic_ulg_mild.m4a | Bin 0 -> 97116 bytes .../res/raw/trio_tone_glass_bell.m4a | Bin 0 -> 59611 bytes .../res/raw/trio_tone_hard_saw_wave.m4a | Bin 0 -> 57987 bytes .../androidMain/res/raw/trio_tone_harp.m4a | Bin 0 -> 66653 bytes .../androidMain/res/raw/trio_tone_meow.m4a | Bin 0 -> 67678 bytes .../res/raw/trio_tone_open_can.m4a | Bin 0 -> 90912 bytes .../res/raw/trio_tone_open_wrapper.m4a | Bin 0 -> 91542 bytes .../res/raw/trio_tone_saw_wave.m4a | Bin 0 -> 66028 bytes .../res/raw/trio_tone_sine_wave.m4a | Bin 0 -> 58216 bytes .../ui/src/androidMain/res/values/strings.xml | 46 +++ .../app/aaps/core/ui/alerts/CgmAlarmTitle.kt | 23 ++ .../alerts/LocalAlertUtilsImplTest.kt | 39 +- .../alerts/cgm/CgmAlarmManagerTest.kt | 343 ++++++++++++++++ .../maintenance/PeriodicMaintenanceTest.kt | 62 ++- .../AndroidSystemNotificationPlatformTest.kt | 24 +- .../receivers/KeepAliveWorkerTest.kt | 2 +- .../AlarmNotificationManager.kt | 34 +- .../CgmAlarmAcknowledgeReceiver.kt | 25 ++ .../HypoTreatedReceiver.kt | 29 ++ .../AndroidSystemNotificationPlatform.kt | 3 +- .../alerts/LocalAlertUtilsImpl.kt | 30 +- .../alerts/cgm/CgmAlarmConditions.kt | 124 ++++++ .../alerts/cgm/CgmAlarmEngine.kt | 257 ++++++++++++ .../implementation/alerts/cgm/CgmAlarmKeys.kt | 74 ++++ .../alerts/cgm/CgmAlarmManager.kt | 369 ++++++++++++++++++ .../alerts/keys/LocalAlertLongKey.kt | 8 +- .../alerts/keys/LocalAlertStringKey.kt | 21 + .../maintenance/PeriodicMaintenance.kt | 35 +- .../CommonNotificationManager.kt | 5 +- .../alerts/cgm/CgmAlarmConditionsTest.kt | 109 ++++++ .../alerts/cgm/CgmAlarmEngineTest.kt | 262 +++++++++++++ .../notifications/IosAlarmSoundPlayer.kt | 17 +- .../IosSystemNotificationPlatform.kt | 82 +++- .../IosSystemNotificationPlatformTest.kt | 47 +++ ios/app/AAPSClient.xcodeproj/project.pbxproj | 4 +- .../aaps/ios/shell/di/IosPlatformBindings.kt | 38 +- .../source/DexcomOnePlusSensorAlertsTest.kt | 144 +++++++ .../plugins/source/DexcomOnePlusPlugin.kt | 41 +- .../source/DexcomOnePlusSensorAlerts.kt | 128 ++++++ .../plugins/source/DexcomOnePlusStaging.kt | 11 +- .../compose/alerts/CgmAlarmControlsScreen.kt | 114 ++++++ .../ui/compose/alerts/CgmAlarmIntentKey.kt | 31 ++ .../app/aaps/ui/search/BuiltInSearchables.kt | 74 +++- wear/NOTICE | 15 + wear/src/main/AndroidManifest.xml | 4 + .../app/aaps/wear/alarm/CgmAlarmReceiver.kt | 24 ++ .../app/aaps/wear/alarm/CgmAlarmWatch.kt | 162 ++++++++ .../app/aaps/wear/comm/DataHandlerWear.kt | 6 +- .../app/aaps/wear/di/WearMemberInjectors.kt | 7 + wear/src/main/res/values/strings.xml | 2 + .../app/aaps/wear/alarm/CgmAlarmWatchTest.kt | 41 ++ .../app/aaps/wear/comm/DataHandlerWearTest.kt | 4 +- 111 files changed, 4072 insertions(+), 62 deletions(-) create mode 100644 core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt create mode 100644 core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt create mode 100644 core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt create mode 100644 core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt create mode 100644 core/ui/SOUNDS.md create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_dcr_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_dcr_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_dcr_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_dts_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_dts_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_dts_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_hg_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_hg_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_hg_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_lg_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_lg_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_lg_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_lgs_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_lgs_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_lgs_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_ulg_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_ulg_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_acoustic_ulg_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_dcr_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_dcr_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_dcr_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_dts_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_dts_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_dts_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_hg_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_hg_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_hg_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_lg_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_lg_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_lg_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_lgs_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_lgs_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_lgs_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_ulg_harsh.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_ulg_medium.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_electronic_ulg_mild.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_glass_bell.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_hard_saw_wave.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_harp.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_meow.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_open_can.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_open_wrapper.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_saw_wave.m4a create mode 100644 core/ui/src/androidMain/res/raw/trio_tone_sine_wave.m4a create mode 100644 core/ui/src/commonMain/kotlin/app/aaps/core/ui/alerts/CgmAlarmTitle.kt create mode 100644 implementation/src/androidHostTest/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmManagerTest.kt create mode 100644 implementation/src/androidMain/kotlin/app/aaps/implementation/androidNotification/CgmAlarmAcknowledgeReceiver.kt create mode 100644 implementation/src/androidMain/kotlin/app/aaps/implementation/androidNotification/HypoTreatedReceiver.kt create mode 100644 implementation/src/commonMain/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmConditions.kt create mode 100644 implementation/src/commonMain/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmEngine.kt create mode 100644 implementation/src/commonMain/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmKeys.kt create mode 100644 implementation/src/commonMain/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmManager.kt create mode 100644 implementation/src/commonMain/kotlin/app/aaps/implementation/alerts/keys/LocalAlertStringKey.kt create mode 100644 implementation/src/commonTest/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmConditionsTest.kt create mode 100644 implementation/src/commonTest/kotlin/app/aaps/implementation/alerts/cgm/CgmAlarmEngineTest.kt create mode 100644 plugins/source/src/androidHostTest/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAlertsTest.kt create mode 100644 plugins/source/src/androidMain/kotlin/app/aaps/plugins/source/DexcomOnePlusSensorAlerts.kt create mode 100644 ui/src/commonMain/kotlin/app/aaps/ui/compose/alerts/CgmAlarmControlsScreen.kt create mode 100644 ui/src/commonMain/kotlin/app/aaps/ui/compose/alerts/CgmAlarmIntentKey.kt create mode 100644 wear/NOTICE create mode 100644 wear/src/main/kotlin/app/aaps/wear/alarm/CgmAlarmReceiver.kt create mode 100644 wear/src/main/kotlin/app/aaps/wear/alarm/CgmAlarmWatch.kt create mode 100644 wear/src/test/kotlin/app/aaps/wear/alarm/CgmAlarmWatchTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index f3a8a19f64df..20a8a560fb5b 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -96,6 +96,16 @@ android:name="app.aaps.implementation.androidNotification.AlarmMuteReceiver" android:exported="false" /> + + + + + + ): MembersInjector<*> = injector + // "Hypo treated" action on the low glucose alarm notification. Same reason as AlarmMuteReceiver: + // without this entry, tapping the button would crash with "No Metro binding". + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(HypoTreatedReceiver::class) + fun bindHypoTreatedReceiver(injector: MembersInjector): MembersInjector<*> = injector + + // "Acknowledge" action on a CGM alarm notification. Same reason as AlarmMuteReceiver. + @Provides + @FeatureMemberInjectors + @IntoMap + @ClassKey(CgmAlarmAcknowledgeReceiver::class) + fun bindCgmAlarmAcknowledgeReceiver(injector: MembersInjector): MembersInjector<*> = injector + // The "time to eat" alarm and its notification buttons - same story as AlarmMuteReceiver above. @Provides @FeatureMemberInjectors diff --git a/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt b/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt index 676b596591ea..6017404f922e 100644 --- a/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt +++ b/app/src/main/kotlin/app/aaps/di/metro/AppRootGraph.kt @@ -122,6 +122,7 @@ import app.aaps.database.AppRepository import app.aaps.database.di.DatabaseConfig import app.aaps.di.ExternalOptionsOverride import app.aaps.implementation.lifecycle.ProcessLifecycleListener +import app.aaps.implementation.maintenance.PeriodicMaintenance import app.aaps.implementation.maintenance.cloud.CloudStorageManager import app.aaps.implementation.notifications.SnackbarNotificationFallback import app.aaps.implementation.plugin.PluginStore @@ -335,6 +336,7 @@ interface AppRootGraph : MetroViewModelMultibindings { val autosensData: AutosensData val commandQueue: CommandQueue val localAlertUtils: LocalAlertUtils + val periodicMaintenance: PeriodicMaintenance val bolusProgressData: BolusProgressData val persistenceLayer: PersistenceLayer val cloudStorageManager: CloudStorageManager diff --git a/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt b/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt index 3eb8a6a71c5d..d3056c79ab3e 100644 --- a/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt +++ b/app/src/main/kotlin/app/aaps/di/metro/MetroGraphs.kt @@ -57,6 +57,7 @@ import app.aaps.di.ExternalOptionsOverride import app.aaps.di.PluginSource import app.aaps.di.mergePlugins import app.aaps.implementation.lifecycle.ProcessLifecycleListener +import app.aaps.implementation.maintenance.PeriodicMaintenance import app.aaps.implementation.notifications.SnackbarNotificationFallback import app.aaps.implementation.plugin.PluginStore import app.aaps.implementation.profile.ProfileSwitchScheduler @@ -277,6 +278,7 @@ class MetroGraphs( val widgetUpdater: WidgetUpdater get() = root.widgetUpdater val commandQueue: CommandQueue get() = root.commandQueue val localAlertUtils: LocalAlertUtils get() = root.localAlertUtils + val periodicMaintenance: PeriodicMaintenance get() = root.periodicMaintenance val persistenceLayer: PersistenceLayer get() = root.persistenceLayer val appRepository: AppRepository get() = root.appRepository val constraintsChecker: ConstraintsChecker get() = root.constraintsChecker diff --git a/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt b/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt index 9f0b20309085..45e52f40c7dc 100644 --- a/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt +++ b/app/src/test/kotlin/app/aaps/di/metro/ReceiverInjectorsTest.kt @@ -2,6 +2,8 @@ package app.aaps.di.metro import app.aaps.implementation.alerts.EatReminderReceiver import app.aaps.implementation.androidNotification.AlarmMuteReceiver +import app.aaps.implementation.androidNotification.CgmAlarmAcknowledgeReceiver +import app.aaps.implementation.androidNotification.HypoTreatedReceiver import app.aaps.persistentNotification.DummyService import app.aaps.plugins.automation.TimerReminderReceiver import app.aaps.plugins.automation.services.LocationService @@ -48,6 +50,18 @@ class ReceiverInjectorsTest { assertThat(injectors.keys).contains(AlarmMuteReceiver::class) } + /** Same case for the "Hypo treated" button on the low glucose alarm notification. */ + @Test + fun `the hypo treated receiver has an injector`() { + assertThat(injectors.keys).contains(HypoTreatedReceiver::class) + } + + /** Same case for the "Acknowledge" button on a CGM alarm notification. */ + @Test + fun `the cgm alarm acknowledge receiver has an injector`() { + assertThat(injectors.keys).contains(CgmAlarmAcknowledgeReceiver::class) + } + /** The "time to eat" alarm and its Stop / +5 min buttons; a missing entry is a crash when the timer ends. */ @Test fun `the eat reminder receiver has an injector`() { diff --git a/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt b/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt index 46cb0fe15159..cb2564f0ea77 100644 --- a/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt +++ b/app/src/testFull/kotlin/app/aaps/di/metro/GraphScopeStabilityTest.kt @@ -178,6 +178,7 @@ class GraphScopeStabilityTest { "pairingOfferFetcher", "pairingOfferPublisher", "passwordCheck", + "periodicMaintenance", "persistenceLayer", "pluginPermissions", "pluginStore", diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index a4459e18df6b..962dbef798d2 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -77,7 +77,37 @@ active_scene|StringNonKey|false actual_basal_profile|MedtrumStringNonKey|true age|StringKey|true alarm_setting|MedtrumStringKey|true +alert_cgm_expiring_lead_hours|IntKey|true +alert_cgm_fall_rate_repeat_minutes|IntKey|true +alert_cgm_fall_rate_sound|StringKey|true +alert_cgm_high_delay_minutes|IntKey|true +alert_cgm_high_repeat_minutes|IntKey|true +alert_cgm_high_sound|StringKey|true +alert_cgm_low_repeat_minutes|IntKey|true +alert_cgm_low_sound|StringKey|true +alert_cgm_rise_rate_repeat_minutes|IntKey|true +alert_cgm_rise_rate_sound|StringKey|true +alert_cgm_sensor_ended_sound|StringKey|true +alert_cgm_sensor_expired_repeat_minutes|IntKey|true +alert_cgm_sensor_failed_repeat_minutes|IntKey|true +alert_cgm_sensor_failed_sound|StringKey|true +alert_cgm_sensor_issue_minutes|IntKey|true +alert_cgm_sensor_issue_repeat_minutes|IntKey|true +alert_cgm_sensor_issue_sound|StringKey|true +alert_cgm_signal_loss_sound|StringKey|true +alert_cgm_signal_lost_minutes|IntKey|true +alert_cgm_signal_lost_repeat_minutes|IntKey|true +alert_cgm_urgent_low_repeat_minutes|IntKey|true +alert_cgm_urgent_low_soon_repeat_minutes|IntKey|true +alert_cgm_urgent_low_soon_sound|StringKey|true +alert_cgm_urgent_low_sound|StringKey|true +alert_hyper_threshold|UnitDoubleKey|true +alert_hypo_threshold|UnitDoubleKey|true alert_override_dnd|BooleanKey|true +alert_rapid_fall_drop_mgdl|IntKey|true +alert_rapid_fall_window|IntKey|true +alert_rapid_rise_mgdl|IntKey|true +alert_rapid_rise_window|IntKey|true allow_hardware_pump|BooleanNonKey|true always_use_shortavg|BooleanKey|true app_expiration_%s|LongComposedKey|true @@ -123,6 +153,10 @@ carelevo_patch_info|CarelevoStringNonKey|false carelevo_temp_basal_infusion_info|CarelevoStringNonKey|false carelevo_user_setting_info|CarelevoStringNonKey|false categorize_uam_as_basal|BooleanKey|true +cgmAlarmRuntime|LocalAlertStringKey|false +cgmAlarmSource|LocalAlertStringKey|false +cgmAlarmsMutedUntil|LocalAlertLongKey|false +cgm_alarm_controls|CgmAlarmIntentKey|false combov2-bt-address-key|ComboStringNonKey|true combov2-cp-cipher-key|ComboStringNonKey|true combov2-key-response-address-key|ComboIntNonKey|true @@ -186,9 +220,22 @@ enableSMB_with_COB|BooleanKey|true enableSMB_with_high_temptarget|BooleanKey|true enableSMB_with_temptarget|BooleanKey|true enable_carbs_required_alert_local|BooleanKey|true +enable_cgm_rise_rate_alert|BooleanKey|true +enable_cgm_second_sensor_ready_alert|BooleanKey|true +enable_cgm_sensor_expired_alert|BooleanKey|true +enable_cgm_sensor_expiring_alert|BooleanKey|true +enable_cgm_sensor_failed_alert|BooleanKey|true +enable_cgm_sensor_issue_alert|BooleanKey|true +enable_cgm_signal_lost_alert|BooleanKey|true +enable_cgm_urgent_low_alert|BooleanKey|true +enable_cgm_urgent_low_soon_alert|BooleanKey|true +enable_cgm_warmup_done_alert|BooleanKey|true enable_fabric2|BooleanKey|true +enable_hyper_alert|BooleanKey|true +enable_hypo_alert|BooleanKey|true enable_missed_bg_readings|BooleanKey|true enable_pump_unreachable_alert|BooleanKey|true +enable_rapid_fall_alert|BooleanKey|true enable_unattended_export|BooleanKey|true eopatch_alarms|EopatchStringNonKey|true eopatch_bolus_current|EopatchStringNonKey|true diff --git a/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt b/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt index 8218c80e408a..1c6e81268089 100644 --- a/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt +++ b/core/interfaces/src/androidHostTest/kotlin/app/aaps/core/interfaces/rx/weardata/EventDataTest.kt @@ -345,4 +345,27 @@ class EventDataTest { assertThat(old).doesNotContain("carbsType") assertThat(EventData.deserialize(old)).isEqualTo(EventData.ActionWizardPreCheck(30, 100, CarbsType.BREAD)) } + + @Test + fun cgmAlarmMessagesRoundTrip() { + listOf( + EventData.CgmAlarm(id = "urgent_low", title = "Urgent low", message = "52 mg/dL", vibrationSeconds = 10, urgent = true), + EventData.CgmAlarm(id = "high", title = "High", message = "", vibrationSeconds = 0, urgent = false), + EventData.CgmAlarmCancel("urgent_low"), + EventData.CgmAlarmAcknowledge("signal_loss") + ).forEach { + assertThat(EventData.deserializeByte(it.serializeByte())).isEqualTo(it) + assertThat(EventData.deserialize(it.serialize())).isEqualTo(it) + } + } + + @Test + fun cgmAlarmMessagesDoNotChangeTheEncodingOfOlderMessages() { + // The CGM alarm messages are appended at the end of EventData. An older message must still + // decode to itself, and must not decode to one of the new ones. + val old = EventData.AlarmStopped(5L) + assertThat(EventData.deserializeByte(old.serializeByte())).isEqualTo(old) + assertThat(EventData.deserialize(old.serialize())).isEqualTo(old) + assertThat(EventData.CgmAlarmCancel("x").serialize()).contains("CgmAlarmCancel") + } } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt new file mode 100644 index 000000000000..e6293f830491 --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/CgmAlarmType.kt @@ -0,0 +1,63 @@ +package app.aaps.core.interfaces.alerts + +import app.aaps.core.interfaces.notifications.NotificationId + +/** + * Alarms that stand in for one another. While one is going off, the ones after it in the same + * group stay quiet: an urgent low needs no low alarm on top, and an ended sensor needs no "ending + * soon" on top. [INFO] alarms never quiet each other. + */ +enum class CgmAlarmGroup { LOW, HIGH, SENSOR, INFO } + +/** + * The CGM alarms, most important first. That order decides which alarm of a [group] goes off when + * several conditions hold at the same time. + * + * One alarm layer for every BG source: the glucose alarms read the stored glucose, the sensor + * alarms read the sensor state of a source that reports it + * ([app.aaps.core.interfaces.source.CgmSensorAlertProvider]). The alarms only notify. They never + * change the glucose values the loop receives, and never change dosing. + * + * @param id stable name, used in the stored alarm state and in the messages to the watch. It must + * not change once released. + * @param notificationId the notification this alarm posts. + * @param reminds true for an alarm that goes off again every few minutes until it is acknowledged. + * False for an information that is shown once per episode. + */ +enum class CgmAlarmType( + val id: String, + val group: CgmAlarmGroup, + val notificationId: NotificationId, + val reminds: Boolean = true, +) { + + URGENT_LOW("urgent_low", CgmAlarmGroup.LOW, NotificationId.CGM_URGENT_LOW), + SENSOR_FAILED("sensor_failed", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_FAILED), + URGENT_LOW_SOON("urgent_low_soon", CgmAlarmGroup.LOW, NotificationId.CGM_URGENT_LOW_SOON), + LOW("low", CgmAlarmGroup.LOW, NotificationId.BG_HYPO), + FALL_RATE("fall_rate", CgmAlarmGroup.LOW, NotificationId.BG_RAPID_FALL), + SENSOR_ENDED("sensor_ended", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_EXPIRED), + HIGH("high", CgmAlarmGroup.HIGH, NotificationId.BG_HYPER), + RISE_RATE("rise_rate", CgmAlarmGroup.HIGH, NotificationId.CGM_RAPID_RISE), + SIGNAL_LOSS("signal_loss", CgmAlarmGroup.SENSOR, NotificationId.CGM_SIGNAL_LOST), + SENSOR_ISSUE("sensor_issue", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_ISSUE), + SENSOR_ENDING_SOON("sensor_ending_soon", CgmAlarmGroup.SENSOR, NotificationId.CGM_SENSOR_EXPIRING, reminds = false), + SECOND_SENSOR_READY("second_sensor_ready", CgmAlarmGroup.INFO, NotificationId.CGM_SECOND_SENSOR_READY, reminds = false), + WARMUP_DONE("warmup_done", CgmAlarmGroup.INFO, NotificationId.CGM_WARMUP_DONE, reminds = false); + + /** True for the alarms that read glucose. The others read the sensor state. */ + val isGlucose: Boolean get() = group == CgmAlarmGroup.LOW || group == CgmAlarmGroup.HIGH + + /** + * The mute timer can never silence this alarm. Only urgent low: a person who muted the alarms for + * a meeting must still be woken by a glucose of 55 mg/dL or less. + */ + val neverMuted: Boolean get() = this == URGENT_LOW + + companion object { + + fun byId(id: String): CgmAlarmType? = entries.firstOrNull { it.id == id } + + fun byNotificationId(id: NotificationId): CgmAlarmType? = entries.firstOrNull { it.notificationId == id } + } +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt index 0c1bfc46fd0a..99090cfc26fb 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/alerts/LocalAlertUtils.kt @@ -1,5 +1,7 @@ package app.aaps.core.interfaces.alerts +import kotlinx.coroutines.flow.StateFlow + interface LocalAlertUtils { /** @@ -32,4 +34,53 @@ interface LocalAlertUtils { * Overview notification with sound, Therapy event */ suspend fun checkStaleBGAlert() + + /** + * Run the CGM alarms (see [CgmAlarmType]): check the current glucose against the glucose alarms + * the user has set up (urgent low, urgent low soon, low, fall rate, high, rise rate), and the + * sensor state of the active BG source against the sensor alarms, then raise, repeat or clear + * their notifications. + * + * The glucose alarms work for any CGM source, because they read the last stored glucose. The + * sensor alarms work for a source that reports its sensor state + * ([app.aaps.core.interfaces.source.CgmSensorAlertProvider]). It only notifies: it never changes + * dosing, the loop or the glucose values the loop receives. The glucose alarms do nothing on stale + * data, because the stale-data alarm owns that case. + */ + suspend fun checkGlucoseAlerts() + + /** + * The user says they treated the current hypo (took carbs): clear the low-glucose alarm and hold + * it for about the time carbs need to work, instead of the shorter automatic repeat. + * + * This only silences. The alarm comes back by itself if glucose is still low when the hold ends, + * and [checkGlucoseAlerts] clears the hold as soon as glucose has recovered. + * + * Returns at once. The hold is written in the background, after a check that is running at that + * moment has finished, so the check cannot overwrite it. + */ + fun snoozeHypoAfterTreatment() + + /** + * The user acknowledged a CGM alarm ([type]), or every CGM alarm that is going off when [type] is + * null: it stops, and stays quiet for its repeat time. When the repeat time is over and the + * condition is still there, it goes off again. Returns at once. + */ + fun acknowledgeCgmAlarms(type: CgmAlarmType? = null) + + /** + * Mute the CGM alarms for [minutes], or end the mute with 0. Urgent low is never muted + * ([CgmAlarmType.neverMuted]). Returns at once. + */ + fun muteCgmAlarms(minutes: Int) + + /** When the mute of the CGM alarms ends (epoch ms), 0 when they are not muted. */ + val cgmAlarmsMutedUntil: StateFlow + + /** + * Play [type] once as a test, with its sound and on the same path as a real alarm, so the user + * hears what it sounds like at night. It goes on until the user dismisses it. It changes nothing + * in the state of the real alarm. + */ + fun testCgmAlarm(type: CgmAlarmType) } \ No newline at end of file diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt new file mode 100644 index 000000000000..5c71c00dfd3d --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmAction.kt @@ -0,0 +1,24 @@ +package app.aaps.core.interfaces.notifications + +/** + * Action button an alarm carries on its **system** notification (lock screen, notification shade), + * on top of the in-app notification card. + * + * Declared per [NotificationId] and not passed where the alarm is posted, because the button must + * survive a trip through the operating system: on Android it goes through a `PendingIntent` to a + * `BroadcastReceiver`, on iOS through a notification category and the notification delegate. The + * in-app [NotificationAction] holds a lambda, which cannot make that trip. Each platform resolves + * the label and what the button does. + */ +enum class AlarmAction { + + /** "Hypo treated": the user took carbs, so hold the low-glucose alarms while they work. */ + HYPO_TREATED, + + /** + * "Acknowledge" on a CGM alarm: every CGM alarm that is going off stops and stays quiet for its + * repeat time. It is not a mute: when the repeat time is over and the condition is still there, + * the alarm goes off again. + */ + CGM_ACKNOWLEDGE +} diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt index 30ab5df22703..edef69d3cf5a 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/AlarmSound.kt @@ -13,24 +13,101 @@ package app.aaps.core.interfaces.notifications * extra, and a resource id is a build specific number - the same value means something else in * the next build. The stable [name] travels instead. * - * Deliberately a closed set: the sound files live in `:core:ui/res/raw` and there are five of them. - * Adding one means adding an entry here, which makes the `when` in the Android resolver stop - * compiling until it is handled. + * Deliberately a closed set: the sound files live in `:core:ui/res/raw`. Adding one means adding an + * entry here, which makes the `when` in the Android resolver stop compiling until it is handled. + * + * The `TRIO_*` sounds come from Trio (MIT licence, see `core/ui/SOUNDS.md`). Only the CGM alarms + * offer them, as the sound the user chose for one alarm. The iOS build copies every file named + * here into the app bundle, so [fileName] and [fileExtension] must match the file in `res/raw`. + * + * @param fileName the file name without extension, the same on Android and iOS. + * @param fileExtension the file type, `mp3` for the AAPS sounds, `m4a` for the Trio sounds. + * @param trioSet the Trio alarm this sound was made for, null for an AAPS sound or a Trio tone that + * any alarm may use. */ -enum class AlarmSound { +enum class AlarmSound( + val fileName: String, + val fileExtension: String = "mp3", + val trioSet: TrioSoundSet? = null, +) { /** Standard alarm. */ - ALARM, + ALARM("alarm"), /** Urgent alarm - used for the Nightscout urgent announcement path. */ - URGENT_ALARM, + URGENT_ALARM("urgentalarm"), /** General error. */ - ERROR, + ERROR("error"), /** Bolus delivery failure. */ - BOLUS_ERROR, + BOLUS_ERROR("boluserror"), /** The "time to eat" timer. A soft kitchen timer, so it is not taken for a warning. */ - EAT_REMINDER + EAT_REMINDER("eatreminder"), + + // Trio sounds: style (acoustic, electronic), the alarm they were made for, urgency level. + TRIO_ACOUSTIC_URGENT_LOW_MILD("trio_acoustic_ulg_mild", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ACOUSTIC_URGENT_LOW_MEDIUM("trio_acoustic_ulg_medium", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ACOUSTIC_URGENT_LOW_HARSH("trio_acoustic_ulg_harsh", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ACOUSTIC_LOW_MILD("trio_acoustic_lg_mild", "m4a", TrioSoundSet.LOW), + TRIO_ACOUSTIC_LOW_MEDIUM("trio_acoustic_lg_medium", "m4a", TrioSoundSet.LOW), + TRIO_ACOUSTIC_LOW_HARSH("trio_acoustic_lg_harsh", "m4a", TrioSoundSet.LOW), + TRIO_ACOUSTIC_LOW_SOON_MILD("trio_acoustic_lgs_mild", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ACOUSTIC_LOW_SOON_MEDIUM("trio_acoustic_lgs_medium", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ACOUSTIC_LOW_SOON_HARSH("trio_acoustic_lgs_harsh", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ACOUSTIC_HIGH_MILD("trio_acoustic_hg_mild", "m4a", TrioSoundSet.HIGH), + TRIO_ACOUSTIC_HIGH_MEDIUM("trio_acoustic_hg_medium", "m4a", TrioSoundSet.HIGH), + TRIO_ACOUSTIC_HIGH_HARSH("trio_acoustic_hg_harsh", "m4a", TrioSoundSet.HIGH), + TRIO_ACOUSTIC_DEVICE_CRITICAL_MILD("trio_acoustic_dcr_mild", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ACOUSTIC_DEVICE_CRITICAL_MEDIUM("trio_acoustic_dcr_medium", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ACOUSTIC_DEVICE_CRITICAL_HARSH("trio_acoustic_dcr_harsh", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ACOUSTIC_DEVICE_TIME_SENSITIVE_MILD("trio_acoustic_dts_mild", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ACOUSTIC_DEVICE_TIME_SENSITIVE_MEDIUM("trio_acoustic_dts_medium", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ACOUSTIC_DEVICE_TIME_SENSITIVE_HARSH("trio_acoustic_dts_harsh", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ELECTRONIC_URGENT_LOW_MILD("trio_electronic_ulg_mild", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ELECTRONIC_URGENT_LOW_MEDIUM("trio_electronic_ulg_medium", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ELECTRONIC_URGENT_LOW_HARSH("trio_electronic_ulg_harsh", "m4a", TrioSoundSet.URGENT_LOW), + TRIO_ELECTRONIC_LOW_MILD("trio_electronic_lg_mild", "m4a", TrioSoundSet.LOW), + TRIO_ELECTRONIC_LOW_MEDIUM("trio_electronic_lg_medium", "m4a", TrioSoundSet.LOW), + TRIO_ELECTRONIC_LOW_HARSH("trio_electronic_lg_harsh", "m4a", TrioSoundSet.LOW), + TRIO_ELECTRONIC_LOW_SOON_MILD("trio_electronic_lgs_mild", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ELECTRONIC_LOW_SOON_MEDIUM("trio_electronic_lgs_medium", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ELECTRONIC_LOW_SOON_HARSH("trio_electronic_lgs_harsh", "m4a", TrioSoundSet.LOW_SOON), + TRIO_ELECTRONIC_HIGH_MILD("trio_electronic_hg_mild", "m4a", TrioSoundSet.HIGH), + TRIO_ELECTRONIC_HIGH_MEDIUM("trio_electronic_hg_medium", "m4a", TrioSoundSet.HIGH), + TRIO_ELECTRONIC_HIGH_HARSH("trio_electronic_hg_harsh", "m4a", TrioSoundSet.HIGH), + TRIO_ELECTRONIC_DEVICE_CRITICAL_MILD("trio_electronic_dcr_mild", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ELECTRONIC_DEVICE_CRITICAL_MEDIUM("trio_electronic_dcr_medium", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ELECTRONIC_DEVICE_CRITICAL_HARSH("trio_electronic_dcr_harsh", "m4a", TrioSoundSet.DEVICE_CRITICAL), + TRIO_ELECTRONIC_DEVICE_TIME_SENSITIVE_MILD("trio_electronic_dts_mild", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ELECTRONIC_DEVICE_TIME_SENSITIVE_MEDIUM("trio_electronic_dts_medium", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_ELECTRONIC_DEVICE_TIME_SENSITIVE_HARSH("trio_electronic_dts_harsh", "m4a", TrioSoundSet.DEVICE_TIME_SENSITIVE), + TRIO_TONE_GLASS_BELL("trio_tone_glass_bell", "m4a", null), + TRIO_TONE_HARP("trio_tone_harp", "m4a", null), + TRIO_TONE_MEOW("trio_tone_meow", "m4a", null), + TRIO_TONE_SAW_WAVE("trio_tone_saw_wave", "m4a", null), + TRIO_TONE_HARD_SAW_WAVE("trio_tone_hard_saw_wave", "m4a", null), + TRIO_TONE_SINE_WAVE("trio_tone_sine_wave", "m4a", null), + TRIO_TONE_OPEN_CAN("trio_tone_open_can", "m4a", null), + TRIO_TONE_OPEN_WRAPPER("trio_tone_open_wrapper", "m4a", null); + + /** True for a sound from Trio, see `core/ui/SOUNDS.md`. */ + val isTrio: Boolean get() = fileName.startsWith("trio_") + + companion object { + + /** The Trio tones that any alarm may use. */ + val trioTones: List get() = entries.filter { it.isTrio && it.trioSet == null } + + /** The Trio sounds made for [set], mild to harsh, acoustic first. */ + fun trioSoundsFor(set: TrioSoundSet): List = entries.filter { it.trioSet == set } + } } + +/** + * The Trio alarm a sound set was written for. Several CGM alarms share a set where Trio has none of + * their own: the rate alarms use the low soon and high sets, and the sensor alarms use the device + * sets. + */ +enum class TrioSoundSet { URGENT_LOW, LOW, LOW_SOON, HIGH, DEVICE_CRITICAL, DEVICE_TIME_SENSITIVE } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt index b9a07c73cff2..284d4a7f1768 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/notifications/NotificationId.kt @@ -31,7 +31,9 @@ import app.aaps.core.interfaces.notifications.NotificationLevel.URGENT enum class NotificationId( val defaultLevel: NotificationLevel, val category: NotificationCategory, - val allowMultiple: Boolean = false + val allowMultiple: Boolean = false, + /** Extra action button carried by this alarm's system notification, if any. */ + val alarmAction: AlarmAction? = null ) { // Profile @@ -266,7 +268,29 @@ enum class NotificationId( // A pre-soak sensor of a native CGM driver was made the production sensor by the app itself, without the // user pressing the promote button. Appended at the END for the same reason as above. - CGM_STAGING_AUTO_PROMOTED(NORMAL, CGM); + CGM_STAGING_AUTO_PROMOTED(NORMAL, CGM), + + // CGM alarms (`CgmAlarmType`), one alarm layer for every BG source. The glucose ones read the + // stored glucose; the sensor ones are raised only for a source that reports its sensor state + // ([app.aaps.core.interfaces.source.CgmSensorAlertProvider]). They only notify; they never change + // dosing. An alarm the user gave a sound is posted URGENT, whatever its level here. Appended at + // the END for the same reason as above. + BG_HYPO(URGENT, CGM, alarmAction = AlarmAction.HYPO_TREATED), + BG_HYPER(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + BG_RAPID_FALL(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_URGENT_LOW(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_URGENT_LOW_SOON(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_RAPID_RISE(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_FAILED(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_EXPIRED(URGENT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_EXPIRING(IMPORTANT, CGM), + CGM_SIGNAL_LOST(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_SENSOR_ISSUE(IMPORTANT, CGM, alarmAction = AlarmAction.CGM_ACKNOWLEDGE), + CGM_WARMUP_DONE(NORMAL, CGM), + CGM_SECOND_SENSOR_READY(NORMAL, CGM), + + /** The test button of a CGM alarm: its sound and text, once, until the user dismisses it. */ + CGM_ALARM_TEST(URGENT, CGM); companion object { diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt index 1eb8e4182d96..1afe59162962 100644 --- a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/rx/weardata/EventData.kt @@ -672,4 +672,29 @@ sealed class EventData : Event() { val durations: List, val title: String = "" ) : EventData() + + // CGM alarms. Appended at the END of the class on purpose, so nothing above them moves. + + /** + * Mobile -> Wear: a CGM alarm is going off on the phone (sent again for each reminder). The watch + * shows it with an Acknowledge button and vibrates through its silent mode, for [vibrationSeconds] + * (0 = no vibration), stronger when [urgent]. [id] is the `CgmAlarmType.id`, so a later + * [CgmAlarmCancel] or [CgmAlarmAcknowledge] can name it. + */ + @Serializable + data class CgmAlarm( + val id: String, + val title: String, + val message: String, + val vibrationSeconds: Int, + val urgent: Boolean + ) : EventData() + + /** Mobile -> Wear: the CGM alarm [id] is over (acknowledged somewhere, or its cause is gone). Stop and remove it. */ + @Serializable + data class CgmAlarmCancel(val id: String) : EventData() + + /** Wear -> Mobile: the wearer acknowledged the CGM alarm [id] on the watch. */ + @Serializable + data class CgmAlarmAcknowledge(val id: String) : EventData() } diff --git a/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt new file mode 100644 index 000000000000..d6b750cc4e5d --- /dev/null +++ b/core/interfaces/src/commonMain/kotlin/app/aaps/core/interfaces/source/CgmSensorAlerts.kt @@ -0,0 +1,179 @@ +package app.aaps.core.interfaces.source + +/** + * Implemented by a [BgSource] that knows the state of its sensor and wants AAPS to raise the + * sensor alarms for it (sensor failed, ended, ending soon, no signal, sensor issue, warm-up done, + * second sensor ready). + * + * Optional: a source that does not implement it gets no sensor alarm at all, and nothing changes + * for it. The alarms are raised in one central place (`LocalAlertUtils.checkGlucoseAlerts`), which + * reads the active source as `activeBgSource as? CgmSensorAlertProvider`. + * + * The source only says what is true now. The user settings (which alarm is on, how long a signal + * may be lost before it warns, how often it repeats) are applied by the central check. The one + * exception is the warning time before the end, which the check passes in, see + * [CgmSensorAlertState.Expiring]. + * + * "Ending soon" and "ended" are measured against the end of the sensor's usable time, including + * any grace period the source knows of (a Dexcom ONE+ / G7 has 12 hours). The + * source shows the same end on its own status screen. + * + * The alarms only notify. Nothing here may change the glucose values the loop receives or dosing. + */ +interface CgmSensorAlertProvider { + + /** + * The most important sensor state at [nowMs]. One state at a time, in this order: + * [CgmSensorAlertState.Failed] > [CgmSensorAlertState.Expired] > [CgmSensorAlertState.SignalLost] > + * [CgmSensorAlertState.SensorIssue] > [CgmSensorAlertState.Expiring] > + * [CgmSensorAlertState.SecondSensorReady] > [CgmSensorAlertState.WarmupDone] > [CgmSensorAlertState.Ok]. + * + * A stopped source answers [CgmSensorAlertState.Ok]. + * + * A function and not a flow on purpose: several states only depend on the clock (ending soon, + * ended, no reading for a while), so the answer is computed when it is asked for. It must be + * cheap and safe to call from any thread. [CgmSensorAlertRules.map] holds the order, so every + * source keeps the same one. + * + * @param expiringLeadMs how long before the end the user wants "ending soon". Before that the + * source must not answer [CgmSensorAlertState.Expiring], so that a less important state, for + * example a ready second sensor, is not hidden while there is nothing to warn about yet. + */ + fun sensorAlertState(nowMs: Long, expiringLeadMs: Long): CgmSensorAlertState +} + +/** + * State of the sensor, for the sensor alarms. Times are wall-clock epoch ms. + * + * Each timestamp also names the episode: the same state with the same timestamp is the same + * episode, and its alarm is raised only once for it. + */ +sealed interface CgmSensorAlertState { + + /** Nothing to report. */ + data object Ok : CgmSensorAlertState + + /** The first usable reading after a warm-up arrived at [atEpochMs]. */ + data class WarmupDone(val atEpochMs: Long) : CgmSensorAlertState + + /** The usable time of the sensor ends at [endsAtEpochMs], including any grace period. */ + data class Expiring(val endsAtEpochMs: Long) : CgmSensorAlertState + + /** + * The usable time of the sensor ended at [atEpochMs], including any grace period. + * + * [atEpochMs] must stay the same for the whole episode: the end of the usable time when the + * source knows it, also when the sensor reports its end by itself and after an app restart. + * Never the moment a message happened to be seen, because each new value is a new episode and + * sounds the alarm again. + */ + data class Expired(val atEpochMs: Long) : CgmSensorAlertState + + /** The sensor cannot be used. No free text, so the user always sees a translated message. */ + data class Failed(val reason: CgmSensorFailure) : CgmSensorAlertState + + /** + * There has been no link to the sensor, or no reading from it, since [sinceEpochMs]. The source + * says so at once; the central check waits for the delay the user has set before it warns, and + * it counts that delay from [sinceEpochMs]. + */ + data class SignalLost(val sinceEpochMs: Long) : CgmSensorAlertState + + /** + * The sensor is linked and sends, but without a usable glucose value (for example too much + * noise), since [sinceEpochMs]. It has not failed and has not ended. The central check waits for + * the delay the user has set, counted from [sinceEpochMs]. + */ + data class SensorIssue(val sinceEpochMs: Long) : CgmSensorAlertState + + /** A pre-soaked second sensor is ready since [atEpochMs], so the user can switch to it. */ + data class SecondSensorReady(val atEpochMs: Long) : CgmSensorAlertState +} + +/** Why a sensor cannot be used, see [CgmSensorAlertState.Failed]. */ +enum class CgmSensorFailure { + + /** The sensor itself reports a fault. */ + SENSOR_ERROR, + + /** The sensor stopped before the end of its life. */ + ENDED_EARLY, + + /** Any other final failure, for example the sensor cannot be paired. */ + OTHER +} + +/** + * The priority order of [CgmSensorAlertProvider.sensorAlertState], in one place, so every source + * answers the same way. A source fills [Input] from what its driver knows and calls [map]. + * + * Pure: no clock of its own, no platform code. + */ +object CgmSensorAlertRules { + + /** + * No reading for this long, while a reading is expected, is a lost signal. This only makes the + * state visible: the central check waits for the delay the user has set before it warns. + */ + const val SILENCE_MS: Long = 5L * 60L * 1000L + + /** + * Everything the order needs. Times are wall-clock epoch ms. + * + * @param stopped the source is stopped: no state at all. + * @param sensorStored a sensor is set up in the main slot. Without one only a ready second + * sensor is worth a message. + * @param failure the sensor cannot be used, null when it can. + * @param endedBySensor the sensor itself says its session has ended. It is [CgmSensorAlertState.Expired] + * when the usable time is over, else [CgmSensorFailure.ENDED_EARLY]. + * @param expiresAtMs end of the usable time including any grace period, null when not known. + * @param linkLostSinceMs the link is down since then, null while it is up. + * @param lastReadingAtMs the last usable reading, null when none yet. + * @param readingExpected false while no reading comes on purpose (warm-up, pairing), so silence + * is not a lost signal then. + * @param issueSinceMs the sensor sends without a usable value since then, null when it does not. + * @param secondSensorReadyAtMs a pre-soak sensor is ready since then, null when it is not. + * @param warmupDoneAtMs the first usable reading after a warm-up, null when none or too old. + * @param expiringLeadMs see [CgmSensorAlertProvider.sensorAlertState]. + */ + data class Input( + val stopped: Boolean, + val sensorStored: Boolean, + val failure: CgmSensorFailure?, + val endedBySensor: Boolean, + val expiresAtMs: Long?, + val linkLostSinceMs: Long?, + val lastReadingAtMs: Long?, + val readingExpected: Boolean, + val issueSinceMs: Long?, + val secondSensorReadyAtMs: Long?, + val warmupDoneAtMs: Long?, + val expiringLeadMs: Long, + val nowMs: Long, + ) + + fun map(input: Input): CgmSensorAlertState { + if (input.stopped) return CgmSensorAlertState.Ok + if (!input.sensorStored) { + return input.secondSensorReadyAtMs?.let { CgmSensorAlertState.SecondSensorReady(it) } ?: CgmSensorAlertState.Ok + } + val now = input.nowMs + val expiresAt = input.expiresAtMs + // The end, once it has come. Null before it, or when the end is not known. + val endedAt = expiresAt?.takeIf { now >= it } + input.failure?.let { return CgmSensorAlertState.Failed(it) } + if (input.endedBySensor) { + return if (endedAt != null) CgmSensorAlertState.Expired(endedAt) + else CgmSensorAlertState.Failed(CgmSensorFailure.ENDED_EARLY) + } + if (endedAt != null) return CgmSensorAlertState.Expired(endedAt) + input.linkLostSinceMs?.let { return CgmSensorAlertState.SignalLost(it) } + val last = input.lastReadingAtMs + if (last != null && input.readingExpected && now - last >= SILENCE_MS) return CgmSensorAlertState.SignalLost(last) + input.issueSinceMs?.let { return CgmSensorAlertState.SensorIssue(it) } + if (expiresAt != null && expiresAt - now <= input.expiringLeadMs) return CgmSensorAlertState.Expiring(expiresAt) + input.secondSensorReadyAtMs?.let { return CgmSensorAlertState.SecondSensorReady(it) } + input.warmupDoneAtMs?.let { return CgmSensorAlertState.WarmupDone(it) } + return CgmSensorAlertState.Ok + } +} diff --git a/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt b/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt new file mode 100644 index 000000000000..f0a16dfeca85 --- /dev/null +++ b/core/interfaces/src/commonTest/kotlin/app/aaps/core/interfaces/source/CgmSensorAlertRulesTest.kt @@ -0,0 +1,101 @@ +package app.aaps.core.interfaces.source + +import kotlin.test.Test +import kotlin.test.assertEquals + +/** The priority order of [CgmSensorAlertRules.map], the same for every BG source. */ +class CgmSensorAlertRulesTest { + + private val now = 1_000_000_000L + private val hour = 3_600_000L + + private fun input( + stopped: Boolean = false, + sensorStored: Boolean = true, + failure: CgmSensorFailure? = null, + endedBySensor: Boolean = false, + expiresAtMs: Long? = now + 100 * hour, + linkLostSinceMs: Long? = null, + lastReadingAtMs: Long? = now, + readingExpected: Boolean = true, + issueSinceMs: Long? = null, + secondSensorReadyAtMs: Long? = null, + warmupDoneAtMs: Long? = null, + expiringLeadMs: Long = 12 * hour, + ) = CgmSensorAlertRules.Input( + stopped, sensorStored, failure, endedBySensor, expiresAtMs, linkLostSinceMs, lastReadingAtMs, readingExpected, + issueSinceMs, secondSensorReadyAtMs, warmupDoneAtMs, expiringLeadMs, now + ) + + private fun map(i: CgmSensorAlertRules.Input) = CgmSensorAlertRules.map(i) + + @Test + fun aHealthySensorIsOk() { + assertEquals(CgmSensorAlertState.Ok, map(input())) + } + + @Test + fun aStoppedSourceSaysNothing() { + assertEquals(CgmSensorAlertState.Ok, map(input(stopped = true, failure = CgmSensorFailure.SENSOR_ERROR))) + } + + @Test + fun withoutASensorOnlyAReadySecondSensorCounts() { + assertEquals(CgmSensorAlertState.Ok, map(input(sensorStored = false, linkLostSinceMs = now - hour))) + assertEquals(CgmSensorAlertState.SecondSensorReady(5L), map(input(sensorStored = false, secondSensorReadyAtMs = 5L))) + } + + @Test + fun failureComesFirst() { + assertEquals( + CgmSensorAlertState.Failed(CgmSensorFailure.SENSOR_ERROR), + map(input(failure = CgmSensorFailure.SENSOR_ERROR, expiresAtMs = now - hour, linkLostSinceMs = now - hour)) + ) + } + + @Test + fun anEndTheSensorReportsIsExpiredAfterTheUsableTimeElseEndedEarly() { + val endsAt = now - hour + assertEquals(CgmSensorAlertState.Expired(endsAt), map(input(endedBySensor = true, expiresAtMs = endsAt))) + assertEquals(CgmSensorAlertState.Failed(CgmSensorFailure.ENDED_EARLY), map(input(endedBySensor = true))) + } + + @Test + fun theEndKeepsItsTimeSoItIsOneEpisode() { + val endsAt = now - hour + assertEquals(CgmSensorAlertState.Expired(endsAt), map(input(expiresAtMs = endsAt))) + assertEquals(CgmSensorAlertState.Expired(endsAt), map(input(expiresAtMs = endsAt, linkLostSinceMs = now - 1))) + } + + @Test + fun aLostLinkOrSilenceIsASignalLoss() { + assertEquals(CgmSensorAlertState.SignalLost(now - 60_000L), map(input(linkLostSinceMs = now - 60_000L))) + val last = now - CgmSensorAlertRules.SILENCE_MS + assertEquals(CgmSensorAlertState.SignalLost(last), map(input(lastReadingAtMs = last))) + assertEquals(CgmSensorAlertState.Ok, map(input(lastReadingAtMs = last + 1))) + // No reading on purpose (warm-up): silence is not a loss. + assertEquals(CgmSensorAlertState.Ok, map(input(lastReadingAtMs = now - hour, readingExpected = false))) + } + + @Test + fun aSensorIssueComesAfterASignalLoss() { + assertEquals(CgmSensorAlertState.SensorIssue(7L), map(input(issueSinceMs = 7L))) + assertEquals(CgmSensorAlertState.SignalLost(3L), map(input(issueSinceMs = 7L, linkLostSinceMs = 3L))) + } + + @Test + fun endingSoonOnlyInsideTheLeadTime() { + val endsAt = now + 12 * hour + assertEquals(CgmSensorAlertState.Expiring(endsAt), map(input(expiresAtMs = endsAt))) + assertEquals(CgmSensorAlertState.Ok, map(input(expiresAtMs = endsAt + 1))) + // Before the lead time a ready second sensor is not hidden. + assertEquals(CgmSensorAlertState.SecondSensorReady(9L), map(input(expiresAtMs = endsAt + 1, secondSensorReadyAtMs = 9L))) + assertEquals(CgmSensorAlertState.Expiring(endsAt), map(input(expiresAtMs = endsAt, secondSensorReadyAtMs = 9L))) + } + + @Test + fun warmupDoneIsTheLeastImportant() { + assertEquals(CgmSensorAlertState.WarmupDone(4L), map(input(warmupDoneAtMs = 4L))) + assertEquals(CgmSensorAlertState.SecondSensorReady(9L), map(input(warmupDoneAtMs = 4L, secondSensorReadyAtMs = 9L))) + } +} diff --git a/core/keys/src/androidMain/res/values/strings.xml b/core/keys/src/androidMain/res/values/strings.xml index d67a29bbd3af..3316b16f7b0c 100644 --- a/core/keys/src/androidMain/res/values/strings.xml +++ b/core/keys/src/androidMain/res/values/strings.xml @@ -36,6 +36,66 @@ Gradually increase notification volume Override Do Not Disturb mode On: alarms ring even when the phone is silent or in Do Not Disturb. Off: alarms do not ring then. In Do Not Disturb they only vibrate. + AAPS sound + Alert on low glucose + Sound an alarm when glucose is at or below the low threshold. + Low glucose alarm threshold + Alert on high glucose + Notify when glucose is at or above the high threshold. + High glucose alarm threshold + Alert on rapid fall + Sound an alarm when glucose drops by at least the configured amount within the configured time window. + Rapid fall drop threshold + How much glucose must drop to sound the alarm. Always in mg/dL, also when AAPS shows mmol/L (18 mg/dL is about 1 mmol/L). + Rapid fall time window + Urgent low alarm + Sound an alarm when glucose is at or below 55 mg/dL (3.1 mmol/L). The mute timer never silences it. + Urgent low soon alarm + Sound an alarm when glucose is falling and will be at or below 55 mg/dL (3.1 mmol/L) within 20 minutes. + Alert on rapid rise + Notify when glucose rises by at least the set amount within the set time window. + Rapid rise threshold + How much glucose must rise for the alarm. Always in mg/dL, also when AAPS shows mmol/L (18 mg/dL is about 1 mmol/L). + Rapid rise time window + Delay the first alarm + The alarm goes off only when the condition has lasted this long. 0 = at once. + Repeat after acknowledge + An alarm that is not acknowledged goes off again every 5 minutes. After you acknowledge it, it stays quiet this long, then goes off again if the cause is still there. 0 = not again until the cause has gone. + An alarm that is not acknowledged goes off again every 5 minutes. After you acknowledge it, it stays quiet this long, then goes off again if glucose is still urgent low. It always comes back, after 30 minutes at most. + Sound + The AAPS sound is the standard AAPS alarm sound. Without sound, the alarm shows a notification only. + No sound + Trio acoustic, mild + Trio acoustic, medium + Trio acoustic, harsh + Trio electronic, mild + Trio electronic, medium + Trio electronic, harsh + Glass bell + Harp + Meow + Saw wave + Hard saw wave + Sine wave + Open can + Open wrapper + Alert when the CGM sensor fails + Sound an alarm when the sensor reports an error or cannot be used. Only for BG sources that report their sensor state. + Alert when the CGM sensor has ended + Sound an alarm when the usable time of the sensor has ended. Only for BG sources that report their sensor state. + Warn before the CGM sensor ends + Notify some hours before the usable time of the sensor ends, so you can prepare a new sensor. Only for BG sources that report their sensor state. + Warn this long before the sensor ends + Alert on lost CGM signal + Notify when the phone has had no link to the sensor, or no reading from it, for some time. Only for BG sources that report their sensor state. + Signal lost for at least + Alert on a CGM sensor issue + Notify when the sensor is linked but sends no usable glucose value, for example because of noise. Only for BG sources that report their sensor state. + Sensor issue for at least + Notify when sensor warm-up is done + Notify when a new sensor sends its first usable reading. Only for BG sources that report their sensor state. + Notify when a second sensor is ready + Notify when a pre-soaked second sensor is ready and you can switch to it. Only for BG sources that support a second sensor. Upload BG data to NS diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt index 6717d798a66c..cb3de1d60680 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/BooleanKey.kt @@ -83,6 +83,22 @@ enum class BooleanKey( ), AlertIncreaseVolume("gradually_increase_notification_volume", true, KeysStrings.pref_title_alert_increase_volume), AlertOverrideDoNotDisturb("alert_override_dnd", true, KeysStrings.pref_title_alert_override_dnd, KeysStrings.pref_summary_alert_override_dnd, defaultedBySM = true), + // CGM alarms (see CgmAlarmType). The glucose alarms are off by default: the user opts in. + AlertHypo("enable_hypo_alert", false, KeysStrings.pref_title_alert_hypo, KeysStrings.pref_summary_alert_hypo), + AlertHyper("enable_hyper_alert", false, KeysStrings.pref_title_alert_hyper, KeysStrings.pref_summary_alert_hyper), + AlertRapidFall("enable_rapid_fall_alert", false, KeysStrings.pref_title_alert_rapid_fall, KeysStrings.pref_summary_alert_rapid_fall), + AlertUrgentLow("enable_cgm_urgent_low_alert", false, KeysStrings.pref_title_alert_urgent_low, KeysStrings.pref_summary_alert_urgent_low), + AlertUrgentLowSoon("enable_cgm_urgent_low_soon_alert", false, KeysStrings.pref_title_alert_urgent_low_soon, KeysStrings.pref_summary_alert_urgent_low_soon), + AlertRapidRise("enable_cgm_rise_rate_alert", false, KeysStrings.pref_title_alert_rapid_rise, KeysStrings.pref_summary_alert_rapid_rise), + // Sensor state alarms. They are raised only for a BG source that reports its sensor state + // (CgmSensorAlertProvider); for every other source they do nothing, so they can default to on. + AlertCgmSensorFailed("enable_cgm_sensor_failed_alert", true, KeysStrings.pref_title_alert_cgm_sensor_failed, KeysStrings.pref_summary_alert_cgm_sensor_failed), + AlertCgmSensorExpired("enable_cgm_sensor_expired_alert", true, KeysStrings.pref_title_alert_cgm_sensor_expired, KeysStrings.pref_summary_alert_cgm_sensor_expired), + AlertCgmSensorExpiring("enable_cgm_sensor_expiring_alert", true, KeysStrings.pref_title_alert_cgm_sensor_expiring, KeysStrings.pref_summary_alert_cgm_sensor_expiring), + AlertCgmSignalLost("enable_cgm_signal_lost_alert", true, KeysStrings.pref_title_alert_cgm_signal_lost, KeysStrings.pref_summary_alert_cgm_signal_lost), + AlertCgmSensorIssue("enable_cgm_sensor_issue_alert", true, KeysStrings.pref_title_alert_cgm_sensor_issue, KeysStrings.pref_summary_alert_cgm_sensor_issue), + AlertCgmWarmupDone("enable_cgm_warmup_done_alert", true, KeysStrings.pref_title_alert_cgm_warmup_done, KeysStrings.pref_summary_alert_cgm_warmup_done), + AlertCgmSecondSensorReady("enable_cgm_second_sensor_ready_alert", true, KeysStrings.pref_title_alert_cgm_second_sensor_ready, KeysStrings.pref_summary_alert_cgm_second_sensor_ready), BgSourceUploadToNs("dexcomg5_nsupload", true, KeysStrings.pref_title_bg_source_upload_to_ns, defaultedBySM = true, hideParentScreenIfHidden = true, defaultedByHardenedMode = true), BgSourceCreateSensorChange("dexcom_lognssensorchange", true, KeysStrings.pref_title_bg_source_create_sensor_change, KeysStrings.pref_summary_bg_source_create_sensor_change, defaultedBySM = true), diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt index 6a99e2e4df9b..a66c15292734 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/IntKey.kt @@ -413,6 +413,195 @@ enum class IntKey( dependency = BooleanKey.AlertPumpUnreachable, unitType = UnitType.MIN ), + /** + * Rapid-fall drop size: a glucose *difference*, stored and shown in mg/dL for both unit settings. + * + * It must NOT be a `UnitDoubleKey`. That type guesses the unit from the number (below 36 means + * mmol/L), which is right for a glucose level but wrong for a small difference: 30 mg/dL was shown + * as 540, and a typed 25 was stored as 450, so the alarm could never fire. The key string ends in + * `_mgdl` because the old `alert_rapid_fall_drop` holds a float, which an int read cannot load, + * and its value was often wrong. `PreferenceMigrations` copies the old value once, and only when + * it is inside 15-60 mg/dL; any other old value is dropped and the default applies. + */ + AlertRapidFallDrop( + key = "alert_rapid_fall_drop_mgdl", + defaultValue = 30, + min = 15, + max = 60, + title = KeysStrings.pref_title_alert_rapid_fall_drop, + summary = KeysStrings.pref_summary_alert_rapid_fall_drop, + dependency = BooleanKey.AlertRapidFall, + unitType = UnitType.MGDL + ), + AlertRapidFallWindow( + key = "alert_rapid_fall_window", + defaultValue = 15, + min = 5, + max = 30, + title = KeysStrings.pref_title_alert_rapid_fall_window, + dependency = BooleanKey.AlertRapidFall, + unitType = UnitType.MIN + ), + /** Rise rate alarm: how much glucose must rise within [AlertRapidRiseWindow]. A difference, so mg/dL always, like [AlertRapidFallDrop]. */ + AlertRapidRiseAmount( + key = "alert_rapid_rise_mgdl", + defaultValue = 30, + min = 15, + max = 60, + title = KeysStrings.pref_title_alert_rapid_rise_amount, + summary = KeysStrings.pref_summary_alert_rapid_rise_amount, + dependency = BooleanKey.AlertRapidRise, + unitType = UnitType.MGDL + ), + AlertRapidRiseWindow( + key = "alert_rapid_rise_window", + defaultValue = 15, + min = 5, + max = 30, + title = KeysStrings.pref_title_alert_rapid_rise_window, + dependency = BooleanKey.AlertRapidRise, + unitType = UnitType.MIN + ), + /** High alarm: how long glucose must stay high before the first alarm. 0 = at once. */ + AlertHyperDelay( + key = "alert_cgm_high_delay_minutes", + defaultValue = 0, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_delay_first, + summary = KeysStrings.pref_summary_alert_delay_first, + dependency = BooleanKey.AlertHyper, + unitType = UnitType.MIN + ), + AlertCgmExpiringLeadHours( + key = "alert_cgm_expiring_lead_hours", + defaultValue = 12, + min = 1, + max = 48, + title = KeysStrings.pref_title_alert_cgm_expiring_lead, + dependency = BooleanKey.AlertCgmSensorExpiring, + unitType = UnitType.HOURS + ), + AlertCgmSignalLostMinutes( + key = "alert_cgm_signal_lost_minutes", + defaultValue = 10, + min = 5, + max = 60, + title = KeysStrings.pref_title_alert_cgm_signal_lost_delay, + dependency = BooleanKey.AlertCgmSignalLost, + unitType = UnitType.MIN + ), + AlertCgmSensorIssueMinutes( + key = "alert_cgm_sensor_issue_minutes", + defaultValue = 20, + min = 0, + max = 60, + title = KeysStrings.pref_title_alert_cgm_sensor_issue_delay, + dependency = BooleanKey.AlertCgmSensorIssue, + unitType = UnitType.MIN + ), + // Repeat after "Acknowledge": the alarm stays quiet this long, then goes off again if its cause is + // still there. 0 = not again until the cause has gone. Urgent low always comes back, within 30 min. + AlertUrgentLowRepeat( + key = "alert_cgm_urgent_low_repeat_minutes", + defaultValue = 30, + min = 5, + max = 30, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat_urgent_low, + dependency = BooleanKey.AlertUrgentLow, + unitType = UnitType.MIN + ), + AlertUrgentLowSoonRepeat( + key = "alert_cgm_urgent_low_soon_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertUrgentLowSoon, + unitType = UnitType.MIN + ), + AlertHypoRepeat( + key = "alert_cgm_low_repeat_minutes", + defaultValue = 15, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertHypo, + unitType = UnitType.MIN + ), + AlertRapidFallRepeat( + key = "alert_cgm_fall_rate_repeat_minutes", + defaultValue = 15, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertRapidFall, + unitType = UnitType.MIN + ), + AlertHyperRepeat( + key = "alert_cgm_high_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertHyper, + unitType = UnitType.MIN + ), + AlertRapidRiseRepeat( + key = "alert_cgm_rise_rate_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertRapidRise, + unitType = UnitType.MIN + ), + AlertCgmSensorFailedRepeat( + key = "alert_cgm_sensor_failed_repeat_minutes", + defaultValue = 0, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSensorFailed, + unitType = UnitType.MIN + ), + AlertCgmSensorExpiredRepeat( + key = "alert_cgm_sensor_expired_repeat_minutes", + defaultValue = 0, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSensorExpired, + unitType = UnitType.MIN + ), + AlertCgmSignalLostRepeat( + key = "alert_cgm_signal_lost_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSignalLost, + unitType = UnitType.MIN + ), + AlertCgmSensorIssueRepeat( + key = "alert_cgm_sensor_issue_repeat_minutes", + defaultValue = 30, + min = 0, + max = 240, + title = KeysStrings.pref_title_alert_repeat, + summary = KeysStrings.pref_summary_alert_repeat, + dependency = BooleanKey.AlertCgmSensorIssue, + unitType = UnitType.MIN + ), AutotuneDefaultTuneDays(key = "autotune_default_tune_days", defaultValue = 5, min = 1, max = 30, title = KeysStrings.pref_title_autotune_days, summary = KeysStrings.autotune_default_tune_days_summary, unitType = UnitType.DAYS), diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt index fe63d715743f..b4c84e7edb64 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/StringKey.kt @@ -230,8 +230,126 @@ enum class StringKey( validator = StringValidator.minLength(17) ), + // Sound of each CGM alarm: "default" (the standard AAPS alarm sound), "none" (notification only), + // or a Trio sound (see core/ui/SOUNDS.md). The value of a Trio sound is its file name. Urgent low + // has no "none". + AlertUrgentLowSound( + key = "alert_cgm_urgent_low_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("ulg", allowNone = false), + dependency = BooleanKey.AlertUrgentLow, + ), + AlertUrgentLowSoonSound( + key = "alert_cgm_urgent_low_soon_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("lgs", allowNone = true), + dependency = BooleanKey.AlertUrgentLowSoon, + ), + AlertHypoSound( + key = "alert_cgm_low_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("lg", allowNone = true), + dependency = BooleanKey.AlertHypo, + ), + AlertRapidFallSound( + key = "alert_cgm_fall_rate_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("lgs", allowNone = true), + dependency = BooleanKey.AlertRapidFall, + ), + AlertHyperSound( + key = "alert_cgm_high_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("hg", allowNone = true), + dependency = BooleanKey.AlertHyper, + ), + AlertRapidRiseSound( + key = "alert_cgm_rise_rate_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("hg", allowNone = true), + dependency = BooleanKey.AlertRapidRise, + ), + AlertCgmSensorFailedSound( + key = "alert_cgm_sensor_failed_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dcr", allowNone = true), + dependency = BooleanKey.AlertCgmSensorFailed, + ), + AlertCgmSensorExpiredSound( + key = "alert_cgm_sensor_ended_sound", + defaultValue = "default", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dts", allowNone = true), + dependency = BooleanKey.AlertCgmSensorExpired, + ), + AlertCgmSignalLostSound( + key = "alert_cgm_signal_loss_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dts", allowNone = true), + dependency = BooleanKey.AlertCgmSignalLost, + ), + AlertCgmSensorIssueSound( + key = "alert_cgm_sensor_issue_sound", + defaultValue = "none", + title = KeysStrings.pref_title_alert_cgm_sound, + summary = KeysStrings.pref_summary_alert_cgm_sound, + preferenceType = PreferenceType.LIST, + entriesRefs = cgmAlarmSoundEntries("dts", allowNone = true), + dependency = BooleanKey.AlertCgmSensorIssue, + ), + ; override val entries: Map = entriesRefs + entriesLiterals.mapValues { TextRef.Literal(it.value) } } + +/** + * The sound choices of one CGM alarm: the AAPS sound, no sound (unless [allowNone] is false), the six + * Trio sounds made for [trioSet] (acoustic and electronic, mild to harsh), then the eight Trio tones. + * The value of a Trio sound is its file name in `core/ui/res/raw`, which `AlarmSound.fileName` holds. + */ +private fun cgmAlarmSoundEntries(trioSet: String, allowNone: Boolean): Map = buildMap { + put("default", KeysStrings.alert_sound_default) + if (allowNone) put("none", KeysStrings.alert_sound_none) + put("trio_acoustic_${trioSet}_mild", KeysStrings.alert_sound_trio_acoustic_mild) + put("trio_acoustic_${trioSet}_medium", KeysStrings.alert_sound_trio_acoustic_medium) + put("trio_acoustic_${trioSet}_harsh", KeysStrings.alert_sound_trio_acoustic_harsh) + put("trio_electronic_${trioSet}_mild", KeysStrings.alert_sound_trio_electronic_mild) + put("trio_electronic_${trioSet}_medium", KeysStrings.alert_sound_trio_electronic_medium) + put("trio_electronic_${trioSet}_harsh", KeysStrings.alert_sound_trio_electronic_harsh) + put("trio_tone_glass_bell", KeysStrings.alert_sound_trio_glass_bell) + put("trio_tone_harp", KeysStrings.alert_sound_trio_harp) + put("trio_tone_meow", KeysStrings.alert_sound_trio_meow) + put("trio_tone_saw_wave", KeysStrings.alert_sound_trio_saw_wave) + put("trio_tone_hard_saw_wave", KeysStrings.alert_sound_trio_hard_saw_wave) + put("trio_tone_sine_wave", KeysStrings.alert_sound_trio_sine_wave) + put("trio_tone_open_can", KeysStrings.alert_sound_trio_open_can) + put("trio_tone_open_wrapper", KeysStrings.alert_sound_trio_open_wrapper) +} diff --git a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt index f6777ce1b9da..5ba65c162f59 100644 --- a/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt +++ b/core/keys/src/commonMain/kotlin/app/aaps/core/keys/UnitDoubleKey.kt @@ -32,7 +32,25 @@ enum class UnitDoubleKey( defaultedBySM = true, dependency = BooleanKey.ApsUseDynamicSensitivity, sync = SyncSpec(SyncChannel.Cold, SyncDirection.Bidirectional) + ), + AlertHypoThreshold( + key = "alert_hypo_threshold", + defaultValue = 70.0, + minMgdl = 50, + maxMgdl = 100, + title = KeysStrings.pref_title_alert_hypo_threshold, + dependency = BooleanKey.AlertHypo + ), + AlertHyperThreshold( + key = "alert_hyper_threshold", + defaultValue = 250.0, + minMgdl = 140, + maxMgdl = 400, + title = KeysStrings.pref_title_alert_hyper_threshold, + dependency = BooleanKey.AlertHyper ) + // The rapid-fall drop size is a glucose difference, so it is the IntKey `AlertRapidFallDrop` in + // mg/dL: this type guesses the unit from the number and gets small differences wrong. ; } diff --git a/core/ui/SOUNDS.md b/core/ui/SOUNDS.md new file mode 100644 index 000000000000..f1f2242acc24 --- /dev/null +++ b/core/ui/SOUNDS.md @@ -0,0 +1,73 @@ +# Alarm sounds + +## The Trio sounds (`src/androidMain/res/raw/trio_*.m4a`) + +The CGM alarm sounds in `src/androidMain/res/raw/trio_*.m4a` come from Trio, the open source app +for people with diabetes on iOS. The CGM alarms (Preferences > Alerts > CGM alarms) can use them, +on Android and on iOS. The iOS app copies the same files into its bundle when it is built, so +there is only one set. + +- Source: [nightscout/Trio pull request 1645](https://github.com/nightscout/Trio/pull/1645), + "Rework Trio Alarm Sounds: Add Urgency Levels and Voice Alarms", merged on 2026-10-19 + (commit `cd6ad0706db1e7a546360d4631f75b24a402ba58`). +- Brought into Trio by Deniz Cengiz ([dnzxy](https://github.com/dnzxy)). +- The sounds were designed for Trio by a sound designer who is a diabetes dad and Trio user, and + who wants to stay anonymous. +- We took the files, already converted, from nightscout/AndroidAPS pull request 5397 (Dexcom G7 + direct, by t1dude), path `cgm/dexcomg7/src/main/res/raw/g7_*.m4a` at commit `bec1b16ba20`. + +Thank you to all of them. + +### What we took + +- The Acoustic and Electronic sets, each at three urgency levels (mild, medium, harsh), for these + Trio alarms: urgent low (`ulg`), low (`lg`), low soon (`lgs`), high (`hg`), device critical (`dcr`) + and device time-sensitive (`dts`). +- Eight extra tones from the same pull request: glass bell, harp, meow, saw wave, hard saw wave, + sine wave, open can and open wrapper. + +Not taken: the carbs required set, the spoken alarms, and the older Trio tones. + +### What was changed + +- In pull request 5397: converted from CAF (16-bit PCM) to AAC at 96 kbit/s in an `.m4a` file, + because Android does not play CAF (`afconvert -f m4af -d aac -b 96000` on macOS). +- Here: renamed from `g7_