diff --git a/app/src/testFull/kotlin/app/aaps/lifecycle/PluginLifetimeWorkScanTest.kt b/app/src/testFull/kotlin/app/aaps/lifecycle/PluginLifetimeWorkScanTest.kt index ee274e528140..ea23a245348a 100644 --- a/app/src/testFull/kotlin/app/aaps/lifecycle/PluginLifetimeWorkScanTest.kt +++ b/app/src/testFull/kotlin/app/aaps/lifecycle/PluginLifetimeWorkScanTest.kt @@ -52,6 +52,9 @@ class PluginLifetimeWorkScanTest { "SignatureVerifierPlugin#onStart" to "onStop removes the callbacks, quits the looper and nulls the handler", "OmnipodDashPumpPlugin#scope" to "onStop cancels the scope and tears the handler down", "OmnipodDashPumpPlugin#onStart" to "onStop cancels the scope and tears the handler down", + "O5PumpPlugin#scope" to "the statusChecker that the init block re-posts is removed in onStop, which also nulls the handler", + "O5PumpPlugin#armStatusChecker" to "onStop removes the statusChecker callbacks and nulls the handler", + "O5PumpPlugin#onStart" to "onStop removes the statusChecker callbacks, nulls the handler and cancels the scope", "LoopPlugin#scheduleBuildAndStoreDeviceStatus" to "the job is held in deviceStatusJob and onStop cancels it", "LoopPlugin#scheduleSmbFallback" to "the deferred SMB re-run is held in smbFallbackJob and onStop cancels it", "XdripPlugin#onStart" to "onStop removes the callbacks first, then quits the looper", @@ -279,6 +282,11 @@ class PluginLifetimeWorkScanTest { "readStatus(unconfirmed_command). A read. SAFE to abandon - but see handleCommandConfirmation " + "below, which is the reason unconfirmed commands are being chased in the first place." ), + "O5PumpPlugin.kt#refreshStatusOnUnacknowledgedCommands" to Site( + 1, + "readStatus(omnipod_5_unconfirmed_command). A copy of OmnipodDashPumpPlugin#refreshStatusOnUnacknowledgedCommands. " + + "A read. SAFE to abandon." + ), "OmnipodErosPumpPlugin.kt#queueAcknowledgeAlertsCommand" to Site( 1, "customCommand(CommandSilenceAlerts), result only logged. Silencing an alert is a pod write, but " + @@ -302,6 +310,13 @@ class PluginLifetimeWorkScanTest { "actual harm here, because it is the only record that the correction worked. Cancelling would " + "not stop the delivery anyway; the command is already in the queue by then. This is the site " + "that rules out a per-enable pluginScope for this driver." + ), + "O5PumpPlugin.kt#queueBasalCorrectionIfNeeded" to Site( + 1, + "customCommand(CommandDeliverBasalCorrection). DELIVERS INSULIN. The O5 copy of the correction in " + + "OmnipodDashPumpPlugin#handleCommandConfirmation, and the same decision: it must NOT be cancelled, " + + "and cancelling would not stop it anyway, because the command is already in the queue. The queued " + + "command checks the drift again before it sends anything. Rules out a per-enable pluginScope for O5 too." ) ) diff --git a/app/src/testFull/resources/prefs-schema.txt b/app/src/testFull/resources/prefs-schema.txt index c51f7e72cda4..1934dae936ca 100644 --- a/app/src/testFull/resources/prefs-schema.txt +++ b/app/src/testFull/resources/prefs-schema.txt @@ -24,6 +24,8 @@ AAPS.Omnipod.suspend_delivery_button_enabled|ErosBooleanPreferenceKey|true AAPS.Omnipod.tbr_beeps_enabled|OmnipodBooleanPreferenceKey|true AAPS.Omnipod.tbrs_set|ErosLongNonPreferenceKey|true AAPS.Omnipod.time_change_enabled|ErosBooleanPreferenceKey|true +AAPS.Omnipod5.pod_state|O5StringNonPreferenceKey|true +AAPS.Omnipod5.registration_data_encrypted|O5StringNonPreferenceKey|false AAPS.OmnipodDash.pod_state|DashStringNonPreferenceKey|true AAPS.RileyLink.LastGoodDeviceFrequency|RileyLinkDoubleKey|true AAPS.RileyLink.lastGoodDeviceCommunicationTime|RileyLinkLongKey|true @@ -365,6 +367,7 @@ nsclientinternal_api_secret|StringKey|true nsclientinternal_url|StringKey|true oh_charging_only|BooleanKey|true oh_wifi_only|BooleanKey|true +omnipod_5_certificate_store|O5IntentKey|false openaps_smb_min_5m_carbimpact|DoubleKey|true openapsama_autosens_period|IntKey|true openapsama_current_basal_safety_multiplier|DoubleKey|true diff --git a/core/data/src/commonMain/kotlin/app/aaps/core/data/pump/defs/PumpType.kt b/core/data/src/commonMain/kotlin/app/aaps/core/data/pump/defs/PumpType.kt index 91a3ee8d0423..367c991d957d 100644 --- a/core/data/src/commonMain/kotlin/app/aaps/core/data/pump/defs/PumpType.kt +++ b/core/data/src/commonMain/kotlin/app/aaps/core/data/pump/defs/PumpType.kt @@ -256,6 +256,26 @@ enum class PumpType( hasCustomUnreachableAlertCheck = false, supportBatteryLevel = false ), + OMNIPOD_5( + description = "Omnipod 5", + manufacturer = ManufacturerType.Insulet, + model = "5", + bolusSize = 0.05, + specialBolusSize = null, + extendedBolusSettings = DoseSettings(0.05, 30, 8 * 60, 0.05), + pumpTempBasalType = PumpTempBasalType.Absolute, + tbrSettings = DoseSettings(0.05, 30, 12 * 60, 0.0, 30.0), + specialBasalDurations = arrayOf(Capability.BasalRate_Duration30minAllowed), + baseBasalMinValue = 0.05, + baseBasalMaxValue = null, + baseBasalStep = 0.05, + baseBasalSpecialSteps = null, + isPatchPump = true, + maxReservoirReading = 50, + pumpCapability = PumpCapability.OmnipodCapabilities, + hasCustomUnreachableAlertCheck = false, + supportBatteryLevel = false + ), MEDTRONIC_512_712( description = "Medtronic 512/712", manufacturer = ManufacturerType.Medtronic, 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..9b6d0f2289c5 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 @@ -66,6 +66,7 @@ enum class Sources { Omnipod, //No entry currently OmnipodEros, OmnipodDash, //No entry currently + Omnipod5, EOPatch2, Equil, Medtrum, 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..6b74f219cec7 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 @@ -192,6 +192,7 @@ data class UserEntry( Omnipod, //No entry currently OmnipodEros, OmnipodDash, //No entry currently + Omnipod5, EOPatch2, Equil, Medtrum, diff --git a/database/impl/src/commonMain/kotlin/app/aaps/database/entities/embedments/InterfaceIDs.kt b/database/impl/src/commonMain/kotlin/app/aaps/database/entities/embedments/InterfaceIDs.kt index 45b6ba1f7e61..e3e19b48bceb 100644 --- a/database/impl/src/commonMain/kotlin/app/aaps/database/entities/embedments/InterfaceIDs.kt +++ b/database/impl/src/commonMain/kotlin/app/aaps/database/entities/embedments/InterfaceIDs.kt @@ -35,6 +35,7 @@ data class InterfaceIDs @Ignore constructor( DANA_RS_KOREAN, OMNIPOD_EROS, OMNIPOD_DASH, + OMNIPOD_5, MEDTRONIC_512_517, MEDTRONIC_515_715, MEDTRONIC_522_722, diff --git a/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/PumpTypeExtension.kt b/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/PumpTypeExtension.kt index 915e9fb8e4e5..21d35eb0b19f 100644 --- a/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/PumpTypeExtension.kt +++ b/database/persistence/src/commonMain/kotlin/app/aaps/database/persistence/converters/PumpTypeExtension.kt @@ -23,6 +23,7 @@ fun InterfaceIDs.PumpType.fromDb(): PumpType = InterfaceIDs.PumpType.DANA_I2 -> PumpType.DANA_I2 InterfaceIDs.PumpType.OMNIPOD_EROS -> PumpType.OMNIPOD_EROS InterfaceIDs.PumpType.OMNIPOD_DASH -> PumpType.OMNIPOD_DASH + InterfaceIDs.PumpType.OMNIPOD_5 -> PumpType.OMNIPOD_5 InterfaceIDs.PumpType.MEDTRONIC_512_517 -> PumpType.MEDTRONIC_512_712 InterfaceIDs.PumpType.MEDTRONIC_515_715 -> PumpType.MEDTRONIC_515_715 InterfaceIDs.PumpType.MEDTRONIC_522_722 -> PumpType.MEDTRONIC_522_722 @@ -66,6 +67,7 @@ fun PumpType.toDb(): InterfaceIDs.PumpType = PumpType.DANA_I2 -> InterfaceIDs.PumpType.DANA_I2 PumpType.OMNIPOD_EROS -> InterfaceIDs.PumpType.OMNIPOD_EROS PumpType.OMNIPOD_DASH -> InterfaceIDs.PumpType.OMNIPOD_DASH + PumpType.OMNIPOD_5 -> InterfaceIDs.PumpType.OMNIPOD_5 PumpType.MEDTRONIC_512_712 -> InterfaceIDs.PumpType.MEDTRONIC_512_517 PumpType.MEDTRONIC_515_715 -> InterfaceIDs.PumpType.MEDTRONIC_515_715 PumpType.MEDTRONIC_522_722 -> InterfaceIDs.PumpType.MEDTRONIC_522_722 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..b555f49e6a60 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 @@ -70,6 +70,7 @@ fun UserEntry.Sources.fromDb(): Sources = UserEntry.Sources.Omnipod -> Sources.Omnipod UserEntry.Sources.OmnipodEros -> Sources.OmnipodEros UserEntry.Sources.OmnipodDash -> Sources.OmnipodDash + UserEntry.Sources.Omnipod5 -> Sources.Omnipod5 UserEntry.Sources.EOPatch2 -> Sources.EOPatch2 UserEntry.Sources.Equil -> Sources.Equil UserEntry.Sources.Medtrum -> Sources.Medtrum @@ -158,6 +159,7 @@ fun Sources.toDb(): UserEntry.Sources = Sources.Omnipod -> UserEntry.Sources.Omnipod Sources.OmnipodEros -> UserEntry.Sources.OmnipodEros Sources.OmnipodDash -> UserEntry.Sources.OmnipodDash + Sources.Omnipod5 -> UserEntry.Sources.Omnipod5 Sources.EOPatch2 -> UserEntry.Sources.EOPatch2 Sources.Equil -> UserEntry.Sources.Equil Sources.Medtrum -> UserEntry.Sources.Medtrum diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ecedce8dffd4..b21b2ef41c6b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -123,6 +123,7 @@ androidx-legacy-support = { group = "androidx.legacy", name = "legacy-support-v1 androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycleRuntimeKtx" } androidx-documentfile = { group = "androidx.documentfile", name = "documentfile", version = "1.1.0" } androidx-preference = { group = "androidx.preference", name = "preference-ktx", version = "1.2.1" } +androidx-webkit = { group = "androidx.webkit", name = "webkit", version = "1.12.1" } androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" } androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" } androidx-room-rxjava3 = { group = "androidx.room", name = "room-rxjava3", version.ref = "room" } 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..a5bd3ee4bd6c 100644 --- a/implementation/src/commonMain/kotlin/app/aaps/implementation/userEntry/UserEntryPresentationHelperImpl.kt +++ b/implementation/src/commonMain/kotlin/app/aaps/implementation/userEntry/UserEntryPresentationHelperImpl.kt @@ -162,6 +162,7 @@ class UserEntryPresentationHelperImpl( Sources.Omnipod -> IcPatchPump Sources.OmnipodDash -> IcPatchPump Sources.OmnipodEros -> IcPatchPump + Sources.Omnipod5 -> IcPatchPump Sources.Ottai -> IcPluginSyai Sources.Overview -> Icons.Default.Home Sources.PocTech -> IcPluginPocTec @@ -250,6 +251,7 @@ class UserEntryPresentationHelperImpl( Sources.Omnipod -> ElementType.PUMP.color() Sources.OmnipodDash -> ElementType.PUMP.color() Sources.OmnipodEros -> ElementType.PUMP.color() + Sources.Omnipod5 -> ElementType.PUMP.color() Sources.Ottai -> ElementType.CGM_DEX.color() Sources.Overview -> ElementType.AAPS.color() Sources.PocTech -> ElementType.CGM_DEX.color() diff --git a/pump/omnipod/common/build.gradle.kts b/pump/omnipod/common/build.gradle.kts index 1abdbea36d68..efa034f3a1c2 100644 --- a/pump/omnipod/common/build.gradle.kts +++ b/pump/omnipod/common/build.gradle.kts @@ -21,6 +21,7 @@ dependencies { implementation(libs.androidx.compose.ui.tooling.preview) debugImplementation(libs.androidx.compose.ui.tooling) + implementation(libs.kotlinx.coroutines.rx3) testImplementation(project(":shared:tests")) diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/Ids.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/Ids.kt index ca65d55a27d5..96087040aba2 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/Ids.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/Ids.kt @@ -3,12 +3,23 @@ package app.aaps.pump.omnipod.common.bledriver.comm import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.scan.PodScanner import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManager -class Ids(podState: OmnipodDashPodStateManager) { +/** + * The controller/pod identity pair used throughout pairing and session establishment. + * + * The primary constructor (from [OmnipodDashPodStateManager]) is unchanged from before - + * every existing Dash call site behaves identically. [forController] is an additive + * factory for pod types (e.g. Omnipod 5) that don't have a Dash-style pod state manager + * to derive their controller/pod ids from - O5 derives its controller id from + * [app.aaps.pump.omnipod.common.bledriver.comm.pair.O5CertificateStore.controllerId] + * instead. + */ +class Ids private constructor(val myId: Id, val podId: Id) { - val myId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) - private val uniqueId = podState.uniqueId - val podId = uniqueId?.let(Id::fromLong) - ?: myId.increment() // pod not activated + constructor(podState: OmnipodDashPodStateManager) : this( + myId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID), + podId = podState.uniqueId?.let(Id::fromLong) + ?: Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID).increment() + ) companion object { @@ -17,5 +28,8 @@ class Ids(podState: OmnipodDashPodStateManager) { PodScanner.POD_ID_NOT_ACTIVATED ) } + + /** For pod types without a Dash-style pod state manager to derive ids from. */ + fun forController(myId: Id, podId: Id): Ids = Ids(myId, podId) } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/SharedBleManager.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/SharedBleManager.kt index 6f70450f1ceb..71d508ecca34 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/SharedBleManager.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/SharedBleManager.kt @@ -52,7 +52,11 @@ abstract class SharedBleManager( * Exceptions are handled by the enclosing operation: the connection is disconnected and the * observable emits the error. */ - protected open fun onCommandWriteCompleted() = Unit + protected open fun onCommandWriteCompleted() { + onCommandSent() + } + + protected open fun onCommandSent() = Unit /** * Called on the subscription thread before [PodEvent.ResponseReceived] is emitted. @@ -109,6 +113,7 @@ abstract class SharedBleManager( } is CommandReceiveError -> { + readResult.result?.let(::onResponse) emitter.tryOnError(MessageIOException("Could not read response: $readResult")) return@create } @@ -155,6 +160,7 @@ abstract class SharedBleManager( emitter.onNext(PodEvent.Connected) complete(emitter::onComplete) { busyReleasedBeforeCompletion = true } } catch (ex: Exception) { + aapsLogger.error(LTag.PUMPBTCOMM, "$connectionName connection failed", ex) disconnect(false) emitter.tryOnError(ex) } finally { diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommand.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommand.kt index cd9c654a890e..9c1c162f033d 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommand.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommand.kt @@ -13,6 +13,8 @@ object BleCommandSuccess : BleCommand(BleCommandType.SUCCESS) object BleCommandFail : BleCommand(BleCommandType.FAIL) +object BleCommandPairStatus : BleCommand(BleCommandType.PAIR_STATUS) + data class BleCommandNack(val idx: Byte) : BleCommand(BleCommandType.NACK, byteArrayOf(idx)) { companion object { @@ -93,6 +95,9 @@ sealed class BleCommand(val data: ByteArray) { BleCommandType.FAIL -> BleCommandFail + BleCommandType.PAIR_STATUS -> + BleCommandPairStatus + BleCommandType.HELLO -> BleCommandIncorrect("Incorrect hello command received", payload) diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommandType.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommandType.kt index 76e137311b12..6a13d233589a 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommandType.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/command/BleCommandType.kt @@ -8,6 +8,12 @@ enum class BleCommandType(val value: Byte) { SUCCESS(0x04.toByte()), FAIL(0x05.toByte()), HELLO(0x06.toByte()), + + /** O5-only: an intermediate "still working" status the pod can send on the CMD + * characteristic while preparing a response, before the real expected command + * (e.g. SUCCESS). Matches OmnipodKit's PodCommand.PAIR_STATUS - see + * PeripheralManager.waitForCommand(), which loops past it instead of failing. */ + PAIR_STATUS(0x08.toByte()), INCORRECT(0x09.toByte()); companion object { diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/interfaces/io/CharacteristicType.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/interfaces/io/CharacteristicType.kt index bd7277c409f7..d4facc3720ba 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/interfaces/io/CharacteristicType.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/interfaces/io/CharacteristicType.kt @@ -4,7 +4,18 @@ import java.math.BigInteger import java.util.UUID enum class CharacteristicType(val value: String) { - CMD("1a7e2441-e3ed-4464-8b7e-751e03d0dc5f"), DATA("1a7e2442-e3ed-4464-8b7e-751e03d0dc5f"); + CMD("1a7e2441-e3ed-4464-8b7e-751e03d0dc5f"), + DATA("1a7e2442-e3ed-4464-8b7e-751e03d0dc5f"), + + /** + * Omnipod 5's data characteristic. O5 shares Dash's CMD characteristic (and GATT + * service) but uses a different DATA characteristic - see + * [app.aaps.pump.omnipod.common.bledriver.pod.util.BluetoothServiceUuids] for the + * canonical source of these UUIDs (this enum predates that file and is left as the + * existing GATT-wiring mechanism rather than migrated wholesale, to avoid touching + * more of the working Dash connection path than necessary). + */ + DATA_O5("1a7e2443-e3ed-4464-8b7e-751e03d0dc5f"); val uuid: UUID get() = UUID( diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/callbacks/BleCommCallbacks.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/callbacks/BleCommCallbacks.kt index f223b207cea2..6c4b2958a2ab 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/callbacks/BleCommCallbacks.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/callbacks/BleCommCallbacks.kt @@ -11,6 +11,7 @@ import app.aaps.core.utils.toHex import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.CharacteristicType.Companion.byValue import app.aaps.pump.omnipod.common.bledriver.comm.legacy.io.IncomingPackets import app.aaps.pump.omnipod.common.bledriver.comm.session.DisconnectHandler +import app.aaps.pump.omnipod.common.bledriver.pod.util.BluetoothServiceUuids import java.util.UUID import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch @@ -32,8 +33,16 @@ class BleCommCallbacks( private var connected: CountDownLatch = CountDownLatch(1) @Synchronized get @Synchronized set + private var mtuNegotiationComplete: CountDownLatch = CountDownLatch(1) + @Synchronized get + @Synchronized set private val writeQueue: BlockingQueue = LinkedBlockingQueue() + /** The ATT MTU last confirmed via [onMtuChanged]; the BLE-spec default until negotiated. */ + @Volatile + var negotiatedMtu: Int = DEFAULT_ATT_MTU + private set + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { aapsLogger.debug(LTag.PUMPBTCOMM, "OnConnectionStateChange with status/state: $status/$newState") super.onConnectionStateChange(gatt, status, newState) @@ -120,7 +129,14 @@ class BleCommCallbacks( super.onCharacteristicChanged(gatt, characteristic) val payload = characteristic.value - val characteristicType = byValue(characteristic.uuid.toString()) + val uuid = characteristic.uuid.toString() + + if (uuid.equals(BluetoothServiceUuids.O5_HEARTBEAT_CHARACTERISTIC_UUID, ignoreCase = true)) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Received O5 heartbeat: ${payload.toHex()}") + return + } + + val characteristicType = byValue(uuid) aapsLogger.debug( LTag.PUMPBTCOMM, @@ -153,6 +169,24 @@ class BleCommCallbacks( LTag.PUMPBTCOMM, "onMtuChanged with MTU/status: $mtu/$status " ) + if (status == BluetoothGatt.GATT_SUCCESS) { + negotiatedMtu = mtu + } + mtuNegotiationComplete.countDown() + } + + /** + * @return true once [onMtuChanged] has fired (successfully or not); false on timeout. + * Callers should check [negotiatedMtu] afterwards to see what was actually granted. + */ + fun waitForMtuChange(timeoutMs: Long): Boolean { + val latch = mtuNegotiationComplete + try { + latch.await(timeoutMs, TimeUnit.MILLISECONDS) + } catch (e: InterruptedException) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while waiting for MTU negotiation") + } + return latch.count == 0L } override fun onReadRemoteRssi(gatt: BluetoothGatt?, rssi: Int, status: Int) { @@ -210,13 +244,19 @@ class BleCommCallbacks( aapsLogger.debug(LTag.PUMPBTCOMM, "Reset connection") connected.countDown() serviceDiscoveryComplete.countDown() + mtuNegotiationComplete.countDown() connected = CountDownLatch(1) serviceDiscoveryComplete = CountDownLatch(1) + mtuNegotiationComplete = CountDownLatch(1) + negotiatedMtu = DEFAULT_ATT_MTU flushConfirmationQueue() } companion object { // the confirmation queue should be empty anyway private const val WRITE_CONFIRM_TIMEOUT_MS = 10 + + /** BLE-spec default ATT MTU (23 bytes total, 20 usable payload) before any negotiation. */ + const val DEFAULT_ATT_MTU = 23 } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIO.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIO.kt index b760d517503c..affccaf98225 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIO.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIO.kt @@ -110,13 +110,19 @@ open class BleIO( throw ConnectException("Expecting one descriptor, found: ${descriptors.size}") } val descriptor = descriptors[0] - descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE + val usesIndicate = usesIndicate(characteristic) + val enableValue = if (usesIndicate) BluetoothGattDescriptor.ENABLE_INDICATION_VALUE else BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + aapsLogger.debug( + LTag.PUMPBTCOMM, + "$type characteristic properties: ${characteristic.properties} (using ${if (usesIndicate) "INDICATE" else "NOTIFY"})" + ) + descriptor.value = enableValue gatt.writeDescriptor(descriptor) - .assertTrue("enable indications on descriptor") + .assertTrue("enable ${if (usesIndicate) "indications" else "notifications"} on descriptor") - aapsLogger.debug(LTag.PUMPBTCOMM, "Enabling indications for $type") + aapsLogger.debug(LTag.PUMPBTCOMM, "Enabling ${if (usesIndicate) "indications" else "notifications"} for $type") val confirmation = bleCommCallbacks.confirmWrite( - BluetoothGattDescriptor.ENABLE_INDICATION_VALUE, + enableValue, descriptor.uuid.toString(), DEFAULT_IO_TIMEOUT_MS ) @@ -131,6 +137,17 @@ open class BleIO( companion object { const val DEFAULT_IO_TIMEOUT_MS = BleCharacteristicIO.DEFAULT_IO_TIMEOUT_MS + + /** + * Isolated from [readyToRead]'s GATT calls so this decision is directly unit + * testable, without needing the full connect()/readyToRead() mock chain - and + * the real Android framework's null ENABLE_INDICATION_VALUE/ + * ENABLE_NOTIFICATION_VALUE static-field environment boundary that chain hits in + * pure-JVM tests (see O5ConnectionTest's documented stopping point) - just to + * verify which branch gets picked. + */ + internal fun usesIndicate(characteristic: BluetoothGattCharacteristic): Boolean = + characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0 } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/CmdBleIO.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/CmdBleIO.kt index e425669c3583..955427a58702 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/CmdBleIO.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/CmdBleIO.kt @@ -2,10 +2,13 @@ package app.aaps.pump.omnipod.common.bledriver.comm.legacy.io import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic +import android.os.SystemClock import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag import app.aaps.pump.omnipod.common.bledriver.comm.OmnipodDashBleManagerImpl import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommand import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommandHello +import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommandType import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleConfirmError import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleConfirmIncorrectData import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleConfirmResult @@ -16,13 +19,13 @@ import java.util.concurrent.BlockingQueue import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.CmdBleIO as CmdBleIOInterface class CmdBleIO( - logger: AAPSLogger, + private val aapsLogger: AAPSLogger, characteristic: BluetoothGattCharacteristic, private val incomingPackets: BlockingQueue, gatt: BluetoothGatt, bleCommCallbacks: BleCommCallbacks ) : BleIO( - logger, + aapsLogger, characteristic, incomingPackets, gatt, @@ -34,15 +37,41 @@ class CmdBleIO( return incomingPackets.peek() } - override fun hello() = sendAndConfirmPacket(BleCommandHello(OmnipodDashBleManagerImpl.CONTROLLER_ID).data) + override fun hello() = hello(OmnipodDashBleManagerImpl.CONTROLLER_ID) + + /** + * O5 sends its own certificate-derived controller id here (not the Dash + * [OmnipodDashBleManagerImpl.CONTROLLER_ID]). The id announced in this handshake must + * match the source id used later in the pairing messages (SP1/SP2), or the pod aborts + * the pairing. + */ + fun hello(controllerId: Int) = sendAndConfirmPacket(BleCommandHello(controllerId).data) override fun expectCommandType(expected: BleCommand, timeoutMs: Long): BleConfirmResult { - return receivePacket(timeoutMs)?.let { - if (it.isNotEmpty() && it[0] == expected.data[0]) - BleConfirmSuccess - else - BleConfirmIncorrectData(it) + val deadlineMs = SystemClock.elapsedRealtime() + timeoutMs + while (true) { + val remainingMs = deadlineMs - SystemClock.elapsedRealtime() + if (remainingMs <= 0) { + return BleConfirmError("Error reading packet") + } + val received = receivePacket(remainingMs) ?: return BleConfirmError("Error reading packet") + when { + received.isEmpty() -> + return BleConfirmIncorrectData(received) + + received[0] == expected.data[0] -> + return BleConfirmSuccess + + received[0] == BleCommandType.PAIR_STATUS.value -> { + aapsLogger.debug( + LTag.PUMPBTCOMM, + "expectCommandType: skipping intermediate PAIR_STATUS while waiting for $expected" + ) + } + + else -> + return BleConfirmIncorrectData(received) + } } - ?: BleConfirmError("Error reading packet") } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/DataBleIO.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/DataBleIO.kt index 1fdb0ff71abe..48603c83ac76 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/DataBleIO.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/DataBleIO.kt @@ -13,12 +13,13 @@ class DataBleIO( characteristic: BluetoothGattCharacteristic, incomingPackets: BlockingQueue, gatt: BluetoothGatt, - bleCommCallbacks: BleCommCallbacks + bleCommCallbacks: BleCommCallbacks, + type: CharacteristicType = CharacteristicType.DATA ) : BleIO( logger, characteristic, incomingPackets, gatt, bleCommCallbacks, - CharacteristicType.DATA + type ), DataBleIOInterface diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/IncomingPackets.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/IncomingPackets.kt index 674242f51a95..15fab709054d 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/IncomingPackets.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/IncomingPackets.kt @@ -11,8 +11,9 @@ class IncomingPackets { fun byCharacteristicType(char: CharacteristicType): BlockingQueue { return when (char) { - CharacteristicType.DATA -> dataQueue - CharacteristicType.CMD -> cmdQueue + CharacteristicType.DATA -> dataQueue + CharacteristicType.DATA_O5 -> dataQueue + CharacteristicType.CMD -> cmdQueue } } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/Connection.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/Connection.kt index 02fcc6709c49..6c5fa3290802 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/Connection.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/Connection.kt @@ -12,6 +12,7 @@ import app.aaps.pump.omnipod.common.bledriver.comm.legacy.io.CmdBleIO import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO import app.aaps.pump.omnipod.common.bledriver.comm.session.Session import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionKeys +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManager class Connection( @@ -22,7 +23,7 @@ class Connection( private val podState: OmnipodDashPodStateManager ) : SharedBleConnection(podDevice, aapsLogger, config, context) { - override val connectionName = "Dash" + override val podType = PodType.DASH override fun recordConnectionAttempt() { podState.connectionAttempts++ diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/ServiceDiscoverer.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/ServiceDiscoverer.kt index 5fd83be32e7b..d2c56187a54f 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/ServiceDiscoverer.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/ServiceDiscoverer.kt @@ -11,6 +11,7 @@ import app.aaps.pump.omnipod.common.bledriver.comm.legacy.callbacks.BleCommCallb import app.aaps.pump.omnipod.common.bledriver.comm.session.Connected import app.aaps.pump.omnipod.common.bledriver.comm.session.ConnectionWaitCondition import app.aaps.pump.omnipod.common.bledriver.comm.session.STOP_CONNECTING_CHECK_INTERVAL_MS +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType import java.math.BigInteger import java.util.UUID @@ -22,9 +23,17 @@ class ServiceDiscoverer( ) { /** - * This is first step after connection establishment + * This is first step after connection establishment. + * + * [podType] defaults to [PodType.DASH], preserving existing behavior for every call + * site that doesn't pass it explicitly. Dash and Omnipod 5 share the same GATT + * service and CMD characteristic; only the DATA characteristic differs (see + * [app.aaps.pump.omnipod.common.bledriver.pod.util.BluetoothServiceUuids]). */ - fun discoverServices(connectionWaitCond: ConnectionWaitCondition): Map { + fun discoverServices( + connectionWaitCond: ConnectionWaitCondition, + podType: PodType = PodType.DASH + ): Map { logger.debug(LTag.PUMPBTCOMM, "Discovering services") bleCallbacks.startServiceDiscovery() try { @@ -55,8 +64,9 @@ class ServiceDiscoverer( } val cmdChar = service.getCharacteristic(CharacteristicType.CMD.uuid) ?: throw ConnectException("Characteristic not found: ${CharacteristicType.CMD.value}") - val dataChar = service.getCharacteristic(CharacteristicType.DATA.uuid) - ?: throw ConnectException("Characteristic not found: ${CharacteristicType.DATA.value}") + val dataCharacteristicType = if (podType == PodType.OMNIPOD_5) CharacteristicType.DATA_O5 else CharacteristicType.DATA + val dataChar = service.getCharacteristic(dataCharacteristicType.uuid) + ?: throw ConnectException("Characteristic not found: ${dataCharacteristicType.value}") return mapOf( CharacteristicType.CMD to cmdChar, CharacteristicType.DATA to dataChar diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/SharedBleConnection.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/SharedBleConnection.kt index 8e1e7aea0470..c650b6b2ef6c 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/SharedBleConnection.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/session/SharedBleConnection.kt @@ -34,6 +34,7 @@ import app.aaps.pump.omnipod.common.bledriver.comm.session.Session import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionEstablisher import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionKeys import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionNegotiationResynchronization +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType abstract class SharedBleConnection( protected val podDevice: BluetoothDevice, @@ -42,7 +43,7 @@ abstract class SharedBleConnection( protected val context: Context ) : BleConnection, DisconnectHandler { - protected abstract val connectionName: String + protected abstract val podType: PodType protected val incomingPackets = IncomingPackets() protected val bleCommCallbacks by lazy { BleCommCallbacks(aapsLogger, incomingPackets, this) } protected var gattConnection: BluetoothGatt? = null @@ -61,11 +62,12 @@ abstract class SharedBleConnection( protected open fun prepareGatt(gatt: BluetoothGatt) = Unit protected abstract fun hello(cmdBleIO: CmdBleIO) protected abstract fun createSession(messageIO: MessageIO, ids: Ids, keys: SessionKeys, enDecrypt: EnDecrypt): Session + protected open fun discoverServices( gatt: BluetoothGatt, connectionWaitCond: ConnectionWaitCondition ): Map = - ServiceDiscoverer(aapsLogger, gatt, bleCommCallbacks, this).discoverServices(connectionWaitCond) + ServiceDiscoverer(aapsLogger, gatt, bleCommCallbacks, this).discoverServices(connectionWaitCond, podType) protected open fun createMessageIO( gatt: BluetoothGatt, @@ -78,19 +80,21 @@ abstract class SharedBleConnection( gatt, bleCommCallbacks ) + val dataType = if (podType == PodType.OMNIPOD_5) CharacteristicType.DATA_O5 else CharacteristicType.DATA val dataBleIO = DataBleIO( aapsLogger, discovered.getValue(CharacteristicType.DATA), incomingPackets.dataQueue, gatt, - bleCommCallbacks + bleCommCallbacks, + dataType ) return cmdBleIO to dataBleIO } @Synchronized final override fun connect(connectionWaitCond: ConnectionWaitCondition) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting $connectionName connectionWaitCond=$connectionWaitCond") + aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting $podType connectionWaitCond=$connectionWaitCond") connectionWaitCondition = connectionWaitCond recordConnectionAttempt() updateConnectionState(LifecycleState.CONNECTING) @@ -121,7 +125,7 @@ abstract class SharedBleConnection( val discovered = discoverServices(gatt, connectionWaitCond) prepareGatt(gatt) val (cmdBleIO, dataBleIO) = createMessageIO(gatt, discovered) - msgIO = MessageIO(aapsLogger, cmdBleIO, dataBleIO) + msgIO = MessageIO(aapsLogger, cmdBleIO, dataBleIO, podType) hello(cmdBleIO) cmdBleIO.readyToRead() dataBleIO.readyToRead() @@ -130,7 +134,7 @@ abstract class SharedBleConnection( @Synchronized final override fun disconnect(closeGatt: Boolean) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Disconnecting $connectionName closeGatt=$closeGatt") + aapsLogger.debug(LTag.PUMPBTCOMM, "Disconnecting $podType closeGatt=$closeGatt") if (!closeGatt && gattConnection != null) { gattConnection?.disconnect() updateConnectionState(LifecycleState.DISCONNECTED) @@ -158,7 +162,7 @@ abstract class SharedBleConnection( } } } catch (_: InterruptedException) { - aapsLogger.info(LTag.PUMPBTCOMM, "Interrupted while waiting for $connectionName connection") + aapsLogger.info(LTag.PUMPBTCOMM, "Interrupted while waiting for $podType connection") } return connectionState() } @@ -195,7 +199,7 @@ abstract class SharedBleConnection( } final override fun onConnectionLost(status: Int) { - aapsLogger.info(LTag.PUMPBTCOMM, "Lost $connectionName connection with status: $status") + aapsLogger.info(LTag.PUMPBTCOMM, "Lost $podType connection with status: $status") connectionWaitCondition?.stopConnection?.let { if (it.count > 0) it.countDown() } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageIO.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageIO.kt index a5331e807906..dd5970aade1b 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageIO.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageIO.kt @@ -10,6 +10,7 @@ import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommandFail import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommandNack import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommandRTS import app.aaps.pump.omnipod.common.bledriver.comm.command.BleCommandSuccess +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleCharacteristicIO import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleConfirmError import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleConfirmIncorrectData import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleConfirmSuccess @@ -20,8 +21,11 @@ import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.BleSendSuccess import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.CmdBleIO import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.DataBleIO import app.aaps.pump.omnipod.common.bledriver.comm.packet.BlePacket +import app.aaps.pump.omnipod.common.bledriver.comm.packet.BlePacketLayout import app.aaps.pump.omnipod.common.bledriver.comm.packet.PayloadJoiner import app.aaps.pump.omnipod.common.bledriver.comm.packet.PayloadSplitter +import app.aaps.pump.omnipod.common.bledriver.comm.packet.blePacketLayout +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType sealed class MessageSendResult object MessageSendSuccess : MessageSendResult() @@ -41,12 +45,18 @@ class MessageIO( private val aapsLogger: AAPSLogger, private val cmdBleIO: CmdBleIO, private val dataBleIO: DataBleIO, + private val podType: PodType = PodType.DASH, ) { private val receivedOutOfOrder = LinkedHashMap() var maxMessageReadTries = 3 var messageReadTries = 0 + private val packetLayout: BlePacketLayout = podType.blePacketLayout + + private val readTimeoutMs: Long = + if (podType.isO5) MESSAGE_READ_TIMEOUT_MS else BleCharacteristicIO.DEFAULT_IO_TIMEOUT_MS + @Suppress("ReturnCount") fun sendMessage(msg: MessagePacket): MessageSendResult { val foundRTS = cmdBleIO.flushIncomingQueue() @@ -57,23 +67,25 @@ class MessageIO( } dataBleIO.flushIncomingQueue() - val rtsSendResult = cmdBleIO.sendAndConfirmPacket(BleCommandRTS.data) - if (rtsSendResult is BleSendErrorSending) { - return MessageSendErrorSending(rtsSendResult) - } - val expectCTS = cmdBleIO.expectCommandType(BleCommandCTS) - if (expectCTS !is BleConfirmSuccess) { - return MessageSendErrorSending(expectCTS.toString()) + if (podType.isDash) { + val rtsSendResult = cmdBleIO.sendAndConfirmPacket(BleCommandRTS.data) + if (rtsSendResult is BleSendErrorSending) { + return MessageSendErrorSending(rtsSendResult) + } + val expectCTS = cmdBleIO.expectCommandType(BleCommandCTS) + if (expectCTS !is BleConfirmSuccess) { + return MessageSendErrorSending(expectCTS.toString()) + } } val payload = msg.asByteArray() aapsLogger.debug(LTag.PUMPBTCOMM, "Sending message: ${payload.toHex()}") - val splitter = PayloadSplitter(payload) + val splitter = PayloadSplitter(payload, packetLayout) val packets = splitter.splitInPackets() for ((index, packet) in packets.withIndex()) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Sending DATA: ${packet.toByteArray().toHex()}") - val sendResult = dataBleIO.sendAndConfirmPacket(packet.toByteArray()) + aapsLogger.debug(LTag.PUMPBTCOMM, "Sending DATA: ${packet.toByteArray(packetLayout).toHex()}") + val sendResult = dataBleIO.sendAndConfirmPacket(packet.toByteArray(packetLayout)) val ret = handleSendResult(sendResult, index, packets) if (ret !is MessageSendSuccess) { return ret @@ -87,7 +99,7 @@ class MessageIO( } } - return when (val expectSuccess = cmdBleIO.expectCommandType(BleCommandSuccess)) { + return when (val expectSuccess = cmdBleIO.expectCommandType(BleCommandSuccess, readTimeoutMs)) { is BleConfirmSuccess -> MessageSendSuccess @@ -108,18 +120,20 @@ class MessageIO( @Suppress("ReturnCount") fun receiveMessage(readRTS: Boolean = true): MessagePacket? { - if (readRTS) { - val expectRTS = cmdBleIO.expectCommandType(BleCommandRTS, MESSAGE_READ_TIMEOUT_MS) - if (expectRTS !is BleConfirmSuccess) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading RTS: $expectRTS") - return null + if (podType.isDash) { + if (readRTS) { + val expectRTS = cmdBleIO.expectCommandType(BleCommandRTS, MESSAGE_READ_TIMEOUT_MS) + if (expectRTS !is BleConfirmSuccess) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading RTS: $expectRTS") + return null + } } - } - val sendResult = cmdBleIO.sendAndConfirmPacket(BleCommandCTS.data) - if (sendResult !is BleSendSuccess) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Error sending CTS: $sendResult") - return null + val sendResult = cmdBleIO.sendAndConfirmPacket(BleCommandCTS.data) + if (sendResult !is BleSendSuccess) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Error sending CTS: $sendResult") + return null + } } readReset() var expected: Byte = 0 @@ -129,7 +143,7 @@ class MessageIO( aapsLogger.warn(LTag.PUMPBTCOMM, "Error reading first packet:$firstPacket") return null } - val joiner = PayloadJoiner(firstPacket.payload) + val joiner = PayloadJoiner(firstPacket.payload, packetLayout) maxMessageReadTries = joiner.fullFragments * 2 + 2 for (i in 1 until joiner.fullFragments + 1) { expected++ @@ -190,7 +204,7 @@ class MessageIO( if (received == null) { MessageSendErrorSending(received.toString()) } else { - val sendResult = dataBleIO.sendAndConfirmPacket(packets[receivedCmd.idx.toInt()].toByteArray()) + val sendResult = dataBleIO.sendAndConfirmPacket(packets[receivedCmd.idx.toInt()].toByteArray(packetLayout)) handleSendResult(sendResult, index, packets) } } @@ -216,7 +230,7 @@ class MessageIO( while (messageReadTries < maxMessageReadTries && packetTries < MAX_PACKET_READ_TRIES) { messageReadTries++ packetTries++ - val received = dataBleIO.receivePacket() + val received = dataBleIO.receivePacket(readTimeoutMs) if (received == null || received.isEmpty()) { if (nackOnTimeout) cmdBleIO.sendAndConfirmPacket(BleCommandNack(index).data) diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacket.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacket.kt index 4540e3370edc..d4ba0fe08561 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacket.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacket.kt @@ -22,11 +22,18 @@ data class MessagePacket( val gateway: Boolean = false, val sas: Boolean = true, // TODO: understand, seems to always be true val tfs: Boolean = false, // TODO: understand, seems to be false - val version: Short = 0.toShort() + val version: Short = 0.toShort(), + /** O5-only: raw (r||s, 64-byte) P-256 ECDSA signature for [MessageType.ENCRYPTED_SIGNED] + * messages - set only after [payload] has already been AES-CCM encrypted (see + * [app.aaps.pump.omnipod.common.bledriver.comm.session.Session]'s signing step). + * Appended to the wire bytes after [payload] but - matching OmnipodKit's + * MessagePacket.swift exactly - deliberately excluded from the size field computed + * in [asByteArray], since the pod doesn't count it as part of the message body. */ + val signatureData: ByteArray? = null ) { fun asByteArray(forEncryption: Boolean = false): ByteArray { - val bb = ByteBuffer.allocate(16 + payload.size) + val bb = ByteBuffer.allocate(16 + payload.size + (signatureData?.size ?: 0)) bb.put(MAGIC_PATTERN.toByteArray()) val f1 = Flag() @@ -53,8 +60,9 @@ data class MessagePacket( bb.put(f2.value.toByte()) bb.put(this.sequenceNumber) bb.put(this.ackNumber) + val hasTag = type == MessageType.ENCRYPTED || type == MessageType.ENCRYPTED_SIGNED val size = payload.size - - if (type == MessageType.ENCRYPTED && !forEncryption) 8 else 0 + if (hasTag && !forEncryption) 8 else 0 bb.put((size ushr 3).toByte()) bb.put((size shl 5).toByte()) @@ -62,6 +70,7 @@ data class MessagePacket( bb.put(this.destination.address) bb.put(this.payload) + signatureData?.let { bb.put(it) } val ret = ByteArray(bb.position()) bb.flip() @@ -93,7 +102,7 @@ data class MessagePacket( val lastMessage = f2.get(2) != 0 val gateway = f2.get(3) != 0 val type = - MessageType.byValue((f1.get(7) or (f1.get(6) shl 1) or (f1.get(5) shl 2) or (f1.get(4) shl 3)).toByte()) + MessageType.byValue((f2.get(7) or (f2.get(6) shl 1) or (f2.get(5) shl 2) or (f2.get(4) shl 3)).toByte()) if (version.toInt() != 0) { throw CouldNotParseMessageException(payload) } @@ -102,8 +111,9 @@ data class MessagePacket( val size = (payload[6].toInt() shl 3) or (payload[7].toUnsignedInt() ushr 5) payload.assertSizeAtLeast(size + HEADER_SIZE) + val hasTag = type == MessageType.ENCRYPTED || type == MessageType.ENCRYPTED_SIGNED val payloadEnd = 16 + size + - if (type == MessageType.ENCRYPTED) 8 // TAG + if (hasTag) 8 // TAG else 0 return MessagePacket( diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageType.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageType.kt index 1674f9682eb7..d82dc2b367f7 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageType.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessageType.kt @@ -4,7 +4,16 @@ enum class MessageType(val value: Byte) { CLEAR(0), ENCRYPTED(1), SESSION_ESTABLISHMENT(2), - PAIRING(3); + PAIRING(3), + + /** + * Signed + encrypted messages (post-pairing signed pod commands). Not yet used by any + * caller in this codebase - there's no signed-command layer built yet (Swift's + * O5AidCommands.swift equivalent) - but MessagePacket's tag-size handling below already + * accounts for it, matching Swift's MessagePacket.swift exactly, so the wire format is + * correct from the moment this type does get a caller. + */ + ENCRYPTED_SIGNED(4); companion object { diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/StringLengthPrefixEncoding.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/StringLengthPrefixEncoding.kt index 3e74287a2a53..2638d9afb131 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/StringLengthPrefixEncoding.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/StringLengthPrefixEncoding.kt @@ -28,7 +28,7 @@ class StringLengthPrefixEncoding private constructor() { remaining.assertSizeAtLeast(key.length + LENGTH_BYTES) remaining = remaining.copyOfRange(key.length, remaining.size) - val length = (remaining[0].toUnsignedInt() shl 1) or remaining[1].toUnsignedInt() + val length = (remaining[0].toUnsignedInt() shl 8) or remaining[1].toUnsignedInt() remaining.assertSizeAtLeast(length) ret[index] = remaining.copyOfRange(LENGTH_BYTES, LENGTH_BYTES + length) remaining = remaining.copyOfRange(LENGTH_BYTES + length, remaining.size) diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacket.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacket.kt index 8c26214d4b80..d74277e6bdda 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacket.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacket.kt @@ -6,12 +6,7 @@ import java.nio.ByteBuffer sealed class BlePacket { abstract val payload: ByteArray - abstract fun toByteArray(): ByteArray - - companion object { - - const val MAX_SIZE = 20 - } + abstract fun toByteArray(layout: BlePacketLayout): ByteArray } data class FirstBlePacket( @@ -22,9 +17,9 @@ data class FirstBlePacket( val oneExtraPacket: Boolean = false ) : BlePacket() { - override fun toByteArray(): ByteArray { + override fun toByteArray(layout: BlePacketLayout): ByteArray { val bb = ByteBuffer - .allocate(MAX_SIZE) + .allocate(layout.maxPayloadSize) .put(0) // index .put(fullFragments.toByte()) // # of fragments except FirstBlePacket and LastOptionalPlusOneBlePacket crc32?.let { @@ -36,7 +31,7 @@ data class FirstBlePacket( bb.put(payload) val pos = bb.position() - val ret = ByteArray(MAX_SIZE) + val ret = ByteArray(if (layout.padToMaxPayloadSize) layout.maxPayloadSize else pos) bb.flip() bb.get(ret, 0, pos) @@ -45,15 +40,15 @@ data class FirstBlePacket( companion object { - fun parse(payload: ByteArray): FirstBlePacket { + fun parse(payload: ByteArray, layout: BlePacketLayout): FirstBlePacket { payload.assertSizeAtLeast(HEADER_SIZE_WITH_MIDDLE_PACKETS, 0) if (payload[0].toInt() != 0) { // most likely we lost the first packet. throw IncorrectPacketException(payload, 0) } - val fullFragments = payload[1].toInt() - require(fullFragments < MAX_FRAGMENTS) { "Received more than $MAX_FRAGMENTS fragments" } + val fullFragments = payload[1].toUnsignedInt() + require(fullFragments < layout.maxFragments) { "Received more than ${layout.maxFragments} fragments" } payload.assertSizeAtLeast(HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, 0) @@ -61,25 +56,26 @@ data class FirstBlePacket( fullFragments == 0 -> { val rest = payload[6] - val end = Integer.min(rest + HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, payload.size) + val restUnsigned = rest.toUnsignedInt() + val end = Integer.min(restUnsigned + HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, payload.size) payload.assertSizeAtLeast(end, 0) FirstBlePacket( fullFragments = fullFragments, payload = payload.copyOfRange(HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, end), crc32 = ByteBuffer.wrap(payload.copyOfRange(2, 6)).int.toUnsignedLong(), size = rest, - oneExtraPacket = rest + HEADER_SIZE_WITHOUT_MIDDLE_PACKETS > end + oneExtraPacket = restUnsigned + HEADER_SIZE_WITHOUT_MIDDLE_PACKETS > end ) } // With middle packets - payload.size < MAX_SIZE -> + payload.size < layout.maxPayloadSize -> throw IncorrectPacketException(payload, 0) else -> { FirstBlePacket( fullFragments = fullFragments, - payload = payload.copyOfRange(HEADER_SIZE_WITH_MIDDLE_PACKETS, MAX_SIZE) + payload = payload.copyOfRange(HEADER_SIZE_WITH_MIDDLE_PACKETS, layout.maxPayloadSize) ) } } @@ -87,34 +83,24 @@ data class FirstBlePacket( private const val HEADER_SIZE_WITHOUT_MIDDLE_PACKETS = 7 // we are using all fields private const val HEADER_SIZE_WITH_MIDDLE_PACKETS = 2 - - internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = - MAX_SIZE - HEADER_SIZE_WITHOUT_MIDDLE_PACKETS // we are using all fields - internal const val CAPACITY_WITH_MIDDLE_PACKETS = - MAX_SIZE - HEADER_SIZE_WITH_MIDDLE_PACKETS // we are not using crc32 or size - internal const val CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET = 18 - - private const val MAX_FRAGMENTS = 15 // 15*20=300 bytes } } data class MiddleBlePacket(val index: Byte, override val payload: ByteArray) : BlePacket() { - override fun toByteArray(): ByteArray { + override fun toByteArray(layout: BlePacketLayout): ByteArray { return byteArrayOf(index) + payload } companion object { - fun parse(payload: ByteArray): MiddleBlePacket { - payload.assertSizeAtLeast(MAX_SIZE) + fun parse(payload: ByteArray, layout: BlePacketLayout): MiddleBlePacket { + payload.assertSizeAtLeast(layout.maxPayloadSize) return MiddleBlePacket( index = payload[0], - payload.copyOfRange(1, MAX_SIZE) + payload.copyOfRange(1, layout.maxPayloadSize) ) } - - internal const val CAPACITY = 19 } } @@ -126,15 +112,15 @@ data class LastBlePacket( val oneExtraPacket: Boolean = false ) : BlePacket() { - override fun toByteArray(): ByteArray { + override fun toByteArray(layout: BlePacketLayout): ByteArray { val bb = ByteBuffer - .allocate(MAX_SIZE) + .allocate(layout.maxPayloadSize) .put(index) .put(size) .putInt(crc32.toInt()) .put(payload) val pos = bb.position() - val ret = ByteArray(MAX_SIZE) + val ret = ByteArray(if (layout.padToMaxPayloadSize) layout.maxPayloadSize else pos) bb.flip() bb.get(ret, 0, pos) return ret @@ -142,25 +128,25 @@ data class LastBlePacket( companion object { - fun parse(payload: ByteArray): LastBlePacket { + fun parse(payload: ByteArray, layout: BlePacketLayout): LastBlePacket { payload.assertSizeAtLeast(HEADER_SIZE) val rest = payload[1] - val end = Integer.min(rest + HEADER_SIZE, payload.size) + val restUnsigned = rest.toUnsignedInt() + val end = Integer.min(restUnsigned + HEADER_SIZE, payload.size) payload.assertSizeAtLeast(end) return LastBlePacket( index = payload[0], crc32 = ByteBuffer.wrap(payload.copyOfRange(2, 6)).int.toUnsignedLong(), - oneExtraPacket = rest + HEADER_SIZE > end, + oneExtraPacket = restUnsigned + HEADER_SIZE > end, size = rest, payload = payload.copyOfRange(HEADER_SIZE, end) ) } private const val HEADER_SIZE = 6 - internal const val CAPACITY = MAX_SIZE - HEADER_SIZE } } @@ -170,15 +156,16 @@ data class LastOptionalPlusOneBlePacket( val size: Byte ) : BlePacket() { - override fun toByteArray(): ByteArray { - return byteArrayOf(index, size) + payload + ByteArray(MAX_SIZE - payload.size - 2) + override fun toByteArray(layout: BlePacketLayout): ByteArray { + val exact = byteArrayOf(index, size) + payload + return if (layout.padToMaxPayloadSize) exact + ByteArray(layout.maxPayloadSize - exact.size) else exact } companion object { - fun parse(payload: ByteArray): LastOptionalPlusOneBlePacket { + fun parse(payload: ByteArray, layout: BlePacketLayout): LastOptionalPlusOneBlePacket { payload.assertSizeAtLeast(2) - val size = payload[1].toInt() + val size = payload[1].toUnsignedInt() payload.assertSizeAtLeast(HEADER_SIZE + size) return LastOptionalPlusOneBlePacket( @@ -200,3 +187,11 @@ private fun ByteArray.assertSizeAtLeast(size: Int, index: Byte? = null) { throw IncorrectPacketException(this, index) } } + +/** + * Reinterprets this Byte's bit pattern as an unsigned value (0..255), matching the on-wire + * meaning of every size/count/index byte in this protocol. Kotlin's Byte is signed, so plain + * arithmetic/comparison on it silently sign-extends (e.g. wire value 200 reads back as -56) - + * this is needed anywhere such a byte feeds into arithmetic or a comparison, not just storage. + */ +internal fun Byte.toUnsignedInt(): Int = this.toInt() and 0xFF diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacketLayout.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacketLayout.kt new file mode 100644 index 000000000000..25887bba402a --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacketLayout.kt @@ -0,0 +1,77 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.packet + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType + +/** + * BLE packet framing parameters. Dash and Omnipod 5 share the same header byte layout but + * use different maximum payload sizes per packet (Dash: 20 bytes, O5: 244 bytes), which in + * turn changes every derived fragment capacity used when splitting/joining message payloads. + * + * Ported from OmnipodKit's BlePodProfile.swift (loopandlearn/OmnipodKit) `BlePacketLayout` + * struct and its `omnipodDash`/`omnipod5` presets. + */ +data class BlePacketLayout( + val maxPayloadSize: Int, + val maxFragments: Int, + val firstPacketHeaderSizeWithoutMiddlePackets: Int, + val firstPacketHeaderSizeWithMiddlePackets: Int, + val lastPacketHeaderSize: Int, + /** + * Whether [BlePacket.toByteArray] zero-pads every packet out to [maxPayloadSize]. + * + * OmnipodKit's BLEPacket.swift never pads - it writes exactly the bytes it built (its + * `Data(capacity:)` is only an allocation hint, not a length). This codebase's Dash + * path has always padded, and since Dash's [maxPayloadSize] is 20 that only ever added + * a few trailing zero bytes to the final packet of a message; it's proven correct + * against real Dash hardware over years of use, so it stays enabled there rather than + * being "fixed" to match Swift. + * + * For O5 the same behavior is materially different: [maxPayloadSize] is 244, so a + * 44-byte pairing message went out as a 244-byte BLE write with 193 bytes of zero + * padding, where a real PDM sends 51. Real-hardware logs show a pod does still ACK + * those (it reads the packet's own length field and ignores the tail), so this was not + * what broke pairing - but it is a genuine divergence from the reference on every + * single write, and the multi-packet path it also affects (SPS2.1, ~642 bytes) has + * never yet run against a real pod. Disabled for O5 to match Swift byte-for-byte. + */ + val padToMaxPayloadSize: Boolean +) { + val firstPacketCapacityWithoutMiddlePackets: Int + get() = maxPayloadSize - firstPacketHeaderSizeWithoutMiddlePackets + + val firstPacketCapacityWithMiddlePackets: Int + get() = maxPayloadSize - firstPacketHeaderSizeWithMiddlePackets + + val firstPacketCapacityWithOptionalPlusOnePacket: Int + get() = firstPacketCapacityWithMiddlePackets + + val middlePacketCapacity: Int + get() = maxPayloadSize - 1 + + val lastPacketCapacity: Int + get() = maxPayloadSize - lastPacketHeaderSize + + companion object { + + val DASH = BlePacketLayout( + maxPayloadSize = 20, + maxFragments = 15, + firstPacketHeaderSizeWithoutMiddlePackets = 7, + firstPacketHeaderSizeWithMiddlePackets = 2, + lastPacketHeaderSize = 6, + padToMaxPayloadSize = true + ) + + val OMNIPOD_5 = BlePacketLayout( + maxPayloadSize = 244, + maxFragments = 15, + firstPacketHeaderSizeWithoutMiddlePackets = 7, + firstPacketHeaderSizeWithMiddlePackets = 2, + lastPacketHeaderSize = 6, + padToMaxPayloadSize = false + ) + } +} + +val PodType.blePacketLayout: BlePacketLayout + get() = if (isO5) BlePacketLayout.OMNIPOD_5 else BlePacketLayout.DASH diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadJoiner.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadJoiner.kt index d0d72466ff48..faf6bb400dc9 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadJoiner.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadJoiner.kt @@ -5,7 +5,7 @@ import app.aaps.pump.omnipod.common.bledriver.comm.message.IncorrectPacketExcept import java.nio.ByteBuffer import java.util.LinkedList -class PayloadJoiner(firstPacket: ByteArray) { +class PayloadJoiner(firstPacket: ByteArray, private val layout: BlePacketLayout = BlePacketLayout.DASH) { var oneExtraPacket: Boolean val fullFragments: Int @@ -14,7 +14,7 @@ class PayloadJoiner(firstPacket: ByteArray) { private val fragments: MutableList = LinkedList() init { - val firstPacket = FirstBlePacket.parse(firstPacket) + val firstPacket = FirstBlePacket.parse(firstPacket, layout) fragments.add(firstPacket) fullFragments = firstPacket.fullFragments crc = firstPacket.crc32 ?: 0 @@ -25,25 +25,25 @@ class PayloadJoiner(firstPacket: ByteArray) { if (packet.size < 3) { // idx, size, at least 1 byte of payload throw IncorrectPacketException(packet, (expectedIndex + 1).toByte()) } - val idx = packet[0].toInt() + val idx = packet[0].toUnsignedInt() if (idx != expectedIndex + 1) { throw IncorrectPacketException(packet, (expectedIndex + 1).toByte()) } expectedIndex++ when { idx < fullFragments -> { - fragments.add(MiddleBlePacket.parse(packet)) + fragments.add(MiddleBlePacket.parse(packet, layout)) } idx == fullFragments -> { - val lastPacket = LastBlePacket.parse(packet) + val lastPacket = LastBlePacket.parse(packet, layout) fragments.add(lastPacket) crc = lastPacket.crc32 oneExtraPacket = lastPacket.oneExtraPacket } idx == fullFragments + 1 && oneExtraPacket -> { - fragments.add(LastOptionalPlusOneBlePacket.parse(packet)) + fragments.add(LastOptionalPlusOneBlePacket.parse(packet, layout)) } idx > fullFragments -> { diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitter.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitter.kt index 01f5382fad6a..376166cdae4f 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitter.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitter.kt @@ -3,30 +3,28 @@ package app.aaps.pump.omnipod.common.bledriver.comm.packet import java.lang.Integer.min import java.util.zip.CRC32 -class PayloadSplitter(private val payload: ByteArray) { +class PayloadSplitter(private val payload: ByteArray, private val layout: BlePacketLayout = BlePacketLayout.DASH) { fun splitInPackets(): List { - if (payload.size <= FirstBlePacket.CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET) { + if (payload.size <= layout.firstPacketCapacityWithOptionalPlusOnePacket) { return splitInOnePacket() } val ret = ArrayList() val crc32 = payload.crc32() - val middleFragments = (payload.size - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS) / MiddleBlePacket.CAPACITY + val middleFragments = (payload.size - layout.firstPacketCapacityWithMiddlePackets) / layout.middlePacketCapacity val rest = - ( - (payload.size - middleFragments * MiddleBlePacket.CAPACITY) - - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS - ).toByte() + (payload.size - middleFragments * layout.middlePacketCapacity) - + layout.firstPacketCapacityWithMiddlePackets ret.add( FirstBlePacket( fullFragments = middleFragments + 1, - payload = payload.copyOfRange(0, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS) + payload = payload.copyOfRange(0, layout.firstPacketCapacityWithMiddlePackets) ) ) for (i in 1..middleFragments) { val p = payload.copyOfRange( - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + (i - 1) * MiddleBlePacket.CAPACITY, - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + i * MiddleBlePacket.CAPACITY + layout.firstPacketCapacityWithMiddlePackets + (i - 1) * layout.middlePacketCapacity, + layout.firstPacketCapacityWithMiddlePackets + i * layout.middlePacketCapacity ) ret.add( MiddleBlePacket( @@ -35,27 +33,27 @@ class PayloadSplitter(private val payload: ByteArray) { ) ) } - val end = min(LastBlePacket.CAPACITY, rest.toInt()) + val end = min(layout.lastPacketCapacity, rest) ret.add( LastBlePacket( index = (middleFragments + 1).toByte(), - size = rest, + size = rest.toByte(), payload = payload.copyOfRange( - middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, - middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + end + middleFragments * layout.middlePacketCapacity + layout.firstPacketCapacityWithMiddlePackets, + middleFragments * layout.middlePacketCapacity + layout.firstPacketCapacityWithMiddlePackets + end ), crc32 = crc32 ) ) - if (rest > LastBlePacket.CAPACITY) { + if (rest > layout.lastPacketCapacity) { ret.add( LastOptionalPlusOneBlePacket( index = (middleFragments + 2).toByte(), - size = (rest - LastBlePacket.CAPACITY).toByte(), + size = (rest - layout.lastPacketCapacity).toByte(), payload = payload.copyOfRange( - middleFragments * MiddleBlePacket.CAPACITY + - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + - LastBlePacket.CAPACITY, + middleFragments * layout.middlePacketCapacity + + layout.firstPacketCapacityWithMiddlePackets + + layout.lastPacketCapacity, payload.size ) ) @@ -67,7 +65,7 @@ class PayloadSplitter(private val payload: ByteArray) { private fun splitInOnePacket(): List { val ret = ArrayList() val crc32 = payload.crc32() - val end = min(FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS, payload.size) + val end = min(layout.firstPacketCapacityWithoutMiddlePackets, payload.size) ret.add( FirstBlePacket( fullFragments = 0, @@ -76,7 +74,7 @@ class PayloadSplitter(private val payload: ByteArray) { crc32 = crc32 ) ) - if (payload.size > FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS) { + if (payload.size > layout.firstPacketCapacityWithoutMiddlePackets) { ret.add( LastOptionalPlusOneBlePacket( index = 1, diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/pair/CommandSigner.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/pair/CommandSigner.kt new file mode 100644 index 000000000000..d981396aee52 --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/pair/CommandSigner.kt @@ -0,0 +1,13 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.pair + +/** + * Signs a command payload for the shared BLE [app.aaps.pump.omnipod.common.bledriver.comm + * .session.Session]. This keeps the shared driver free of any Omnipod 5 type: only O5 + * connections pass a non-null signer (Dash never signs), and the O5 module supplies the + * concrete implementation (`O5CertificateStore`). + */ +interface CommandSigner { + + /** Sign [data] with the secondary key; returns the raw signature (r || s, 64 bytes). */ + fun signRaw(data: ByteArray): ByteArray +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/ResponseUtil.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/ResponseUtil.kt index d7aaf7ef4dbe..f2b72039cf77 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/ResponseUtil.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/ResponseUtil.kt @@ -4,6 +4,11 @@ import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.CouldNotParseRespo import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.NakResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoPulseLogPlusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoPulseLogPreviousResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoPulseLogRecentResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.Response import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse @@ -36,14 +41,12 @@ object ResponseUtil { private fun parseAdditionalStatusResponse(payload: ByteArray): Response { return when (byValue(payload[2], ResponseType.StatusResponseType.UNKNOWN)) { ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE -> DefaultStatusResponse(payload) // Unreachable; this response type is only used for requesting a default status response - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_1 -> throw UnsupportedOperationException("Status response page 1 is not (yet) implemented") + ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_1 -> PodInfoTriggeredAlertsResponse(payload) ResponseType.StatusResponseType.ALARM_STATUS -> AlarmStatusResponse(payload) - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_3 -> throw UnsupportedOperationException("Status response page 3 is not (yet) implemented") - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_5 -> throw UnsupportedOperationException("Status response page 5 is not (yet) implemented") - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_6 -> throw UnsupportedOperationException("Status response page 6 is not (yet) implemented") - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_70 -> throw UnsupportedOperationException("Status response page 70 is not (yet) implemented") - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_80 -> throw UnsupportedOperationException("Status response page 80 is not (yet) implemented") - ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_81 -> throw UnsupportedOperationException("Status response page 81 is not (yet) implemented") + ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_3 -> PodInfoPulseLogPlusResponse(payload) + ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_5 -> PodInfoActivationTimeResponse(payload) + ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_80 -> PodInfoPulseLogRecentResponse(payload) + ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_81 -> PodInfoPulseLogPreviousResponse(payload) ResponseType.StatusResponseType.UNKNOWN -> throw CouldNotParseResponseException("Unrecognized additional status response type: ${payload[2]}") } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/Session.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/Session.kt index 54035701a1ed..0fe77834bd2a 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/Session.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/Session.kt @@ -6,16 +6,24 @@ import app.aaps.core.utils.toHex import app.aaps.pump.omnipod.common.bledriver.comm.Ids import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.CouldNotParseResponseException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.MessageIOException import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO import app.aaps.pump.omnipod.common.bledriver.comm.message.MessagePacket import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendErrorConfirming import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendErrorSending +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendResult import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendSuccess import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageType import app.aaps.pump.omnipod.common.bledriver.comm.message.StringLengthPrefixEncoding import app.aaps.pump.omnipod.common.bledriver.comm.message.StringLengthPrefixEncoding.Companion.parseKeys +import app.aaps.pump.omnipod.common.bledriver.comm.pair.CommandSigner import app.aaps.pump.omnipod.common.bledriver.pod.command.base.Command +import app.aaps.pump.omnipod.common.bledriver.pod.command.base.CommandType +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.NakResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.Response +import app.aaps.pump.omnipod.common.bledriver.pod.util.MessageUtil +import java.nio.ByteBuffer sealed class CommandSendResult object CommandSendSuccess : CommandSendResult() @@ -26,7 +34,17 @@ data class CommandSendErrorConfirming(val msg: String) : CommandSendResult() sealed class CommandReceiveResult data class CommandReceiveSuccess(val result: Response) : CommandReceiveResult() -data class CommandReceiveError(val msg: String) : CommandReceiveResult() + +/** + * The command failed, but [result] is non-null when the pod still sent a well-formed reply + * saying so - a NAK, or an Omnipod 5 alarm-status response reporting a fault. + * + * Carrying it matters: a fault arrives *as* a failed command, so discarding the response + * discards the only notice that the pod has faulted. Callers should still report the command + * as failed, but record the pod state the reply carries first (see + * `O5BleManagerImpl.sendCommand`). + */ +data class CommandReceiveError(val msg: String, val result: Response? = null) : CommandReceiveResult() data class CommandAckError(val result: Response, val msg: String) : CommandReceiveResult() class Session( @@ -34,11 +52,24 @@ class Session( private val msgIO: MessageIO, private val ids: Ids, val sessionKeys: SessionKeys, - val enDecrypt: EnDecrypt + val enDecrypt: EnDecrypt, + /** Non-null only for O5 connections (see [app.aaps.pump.omnipod.common.bledriver.comm + * .legacy.session.O5Connection.establishSession]) - Dash has no certificate/ECDSA + * pairing infrastructure and never signs commands, so its `Connection + * .establishSession` leaves this at its default null. */ + private val commandSigner: CommandSigner? = null ) { + /** The 4-bit command-header sequence number (see [app.aaps.pump.omnipod.common + * .bledriver.pod.command.base.HeaderEnabledCommand.encodeHeader]) of the last command + * sent - the response envelope must echo this back (see [parseResponse]'s O5-only + * validation). Distinct from [SessionKeys.msgSequenceNumber], the outer BLE + * MessagePacket-level sequence number this class manages separately. */ + private var lastSentCommandSequenceNumber: Short? = null + fun sendCommand(cmd: Command): CommandSendResult { sessionKeys.msgSequenceNumber++ + lastSentCommandSequenceNumber = cmd.sequenceNumber aapsLogger.debug(LTag.PUMPBTCOMM, "Sending command: ${cmd.encoded.toHex()} in packet $cmd") val msg = getCmdMessage(cmd) @@ -83,18 +114,6 @@ class Session( val response = parseResponse(decrypted) - /*if (!responseType.isInstance(response)) { - if (response is AlarmStatusResponse) { - throw PodAlarmException(response) - } - if (response is NakResponse) { - throw NakResponseException(response) - } - throw IllegalResponseException(responseType, response) - } - - */ - sessionKeys.msgSequenceNumber++ val ack = getAck(responseMsgPacket) aapsLogger.debug(LTag.PUMPBTCOMM, "Sending ACK: ${ack.payload.toHex()} in packet $ack") @@ -102,6 +121,10 @@ class Session( if (sendResult !is MessageSendSuccess) { return CommandAckError(response, "Could not ACK the response: $sendResult") } + // Dash needs a received response and normal completion to update state and show its alarm. + if (response is NakResponse || (response is AlarmStatusResponse && commandSigner != null)) { + return CommandReceiveError("Pod rejected command or reported a fault: $response", response) + } return CommandReceiveSuccess(response) } @@ -111,18 +134,97 @@ class Session( val data = parseKeys(arrayOf(RESPONSE_PREFIX), decrypted.payload)[0] aapsLogger.info(LTag.PUMPBTCOMM, "Received decrypted response: ${data.toHex()} in packet: $decrypted") - // TODO verify length - - // val uniqueId = data.copyOfRange(0, 4) - // val lenghtAndSequenceNumber = data.copyOfRange(4, 6) + if (data.size < RESPONSE_ENVELOPE_MIN_SIZE) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Response envelope shorter than expected (${data.size} bytes): ${data.toHex()}") + } else { + val uniqueId = data.copyOfRange(0, 4) + val lengthAndSequenceNumber = data.copyOfRange(4, 6) + val crc = data.copyOfRange(data.size - 2, data.size) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Response envelope fields: uniqueId=${uniqueId.toHex()}, lengthAndSequenceNumber=${lengthAndSequenceNumber.toHex()}, " + + "crc=${crc.toHex()}" + ) + if (commandSigner != null) { + validateCrc(data) + lastSentCommandSequenceNumber?.let { validateSequenceNumber(lengthAndSequenceNumber, it) } + } + } val payload = data.copyOfRange(6, data.size - 2) - // val crc = data.copyOfRange(data.size - 2, data.size) - - // TODO validate uniqueId, sequenceNumber and crc return ResponseUtil.parseResponse(payload) } + /** + * Checks the response envelope's trailing CRC, which an Omnipod 5 pod computes over + * everything preceding it with the same [MessageUtil.createCrc] this driver already uses + * for outgoing messages. + * + * Rejecting a mismatch matters more than it looks: a badly mangled response would fail to + * parse anyway (`ResponseUtil.parseResponse` throws on an unrecognized type), so the case + * this actually catches is a *subtly* corrupted status response that still parses - wrong + * insulin-delivered counters, reservoir level, or delivery-status bits silently entering + * pod state and IOB. Throwing here routes the command into the existing undefined-state + * path ([CommandSendErrorConfirming]) instead of confirming it with corrupt data. + * + * O5-only, and that restriction is load-bearing. Pinned against captured traffic from two + * pods of each generation: + * - Omnipod 5 (`002a1c6e`, from a Trio installation that hit a real transient corruption + * incident): 495 of 495 pod-generated responses satisfy this CRC, as do all 518 outgoing + * messages - 1013 of 1013 overall. + * - Dash (`1749dbcb`, `podTypeValue: 4` in a Loop Report): outgoing messages satisfy it, + * pod responses never do. No initial value in the whole 16-bit space and no byte range + * reproduces them, which is why this must not run on a Dash connection. + * + * Community confirmation of the same split, from the Omnipod 5 testing discussion: "The + * DASH pods do not check the CRC... The Eros and Omnipod 5 pods both do apply the CRC + * check before accepting a command." + */ + @Throws(CouldNotParseResponseException::class) + internal fun validateCrc(data: ByteArray) { + val actual = ByteBuffer.wrap(data, data.size - 2, 2).short.toInt() and 0xffff + val expected = MessageUtil.createCrc(data.copyOfRange(0, data.size - 2)).toInt() and 0xffff + if (actual != expected) { + throw CouldNotParseResponseException( + "Response CRC mismatch: expected %04x, got %04x".format(expected, actual) + ) + } + } + + /** + * Checks that the pod echoed back the sequence number this protocol expects for a + * response: **the request's sequence number plus one**, wrapped to 4 bits - not the + * request's own number. OmnipodKit does the same, explicitly, in + * BleMessageTransport.sendMessage(): it sets `messageNumber = message.sequenceNum` and + * then calls `incrementMessageNumber()` with the comment "bump to match expected + * Omnipod message # in response", before readAndAckResponse() compares against it. + * + * Confirmed against real Omnipod 5 traffic (a working Loop/Trio installation's Device + * Communication Log): every request/response pair shows response == request + 1, e.g. + * requests with sequence 1/2/3/14 drew responses with sequence 2/3/4/15. An earlier + * revision of this method compared against the request's own number and so would have + * rejected every response the pod ever sent. + * + * [lengthAndSequenceNumber] packs the number the same way + * [app.aaps.pump.omnipod.common.bledriver.pod.command.base.HeaderEnabledCommand + * .encodeHeader] does for outgoing commands - bits 13-10 of the big-endian short + * (bit 15 = multi-command flag, bits 9-0 = body length). + * + * Internal (rather than private) to allow unit testing within this module against + * captured byte arrays, without simulating a full encrypted round trip. + */ + @Throws(CouldNotParseResponseException::class) + internal fun validateSequenceNumber(lengthAndSequenceNumber: ByteArray, sentSequenceNumber: Short) { + val packed = ByteBuffer.wrap(lengthAndSequenceNumber).short.toInt() + val actual = (packed shr 10) and 0x0f + val expected = (sentSequenceNumber.toInt() + 1) and 0x0f + if (actual != expected) { + throw CouldNotParseResponseException( + "Response sequence number mismatch: expected $expected (sent ${sentSequenceNumber.toInt() and 0x0f} + 1), got $actual" + ) + } + } + private fun getAck(response: MessagePacket): MessagePacket { val msg = MessagePacket( type = MessageType.ENCRYPTED, @@ -145,8 +247,9 @@ class Session( aapsLogger.debug(LTag.PUMPBTCOMM, "Sending command: ${wrapped.toHex()}") + val needsSigning = commandSigner != null && cmd.commandType in SIGNED_COMMAND_TYPES val msg = MessagePacket( - type = MessageType.ENCRYPTED, + type = if (needsSigning) MessageType.ENCRYPTED_SIGNED else MessageType.ENCRYPTED, sequenceNumber = sessionKeys.msgSequenceNumber, source = ids.myId, destination = ids.podId, @@ -154,7 +257,95 @@ class Session( eqos = 1 ) - return enDecrypt.encrypt(msg) + val encrypted = enDecrypt.encrypt(msg) + return if (needsSigning) sign(encrypted) else encrypted + } + + /** + * Appends a raw (r||s, 64-byte) P-256 ECDSA signature to an already AES-CCM-encrypted + * O5 command - confirmed against OmnipodKit's BleMessageTransport.swift getCmdMessage(): + * real O5 pod firmware rejects insulin-schedule/deactivate/cancel-delivery commands + * (this codebase's [CommandType.PROGRAM_BASAL]/[CommandType.PROGRAM_TEMP_BASAL]/ + * [CommandType.PROGRAM_BOLUS]/[CommandType.PROGRAM_INSULIN]/[CommandType.DEACTIVATE]/ + * [CommandType.STOP_DELIVERY] - the first four always embed a + * [app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramInsulinCommand] interlock + * block, which is why the Swift original's block-list check treats them the same as a + * standalone [CommandType.PROGRAM_INSULIN]) without this signature, even though every + * other command type is accepted unsigned. The signed byte range is the 16-byte AAD + * header plus the ciphertext+tag - i.e. everything [enDecrypt]'s AES-CCM authenticates, + * signed on top for an extra pod-side check that the command really came from the + * paired controller identity. Matches [EnDecrypt.decrypt]'s own AAD extraction + * (`asByteArray().copyOfRange(0, 16)`), so a receiver reconstructing this input from the + * wire bytes gets byte-identical input to what was signed here. + */ + private fun sign(encrypted: MessagePacket): MessagePacket { + val aad = encrypted.asByteArray(forEncryption = false).copyOfRange(0, 16) + val signature = requireNotNull(commandSigner) { "sign() called without a commandSigner" } + .signRaw(aad + encrypted.payload) + return encrypted.copy(signatureData = signature) + } + + /** + * Sends a raw O5 "AID setup" command payload (see [app.aaps.pump.omnipod.common + * .bledriver.pod.command.aid.O5AidSetupCommands]) and returns the decrypted response + * with [expectedResponsePrefix] stripped. Distinct from [sendCommand]/ + * [readAndAckResponse]: AID setup commands use a plain ASCII `key=value` wire format, + * not the `"S0.0=...,G0.0"` SLPE envelope [getCmdMessage] builds for ordinary + * [Command]s, and their responses aren't the binary [app.aaps.pump.omnipod.common + * .bledriver.pod.response.ResponseUtil] envelope either - just an ASCII prefix + * followed by raw bytes. Always sent as plain [MessageType.ENCRYPTED], never signed - + * confirmed against OmnipodKit's own sendO5AidCommand(), which never takes the + * Type-4-signing path (only the commands [sign] handles do). Throws on any protocol + * failure rather than returning a result type, matching the reference's + * o5SendAidSetupCommands(): any failure here must abort pod activation outright rather + * than silently continuing with a pod that never received this data. + */ + @Suppress("ThrowsCount") + fun sendAidSetupCommand(payload: ByteArray, expectedResponsePrefix: String): ByteArray { + sessionKeys.msgSequenceNumber++ + val msg = MessagePacket( + type = MessageType.ENCRYPTED, + sequenceNumber = sessionKeys.msgSequenceNumber, + source = ids.myId, + destination = ids.podId, + payload = payload, + eqos = 1 + ) + val encrypted = enDecrypt.encrypt(msg) + + var sendResult: MessageSendResult = MessageSendErrorSending("AID setup command not sent") + for (i in 0..MAX_TRIES) { + sendResult = msgIO.sendMessage(encrypted) + if (sendResult is MessageSendSuccess) break + } + if (sendResult !is MessageSendSuccess) { + throw MessageIOException("Could not send AID setup command: $sendResult") + } + + var responseMsgPacket: MessagePacket? = null + for (i in 0..MAX_TRIES) { + responseMsgPacket = msgIO.receiveMessage() + if (responseMsgPacket != null) break + } + val received = responseMsgPacket ?: throw MessageIOException("Could not read AID setup response") + + val decrypted = enDecrypt.decrypt(received) + sessionKeys.msgSequenceNumber++ + val ack = getAck(received) + val ackResult = msgIO.sendMessage(ack) + if (ackResult !is MessageSendSuccess) { + throw MessageIOException("Could not ACK AID setup response: $ackResult") + } + + val prefixBytes = expectedResponsePrefix.toByteArray(Charsets.US_ASCII) + if (decrypted.payload.size < prefixBytes.size || + !decrypted.payload.copyOfRange(0, prefixBytes.size).contentEquals(prefixBytes) + ) { + throw MessageIOException( + "AID setup response missing expected prefix '$expectedResponsePrefix': ${decrypted.payload.toHex()}" + ) + } + return decrypted.payload.copyOfRange(prefixBytes.size, decrypted.payload.size) } companion object { @@ -163,6 +354,26 @@ class Session( private const val COMMAND_SUFFIX = ",G0.0" private const val RESPONSE_PREFIX = "0.0=" + /** 4-byte uniqueId + 2-byte length/sequence + 2-byte CRC surrounding the payload. */ + private const val RESPONSE_ENVELOPE_MIN_SIZE = 8 + private const val MAX_TRIES = 4 + + /** + * O5-only command types that real pod firmware rejects unless sent as + * [MessageType.ENCRYPTED_SIGNED] - see [sign]'s doc comment for why + * [CommandType.PROGRAM_BASAL]/[CommandType.PROGRAM_TEMP_BASAL]/ + * [CommandType.PROGRAM_BOLUS] are included alongside the standalone + * [CommandType.PROGRAM_INSULIN]/[CommandType.DEACTIVATE]/[CommandType.STOP_DELIVERY] + * types the Swift reference's own block-list check names directly. + */ + private val SIGNED_COMMAND_TYPES = setOf( + CommandType.PROGRAM_BASAL, + CommandType.PROGRAM_TEMP_BASAL, + CommandType.PROGRAM_BOLUS, + CommandType.PROGRAM_INSULIN, + CommandType.DEACTIVATE, + CommandType.STOP_DELIVERY + ) } } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionEstablisher.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionEstablisher.kt index 47d0da2d4b30..81c3c151f347 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionEstablisher.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionEstablisher.kt @@ -44,11 +44,14 @@ class SessionEstablisher( if (sendResult !is MessageSendSuccess) { throw SessionEstablishmentException("Could not send the EAP AKA challenge: $sendResult") } + aapsLogger.debug(LTag.PUMPBTCOMM, "EAP-AKA: challenge sent (seq=$msgSeq), awaiting response") val challengeResponse = msgIO.receiveMessage() ?: throw SessionEstablishmentException("Could not establish session") + aapsLogger.debug(LTag.PUMPBTCOMM, "EAP-AKA: challenge response received (${challengeResponse.payload.size} bytes)") val newSqn = processChallengeResponse(challengeResponse) if (newSqn != null) { + aapsLogger.debug(LTag.PUMPBTCOMM, "EAP-AKA: resynchronization required, new SQN=$newSqn") return SessionNegotiationResynchronization( synchronizedEapSqn = newSqn, msgSequenceNumber = msgSeq @@ -58,6 +61,7 @@ class SessionEstablisher( msgSeq++ val success = eapSuccess() msgIO.sendMessage(success) + aapsLogger.debug(LTag.PUMPBTCOMM, "EAP-AKA: session keys negotiated, EAP-Success sent (seq=$msgSeq)") return SessionKeys( ck = milenage.ck, diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/ProgramBolusCommand.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/ProgramBolusCommand.kt index 7983d3339660..d57f34be15f2 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/ProgramBolusCommand.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/ProgramBolusCommand.kt @@ -17,20 +17,38 @@ class ProgramBolusCommand private constructor( multiCommandFlag: Boolean, private val programReminder: ProgramReminder, private val numberOfTenthPulses: Short, - private val delayUntilFirstTenthPulseInUsec: Int + private val delayUntilFirstTenthPulseInUsec: Int, + private val o5BolusInfo: O5BolusInfo? ) : HeaderEnabledCommand(CommandType.PROGRAM_BOLUS, uniqueId, sequenceNumber, multiCommandFlag) { + /** The O5-only trailing fields - see this class's doc comment. [bolusSource] is + * "typically 1" per OmnipodKit's own comment; [mealUnitsTenthPulses]/ + * [correctionUnitsTenthPulses] are 0 for prime/cannula-insertion boluses. */ + class O5BolusInfo( + val bolusSource: Byte, + val mealUnitsTenthPulses: Short, + val correctionUnitsTenthPulses: Short + ) + override val encoded: ByteArray get() { - val bolusCommand = ByteBuffer.allocate(LENGTH.toInt()) + val length = if (o5BolusInfo != null) O5_LENGTH else LENGTH + val bodyLength = if (o5BolusInfo != null) O5_BODY_LENGTH else BODY_LENGTH + val bolusCommandBuffer = ByteBuffer.allocate(length.toInt()) .put(commandType.value) - .put(BODY_LENGTH) + .put(bodyLength) .put(programReminder.encoded) .putShort(numberOfTenthPulses) .putInt(delayUntilFirstTenthPulseInUsec) .putShort(0.toShort()) // Extended bolus pulses .putInt(0) // Delay between tenth extended pulses in usec - .array() + if (o5BolusInfo != null) { + bolusCommandBuffer + .put(o5BolusInfo.bolusSource) + .putShort(o5BolusInfo.mealUnitsTenthPulses) + .putShort(o5BolusInfo.correctionUnitsTenthPulses) + } + val bolusCommand = bolusCommandBuffer.array() val interlockCommand = interlockCommand.encoded val header: ByteArray = encodeHeader( uniqueId, @@ -53,6 +71,7 @@ class ProgramBolusCommand private constructor( ", programReminder=" + programReminder + ", numberOfTenthPulses=" + numberOfTenthPulses + ", delayUntilFirstTenthPulseInUsec=" + delayUntilFirstTenthPulseInUsec + + ", o5BolusInfo=" + (o5BolusInfo != null) + ", commandType=" + commandType + ", uniqueId=" + uniqueId + ", sequenceNumber=" + sequenceNumber + @@ -65,6 +84,8 @@ class ProgramBolusCommand private constructor( private var numberOfUnits: Double? = null private var delayBetweenPulsesInEighthSeconds: Byte? = null private var programReminder: ProgramReminder? = null + private var mealUnits: Double? = null + private var correctionUnits: Double? = null fun setNumberOfUnits(numberOfUnits: Double): Builder { require(numberOfUnits > 0.0) { "Number of units should be greater than zero" } @@ -84,6 +105,14 @@ class ProgramBolusCommand private constructor( return this } + /** O5 only - selects the O5 wire format (see this class's doc comment). Must NOT be + * called for Dash/Eros, which use the original, shorter format instead. */ + fun setO5BolusInfo(mealUnits: Double, correctionUnits: Double): Builder { + this.mealUnits = mealUnits + this.correctionUnits = correctionUnits + return this + } + override fun buildCommand(): ProgramBolusCommand { requireNotNull(numberOfUnits) { "numberOfUnits can not be null" } requireNotNull(delayBetweenPulsesInEighthSeconds) { "delayBetweenPulsesInEighthSeconds can not be null" } @@ -104,6 +133,13 @@ class ProgramBolusCommand private constructor( ProgramInsulinCommand.DeliveryType.BOLUS ) val delayUntilFirstTenthPulseInUsec = delayBetweenPulsesInEighthSeconds!! / 8 * 100000 + val o5BolusInfo = mealUnits?.let { meal -> + O5BolusInfo( + bolusSource = O5_BOLUS_SOURCE, + mealUnitsTenthPulses = Math.round(meal * 200).toShort(), + correctionUnitsTenthPulses = Math.round((correctionUnits ?: 0.0) * 200).toShort() + ) + } return ProgramBolusCommand( interlockCommand, uniqueId!!, @@ -111,7 +147,8 @@ class ProgramBolusCommand private constructor( multiCommandFlag, programReminder!!, (numberOfPulses * 10).toShort(), - delayUntilFirstTenthPulseInUsec + delayUntilFirstTenthPulseInUsec, + o5BolusInfo ) } } @@ -120,6 +157,10 @@ class ProgramBolusCommand private constructor( private const val LENGTH: Short = 15 private const val BODY_LENGTH: Byte = 13 + private const val O5_LENGTH: Short = 20 + private const val O5_BODY_LENGTH: Byte = 18 + private const val O5_BOLUS_SOURCE: Byte = 1 + private fun calculateChecksum(numberOfSlots: Byte, byte10And11: Short, numberOfPulses: Short): Short { return MessageUtil.calculateChecksum( ByteBuffer.allocate(7) diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtil.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtil.kt index 00841cab4ca7..94a7a6752bb3 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtil.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtil.kt @@ -38,9 +38,9 @@ object ProgramBasalUtil { (previousTenthPulsesPerSlot * numberOfSlotsInCurrentElement).toShort() ) ) + startSlotIndex = (numberOfSlotsInCurrentElement + startSlotIndex).toByte() previousTenthPulsesPerSlot = tenthPulsesPerSlot[i] numberOfSlotsInCurrentElement = 1 - startSlotIndex = (numberOfSlotsInCurrentElement + startSlotIndex).toByte() } else { numberOfSlotsInCurrentElement++ } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/ActivationProgress.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/ActivationProgress.kt index 93b43ee81a0f..43add1bbc45f 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/ActivationProgress.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/ActivationProgress.kt @@ -3,6 +3,19 @@ package app.aaps.pump.omnipod.common.bledriver.pod.definition enum class ActivationProgress { NOT_STARTED, GOT_POD_VERSION, + + /** O5-only: the AID setup command batch (see [app.aaps.pump.omnipod.common.bledriver + * .pod.command.aid.O5AidSetupCommands]) has been sent. Confirmed directly against + * OmnipodKit's BlePodComms.swift: pairPod() sends AssignAddressCommand (opcode 0x07 - + * the exact same wire command as [app.aaps.pump.omnipod.common.bledriver.pod.command + * .GetVersionCommand] here, just kept under its historical Eros-era name upstream) + * and only *after* that completes does handleO5Setup() run the AID batch, immediately + * before SetupPod (0x03, [app.aaps.pump.omnipod.common.bledriver.pod.command + * .SetUniqueIdCommand] here). Must come after [GOT_POD_VERSION], not before it - an + * earlier version of this code had it reversed. Dash's activation flow skips straight + * past this state (it has no such requirement), so it costs Dash nothing to have this + * ordinal exist. */ + AID_SETUP, SET_UNIQUE_ID, PROGRAMMED_LOW_RESERVOIR_ALERTS, REPROGRAMMED_LUMP_OF_COAL_ALERT, diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgram.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgram.kt index 8ad9737fdc55..c3949ee9dea9 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgram.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgram.kt @@ -1,29 +1,33 @@ package app.aaps.pump.omnipod.common.bledriver.pod.definition -import java.util.Calendar +import com.google.gson.annotations.SerializedName import java.util.Collections +import java.util.TimeZone class BasalProgram( segments: List ) { - val segments: MutableList = segments.toMutableList() - get() = Collections.unmodifiableList(field) + // Keeps the JSON key "segments" so saved Pod state keeps deserializing across this field's rename. + // Alternate can be removed once all users have upgraded from the O5 beta builds. + @SerializedName(value = "segments", alternate = ["mutableSegmentsOrNull"]) + private var mutableSegmentsOrNull: MutableList? = segments.toMutableList() + private val mutableSegments: MutableList + get() = mutableSegmentsOrNull ?: mutableListOf().also { mutableSegmentsOrNull = it } + + val segments: MutableList get() = Collections.unmodifiableList(mutableSegments) fun addSegment(segment: Segment) { - segments.add(segment) + mutableSegments.add(segment) } fun hasZeroUnitSegments() = segments.any { it.basalRateInHundredthUnitsPerHour == 0 } - fun rateAt(date: Long): Double { - val instance = Calendar.getInstance() - instance.timeInMillis = date - val hourOfDay = instance[Calendar.HOUR_OF_DAY] - val minuteOfHour = instance[Calendar.MINUTE] - val slotIndex = hourOfDay * 2 + minuteOfHour.div(30) - val slot = segments.find { it.startSlotIndex <= slotIndex && slotIndex < it.endSlotIndex } - return (slot?.basalRateInHundredthUnitsPerHour ?: 0).toDouble() / 100 + /** [podOffset] in milliseconds; falls back to the device's current time zone offset if unknown. */ + fun rateAt(date: Long, podOffset: Int?): Double { + val offset = podOffset ?: TimeZone.getDefault().getOffset(date) + val localMillis = Math.floorMod(date + offset, 86400000L) + return rateInHundredthsAtSlot((localMillis / 1800000L).toInt()) / 100.0 } /** diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodStatus.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodStatus.kt index 6acb26892b0d..b221a2b3af97 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodStatus.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodStatus.kt @@ -23,4 +23,6 @@ enum class PodStatus(override val value: Byte) : HasValue { UNKNOWN(0xff.toByte()); fun isRunning(): Boolean = this == RUNNING_ABOVE_MIN_VOLUME || this == RUNNING_BELOW_MIN_VOLUME + + fun isActivationTimeExceeded(): Boolean = this == LUMP_OF_COAL } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodType.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodType.kt new file mode 100644 index 000000000000..dd649de4b0f3 --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PodType.kt @@ -0,0 +1,86 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.definition + +/** + * Unified pod type, identified by the productId byte returned in a pod's VersionResponse. + * + * Ported from OmnipodKit's PodType.swift (loopandlearn/OmnipodKit) to support Eros, Dash, + * and Omnipod 5 pods under a single model so BLE scanning/pairing/command logic can branch + * on pod type instead of assuming Dash-only, as the existing bledriver package did. + */ +enum class PodType(val value: Int) { + + /** Can be used before the actual pod type is known. */ + UNKNOWN(0x0), + + /** Omnipod Eros (PM=PI=2.x.y), AKA "Omnipod Classic (gen 3)". Uses RileyLink. */ + EROS(0x2), + + + /** Omnipod DASH: either TWI board (firmware 4.x.y) or NXP BLE (firmware 3.x.y). */ + DASH(0x4), + + /** Omnipod 5. Value still needs independent verification against real pod hardware. */ + OMNIPOD_5(0x5); + + companion object { + + private const val NEAR_ZERO_BASAL_RATE = 0.01 + + fun fromValue(value: Int): PodType = + entries.firstOrNull { it.value == value } ?: UNKNOWN + } + + val briefName: String + get() = when (this) { + UNKNOWN -> "" + EROS -> "Eros" + DASH -> "DASH" + OMNIPOD_5 -> "O5" + } + + val fullName: String + get() = when (this) { + UNKNOWN -> "Omnipod" + EROS -> "Omnipod Classic" + DASH -> "Omnipod DASH" + OMNIPOD_5 -> "Omnipod 5" + } + + /** DASH uses a blue needle tab; both Eros and O5 pods use a clear tab. */ + val tabColor: String + get() = if (this == DASH) "blue" else "clear" + + /** Only Eros pods use a RileyLink for communication. */ + val usesRileyLink: Boolean + get() = this == EROS + + /** Only Eros pods report an RSSI value in DetailedStatus. */ + val reportsRSSI: Boolean + get() = this == EROS + + /** + * Non-Eros pods use a small near-zero basal rate for pulse timing purposes + * when the actual programmed basal rate is zero. + */ + val zeroBasalRate: Double + get() = if (this == EROS) 0.0 else NEAR_ZERO_BASAL_RATE + + /** + * Top byte used when constructing the fixed 32-bit controller Id: + * - Eros PDMs use 0x1F for the top byte. + * - Dash PDMs use 0x17, with the bottom 5 nibbles derived from the PDM serial number << 2. + * - Omnipod 5 PDMs appear to follow the same SN-based scheme as Dash; the top byte value + * below is a placeholder pending confirmation against real O5 pairing traffic. + */ + val topIdByte: Int + get() = when (this) { + EROS -> 0x1F + DASH -> 0x17 + OMNIPOD_5 -> 0x00 + UNKNOWN -> 0x00 + } + + val isEros: Boolean get() = this == EROS + val isDash: Boolean get() = this == DASH + val isO5: Boolean get() = this == OMNIPOD_5 +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PulseLogEntry.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PulseLogEntry.kt new file mode 100644 index 000000000000..124ba7864854 --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PulseLogEntry.kt @@ -0,0 +1,95 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.definition + +/** + * What kind of delivery activity a [PulseLogEntry] represents - the `ppp` bit-field + * documented on the openaps/openomni wiki's "Pulse Log Entry" page. + */ +enum class PulseLogEntryType(val value: Int) { + + NONE(0), + BASAL(1), + TEMP_BASAL(2), + BOLUS(3), + EXTENDED_BOLUS(4), + UNKNOWN(-1); + + companion object { + + fun fromValue(value: Int): PulseLogEntryType = entries.firstOrNull { it.value == value } ?: UNKNOWN + } +} + +/** + * A single decoded pulse-log dword, as returned in status pages 3/80/81 ([PodInfoPulseLogPlusResponse] + * /[PodInfoPulseLogRecentResponse]/[PodInfoPulseLogPreviousResponse] - see + * `app.aaps.pump.omnipod.common.bledriver.pod.response`). Bit layout ("eeeeee0a pppliiib + * cccccccc dfgggggg") and field meanings are documented on the openaps/openomni project's + * wiki (github.com/openaps/openomni/wiki/Pulse-Log-Entry) - the only place either OmnipodKit + * or this codebase's own (production) Eros pulse-log classes turned out to have any semantic + * decoding at all; both of those just store/display the raw dwords. + * + * [loadCountVal] is deliberately NOT converted to an insulin-unit amount here - the wiki + * documents it as a motor-load measurement (`LoadCountVal = (((LOADCNT & 0x1FF) * 1000) + + * 488) / 976`), not a pulse count, and no source found ties it to a confirmed units-per-count + * scaling factor. Treat it as a diagnostic/relative value, not a dose quantity - asserting a + * specific insulin amount here without that confirmation would be actively misleading in a + * dosing-history context. + * + * Verified against the wiki's own worked example: dword `0x51213E00` decodes to + * encoder=20, drivingFlag=LOAD2, pulseMode=BASAL, immediateBolusTick=0, loadCountVal=125, + * faultFlag=false - matching this class's [PulseLogEntryTest] golden-value test exactly. + */ +data class PulseLogEntry( + /** 6-bit encoder count (`eeeeee`, bits 31-26). */ + val encoder: Int, + /** Which of the two drive coils is active (`a`, bit 24) - false = LOAD1, true = LOAD2. */ + val load2Active: Boolean, + /** What kind of delivery this entry represents (`ppp`, bits 23-21). */ + val pulseMode: PulseLogEntryType, + /** Low-reservoir signal at the time of this entry (`l`, bit 20). */ + val lowReservoir: Boolean, + /** Immediate-bolus tick counter, in quarter-seconds (`iii`, bits 19-17). */ + val immediateBolusTick: Int, + /** Motor-load measurement for this entry (`b`+`cccccccc`, bits 16-8) - see this class's + * doc comment for why this is not converted to an insulin-unit amount. */ + val loadCountVal: Int, + /** Last analog comparator read (`d`, bit 7) - motor-diagnostic bit. */ + val lastComparatorRead: Boolean, + /** Encoder-validation fault flag (`f`, bit 6). */ + val faultFlag: Boolean, + /** Signed 6-bit last computed encoder value (`gggggg`, bits 5-0) - 0 is nominal. */ + val lastEncoderValue: Int +) { + + companion object { + + fun decode(dword: Int): PulseLogEntry { + val encoder = (dword ushr 26) and 0x3F + val load2Active = ((dword ushr 24) and 0x1) != 0 + val pulseMode = PulseLogEntryType.fromValue((dword ushr 21) and 0x7) + val lowReservoir = ((dword ushr 20) and 0x1) != 0 + val immediateBolusTick = (dword ushr 17) and 0x7 + val loadCountValHigh = (dword ushr 8) and 0xFF + val loadCountValLow = (dword ushr 16) and 0x1 + val loadCountVal = (loadCountValHigh shl 1) or loadCountValLow + val lastComparatorRead = ((dword ushr 7) and 0x1) != 0 + val faultFlag = ((dword ushr 6) and 0x1) != 0 + val encoderRaw = dword and 0x3F + val lastEncoderValue = if (encoderRaw and 0x20 != 0) encoderRaw - 64 else encoderRaw + + return PulseLogEntry( + encoder = encoder, + load2Active = load2Active, + pulseMode = pulseMode, + lowReservoir = lowReservoir, + immediateBolusTick = immediateBolusTick, + loadCountVal = loadCountVal, + lastComparatorRead = lastComparatorRead, + faultFlag = faultFlag, + lastEncoderValue = lastEncoderValue + ) + } + + fun decodeAll(dwords: List): List = dwords.map { decode(it) } + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoActivationTimeResponse.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoActivationTimeResponse.kt new file mode 100644 index 000000000000..3fdb95d60fef --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoActivationTimeResponse.kt @@ -0,0 +1,46 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.response + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType.StatusResponseType +import app.aaps.pump.omnipod.common.bledriver.pod.util.byValue +import java.nio.ByteBuffer + +/** + * Status page 5 - pod activation date/time plus fault event code & fault time (same + * fault info [AlarmStatusResponse] reports, available here even without a live alarm + * status query). [year] is the raw 2-digit value the pod reports (e.g. 26 for 2026) - + * converting to a full year/epoch timestamp is left to the caller. + * + * Byte layout ported from OmnipodKit's PodInfoActivationTime.swift - see + * [PodInfoTriggeredAlertsResponse]'s doc comment for the +2 offset-mapping rationale. + */ +class PodInfoActivationTimeResponse( + encoded: ByteArray +) : AdditionalStatusResponseBase(StatusResponseType.STATUS_RESPONSE_PAGE_5, encoded) { + + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val additionalStatusResponseType: Byte = encoded[2] + val faultEventCode: AlarmType = byValue(encoded[3], AlarmType.UNKNOWN) + val faultTime: Short = ByteBuffer.wrap(byteArrayOf(encoded[4], encoded[5])).short + val month: Int = encoded[14].toInt() and 0xff + val day: Int = encoded[15].toInt() and 0xff + val year: Int = encoded[16].toInt() and 0xff + val hour: Int = encoded[17].toInt() and 0xff + val minute: Int = encoded[18].toInt() and 0xff + + override fun toString(): String { + return "PodInfoActivationTimeResponse(" + + "messageType=$messageType, " + + "messageLength=$messageLength, " + + "additionalStatusResponseType=$additionalStatusResponseType, " + + "faultEventCode=$faultEventCode, " + + "faultTime=$faultTime, " + + "month=$month, " + + "day=$day, " + + "year=$year, " + + "hour=$hour, " + + "minute=$minute" + + ")" + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogPlusResponse.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogPlusResponse.kt new file mode 100644 index 000000000000..c95063b83c1f --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogPlusResponse.kt @@ -0,0 +1,52 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.response + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PulseLogEntry +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType.StatusResponseType +import app.aaps.pump.omnipod.common.bledriver.pod.util.byValue +import java.nio.ByteBuffer + +/** + * Status page 3 - up to the last 60 pulse-log entries plus fault/activation-time + * info. Byte layout ported from OmnipodKit's PodInfoPulseLogPlus.swift - see + * [PodInfoTriggeredAlertsResponse]'s doc comment for the +2 offset-mapping rationale. + */ +class PodInfoPulseLogPlusResponse( + encoded: ByteArray +) : AdditionalStatusResponseBase(StatusResponseType.STATUS_RESPONSE_PAGE_3, encoded) { + + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val additionalStatusResponseType: Byte = encoded[2] + val faultEventCode: AlarmType = byValue(encoded[3], AlarmType.UNKNOWN) + val faultTime: Short = ByteBuffer.wrap(byteArrayOf(encoded[4], encoded[5])).short + val activationTime: Short = ByteBuffer.wrap(byteArrayOf(encoded[6], encoded[7])).short + val entrySize: Int = encoded[8].toInt() and 0xff + val maxEntries: Int = encoded[9].toInt() and 0xff + val pulseLog: List + + /** [pulseLog] decoded per-entry - see [PulseLogEntry]'s doc comment for what's confirmed + * vs. left as raw diagnostic values. */ + val decodedPulseLog: List by lazy { PulseLogEntry.decodeAll(pulseLog) } + + init { + require(entrySize == 4) { "Unexpected pulseLogPlus entry size: $entrySize" } + val logStartOffset = 10 + val nEntries = (encoded.size - logStartOffset) / 4 + pulseLog = parsePulseLog(encoded, logStartOffset, nEntries) + } + + override fun toString(): String { + return "PodInfoPulseLogPlusResponse(" + + "messageType=$messageType, " + + "messageLength=$messageLength, " + + "additionalStatusResponseType=$additionalStatusResponseType, " + + "faultEventCode=$faultEventCode, " + + "faultTime=$faultTime, " + + "activationTime=$activationTime, " + + "entrySize=$entrySize, " + + "maxEntries=$maxEntries, " + + "pulseLog=$pulseLog" + + ")" + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogPreviousResponse.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogPreviousResponse.kt new file mode 100644 index 000000000000..2c0cfe5c0bea --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogPreviousResponse.kt @@ -0,0 +1,48 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.response + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PulseLogEntry +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType.StatusResponseType +import java.nio.ByteBuffer + +/** + * Status page 81 (0x51) - like page 80, but the (up to) 50 pulse-log entries + * preceding the "recent" window. Byte layout ported from OmnipodKit's + * PodInfoPulseLog.swift (`PodInfoPulseLogPrevious`) - see + * [PodInfoTriggeredAlertsResponse]'s doc comment for the +2 offset-mapping rationale. + */ +class PodInfoPulseLogPreviousResponse( + encoded: ByteArray +) : AdditionalStatusResponseBase(StatusResponseType.STATUS_RESPONSE_PAGE_81, encoded) { + + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val additionalStatusResponseType: Byte = encoded[2] + + /** Entry count the pod reports; may exceed the number of entries actually + * returned in this payload, matching OmnipodKit's own cross-check. */ + val nEntries: Int = ByteBuffer.wrap(byteArrayOf(encoded[3], encoded[4])).short.toInt() and 0xffff + val pulseLog: List + + /** [pulseLog] decoded per-entry - see [PulseLogEntry]'s doc comment for what's confirmed + * vs. left as raw diagnostic values. */ + val decodedPulseLog: List by lazy { PulseLogEntry.decodeAll(pulseLog) } + + init { + val logStartOffset = 5 + val nEntriesCalculated = (encoded.size - logStartOffset) / 4 + require(nEntries <= nEntriesCalculated) { + "PulseLogPrevious reports $nEntries entries but only $nEntriesCalculated fit in ${encoded.size} bytes" + } + pulseLog = parsePulseLog(encoded, logStartOffset, nEntries) + } + + override fun toString(): String { + return "PodInfoPulseLogPreviousResponse(" + + "messageType=$messageType, " + + "messageLength=$messageLength, " + + "additionalStatusResponseType=$additionalStatusResponseType, " + + "nEntries=$nEntries, " + + "pulseLog=$pulseLog" + + ")" + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogRecentResponse.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogRecentResponse.kt new file mode 100644 index 000000000000..d17bbc4ba11a --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoPulseLogRecentResponse.kt @@ -0,0 +1,41 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.response + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PulseLogEntry +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType.StatusResponseType +import java.nio.ByteBuffer + +/** + * Status page 80 (0x50) - the most recent (up to) 50 pulse-log entries. Byte layout + * ported from OmnipodKit's PodInfoPulseLog.swift (`PodInfoPulseLogRecent`) - see + * [PodInfoTriggeredAlertsResponse]'s doc comment for the +2 offset-mapping rationale. + */ +class PodInfoPulseLogRecentResponse( + encoded: ByteArray +) : AdditionalStatusResponseBase(StatusResponseType.STATUS_RESPONSE_PAGE_80, encoded) { + + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val additionalStatusResponseType: Byte = encoded[2] + val indexLastEntry: Int = ByteBuffer.wrap(byteArrayOf(encoded[3], encoded[4])).short.toInt() and 0xffff + val pulseLog: List + + /** [pulseLog] decoded per-entry - see [PulseLogEntry]'s doc comment for what's confirmed + * vs. left as raw diagnostic values. */ + val decodedPulseLog: List by lazy { PulseLogEntry.decodeAll(pulseLog) } + + init { + val logStartOffset = 5 + val nEntries = (encoded.size - logStartOffset) / 4 + pulseLog = parsePulseLog(encoded, logStartOffset, nEntries) + } + + override fun toString(): String { + return "PodInfoPulseLogRecentResponse(" + + "messageType=$messageType, " + + "messageLength=$messageLength, " + + "additionalStatusResponseType=$additionalStatusResponseType, " + + "indexLastEntry=$indexLastEntry, " + + "pulseLog=$pulseLog" + + ")" + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoTriggeredAlertsResponse.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoTriggeredAlertsResponse.kt new file mode 100644 index 000000000000..845c1a29ee84 --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PodInfoTriggeredAlertsResponse.kt @@ -0,0 +1,41 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.response + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType.StatusResponseType +import java.nio.ByteBuffer + +/** + * Status page 1 - unacknowledged triggered-alert values, one per [AlertType] slot + * (pod-clock minutes-since-activation each alert fired, or 0 if never triggered). + * Byte layout ported from OmnipodKit's PodInfoTriggeredAlerts.swift; that reference + * implementation's `init` operates on a Data slice with the subtype byte already at + * index 0, so its documented offsets are shifted by +2 here to match this codebase's + * convention (used by [AlarmStatusResponse] etc.) of indexing the full response, + * including the messageType/length prefix. + */ +class PodInfoTriggeredAlertsResponse( + encoded: ByteArray +) : AdditionalStatusResponseBase(StatusResponseType.STATUS_RESPONSE_PAGE_1, encoded) { + + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val additionalStatusResponseType: Byte = encoded[2] + val unknownWord: Short = ByteBuffer.wrap(byteArrayOf(encoded[3], encoded[4])).short + val alertActivations: Map = AlertType.entries + .filter { it != AlertType.UNKNOWN } + .sortedBy { it.index } + .mapIndexed { i, slot -> + val offset = 5 + 2 * i + slot to ByteBuffer.wrap(byteArrayOf(encoded[offset], encoded[offset + 1])).short + }.toMap() + + override fun toString(): String { + return "PodInfoTriggeredAlertsResponse(" + + "messageType=$messageType, " + + "messageLength=$messageLength, " + + "additionalStatusResponseType=$additionalStatusResponseType, " + + "unknownWord=$unknownWord, " + + "alertActivations=$alertActivations" + + ")" + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PulseLogUtil.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PulseLogUtil.kt new file mode 100644 index 000000000000..2c5826acabf7 --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/PulseLogUtil.kt @@ -0,0 +1,13 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.response + +import java.nio.ByteBuffer + +/** Parses a trailing run of big-endian 32-bit pulse-log entries, shared by the + * status-page responses that carry one (types 3/80/81) - each entry is opaque, + * bit-packed telemetry, not a plain counter (see OmnipodKit's PodInfoPulseLog.swift + * `binaryDescription` debug helper), so no further interpretation happens here. */ +internal fun parsePulseLog(encoded: ByteArray, startOffset: Int, entryCount: Int): List = + (0 until entryCount).map { i -> + val base = startOffset + i * 4 + ByteBuffer.wrap(byteArrayOf(encoded[base], encoded[base + 1], encoded[base + 2], encoded[base + 3])).int + } diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/ResponseType.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/ResponseType.kt index 180b8037ffe4..b397e3c4a4e8 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/ResponseType.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/response/ResponseType.kt @@ -17,8 +17,6 @@ enum class ResponseType(override val value: Byte) : HasValue { ALARM_STATUS(0x02.toByte()), STATUS_RESPONSE_PAGE_3(0x03.toByte()), STATUS_RESPONSE_PAGE_5(0x05.toByte()), - STATUS_RESPONSE_PAGE_6(0x06.toByte()), - STATUS_RESPONSE_PAGE_70(0x46.toByte()), STATUS_RESPONSE_PAGE_80(0x50.toByte()), STATUS_RESPONSE_PAGE_81(0x51.toByte()), UNKNOWN(0xff.toByte()); diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManager.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManager.kt index abc9b7e8e3d1..44bae4a89869 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManager.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManager.kt @@ -14,6 +14,7 @@ import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse +import app.aaps.pump.omnipod.common.util.PodTimeZone import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Maybe import io.reactivex.rxjava3.core.Single @@ -43,7 +44,9 @@ interface OmnipodDashPodStateManager { val failedConnectionsAfterRetries: Int val timeZoneId: String? + val timeZoneOffset: Int? val timeZoneUpdated: Long? + var timeChangeInProgress: Boolean val sameTimeZone: Boolean // The TimeZone is the same on the phone and on the pod val lastUpdatedSystem: Long // System.currentTimeMillis() val lastStatusResponseReceived: Long @@ -86,6 +89,9 @@ interface OmnipodDashPodStateManager { val lastBolus: LastBolus? var suspendAlertsEnabled: Boolean + /** Counts the current expected rate up to [now] before changing it. */ + fun updateBasalExpected(now: Long) + fun increaseMessageSequenceNumber() fun increaseEapAkaSequenceNumber(): ByteArray fun commitEapAkaSequenceNumber() @@ -99,6 +105,8 @@ interface OmnipodDashPodStateManager { fun incrementSuccessfulConnectionAttemptsAfterRetries() fun incrementFailedConnectionsAfterRetries() fun updateTimeZone() + fun confirmTimeZone(timeZone: PodTimeZone) + fun recordBasalProgramTimeZone(timeZone: PodTimeZone) fun createActiveCommand( historyId: Long, @@ -155,7 +163,8 @@ interface OmnipodDashPodStateManager { @Transient var sendError: Throwable?, var basalProgram: BasalProgram?, val tempBasal: TempBasal?, - val requestedBolus: Double? + val requestedBolus: Double?, + var basalTimeZone: PodTimeZone? = null ) // TODO: set created to "now" on boot diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManagerImpl.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManagerImpl.kt index 35090496f8c6..1df4633e9234 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -24,6 +24,7 @@ import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse import app.aaps.pump.omnipod.common.keys.DashStringNonPreferenceKey +import app.aaps.pump.omnipod.common.util.PodTimeZone import com.google.gson.Gson import dev.zacsweers.metro.Inject import io.reactivex.rxjava3.core.Completable @@ -150,6 +151,16 @@ class OmnipodDashPodStateManagerImpl( override val timeZoneId: String? get() = podState.timeZone + override val timeZoneOffset: Int? + get() = podState.timeZoneOffset + + override var timeChangeInProgress: Boolean + get() = podState.timeChangeInProgress + set(value) { + podState.timeChangeInProgress = value + store() + } + override val sameTimeZone: Boolean get() { val now = System.currentTimeMillis() @@ -322,10 +333,6 @@ class OmnipodDashPodStateManagerImpl( } } - // Offset to convert UTC epoch to pod-local time for rateAt (which uses device timezone internally) - val deviceOffsetMs = TimeZone.getDefault().getOffset(startTime) - val podTimeAdjustmentMs = timeZoneOffset - deviceOffsetMs - // Integrate over each segment return boundaries.sorted().windowed(2).mapIndexed { index, (boundaryStart, boundaryEnd) -> val segmentHours = (boundaryEnd - boundaryStart) / 3600_000.0 @@ -335,7 +342,7 @@ class OmnipodDashPodStateManagerImpl( val rate = tempBasal?.let { tb -> val tempBasalEnd = tb.startTime + tb.durationInMinutes * 60_000L tb.rate.takeIf { segmentMid in tb.startTime until tempBasalEnd } - } ?: basalProgram?.rateAt(segmentMid + podTimeAdjustmentMs) ?: return null // Abort if rate unknown + } ?: basalProgram?.rateAt(segmentMid, timeZoneOffset) ?: return null // Abort if rate unknown val delivery = rate * segmentHours @@ -436,13 +443,18 @@ class OmnipodDashPodStateManagerImpl( return podState.timeZoneUpdated } - override fun updateTimeZone() { - val timeZone = TimeZone.getDefault() - val now = System.currentTimeMillis() + override fun updateTimeZone() = confirmTimeZone(PodTimeZone.now()) - podState.timeZoneOffset = timeZone.getOffset(now) + override fun confirmTimeZone(timeZone: PodTimeZone) { + podState.timeZoneOffset = timeZone.offset podState.timeZone = timeZone.id - podState.timeZoneUpdated = now + podState.timeZoneUpdated = timeZone.updatedAt + store() + } + + override fun recordBasalProgramTimeZone(timeZone: PodTimeZone) { + podState.activeCommand?.basalTimeZone = timeZone + store() } override val expiry: ZonedDateTime? @@ -815,16 +827,7 @@ class OmnipodDashPodStateManagerImpl( ).toInt().toShort() } - // Update basal expected delivery - podState.basalExpected = podState.basalExpected?.let { - integrateExpectedDelivery( - startTime = podState.lastUpdatedSystem, - endTime = now, - timeZoneOffset = podState.timeZoneOffset, - tempBasal = tempBasal, - basalProgram = basalProgram - )?.let { delta -> it + delta } - } ?: basalDelivered.takeIf { isActivationCompleted } + updateBasalExpected(now) // Update bolus pulses delivered (exclude basal corrections) podState.bolusPulsesDelivered = podState.bolusPulsesDelivered?.let { @@ -856,6 +859,25 @@ class OmnipodDashPodStateManagerImpl( updateLastBolusFromResponse(bolusPulsesRemaining) } + @Synchronized + override fun updateBasalExpected(now: Long) { + val start = podState.basalExpectedUpdatedAt ?: podState.lastUpdatedSystem + val end = maxOf(start, now) + if (end != now) { + logger.warn(LTag.PUMP, "Expected basal already counted to $end; requested update time was $now") + } + podState.basalExpected = podState.basalExpected?.let { + integrateExpectedDelivery( + startTime = start, + endTime = end, + timeZoneOffset = podState.timeZoneOffset, + tempBasal = tempBasal, + basalProgram = basalProgram + )?.let { delta -> it + delta } + } ?: basalDelivered.takeIf { isActivationCompleted } + podState.basalExpectedUpdatedAt = end + } + private inline fun logBasalTracking(block: () -> Unit) { val driftBefore = basalDrift.takeIf { isActivationCompleted } ?: 0.0 block() @@ -1031,6 +1053,7 @@ class OmnipodDashPodStateManagerImpl( var timeZone: String? = null, // TimeZone ID (e.g. "Europe/Amsterdam") var timeZoneOffset: Int? = null, var timeZoneUpdated: Long? = null, + var timeChangeInProgress: Boolean = false, var alarmSynced: Boolean = false, var suspendAlertsEnabled: Boolean = false, @@ -1067,6 +1090,7 @@ class OmnipodDashPodStateManagerImpl( var bolusPulsesDelivered: Short? = null, // Cumulative count of bolus pulses for basal tracking var basalExpected: Double? = null, // Initialized to actual on first drift calculation + var basalExpectedUpdatedAt: Long? = null, // Null in state saved before this field was added var lastBasalCorrectionTime: Long? = null, // Timestamp of last basal correction attempt (for cooldown) @Transient var basalCorrectionInProgress: Boolean = false // Transient flag: true while basal correction is delivering diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/util/BluetoothServiceUuids.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/util/BluetoothServiceUuids.kt new file mode 100644 index 000000000000..ef85f7ceba95 --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/util/BluetoothServiceUuids.kt @@ -0,0 +1,66 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.util + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType + +/** + * Centralized BLE service/characteristic UUIDs for Dash and Omnipod 5 pods, ported from + * OmnipodKit's BluetoothServices.swift (loopandlearn/OmnipodKit). + * + * Dash and O5 share the same GATT *service* UUID and *command* characteristic UUID - + * only the *data* characteristic and the pre-pairing advertisement UUID scheme differ. + * This is additive, standalone infrastructure: existing Dash code paths + * ([app.aaps.pump.omnipod.common.bledriver.comm.legacy.scan.BleDiscoveredDevice], + * [app.aaps.pump.omnipod.common.bledriver.comm.interfaces.scan.PodScanner]) still use + * their own inline UUID string literals and are untouched by this file; it exists so new + * pod-type-aware scanning code has one correct place to read these values from instead of + * re-deriving them. + */ +object BluetoothServiceUuids { + + /** GATT service UUID, identical for Dash and O5. */ + const val SERVICE_UUID = "1A7E4024-E3ED-4464-8B7E-751E03D0DC5F" + + /** Command ("CMD") characteristic UUID, identical for Dash and O5. */ + const val COMMAND_CHARACTERISTIC_UUID = "1A7E2441-E3ED-4464-8B7E-751E03D0DC5F" + + /** Dash's data characteristic UUID. */ + const val DASH_DATA_CHARACTERISTIC_UUID = "1A7E2442-E3ED-4464-8B7E-751E03D0DC5F" + + /** O5's data characteristic UUID (differs from Dash's only in this one segment). */ + const val O5_DATA_CHARACTERISTIC_UUID = "1A7E2443-E3ED-4464-8B7E-751E03D0DC5F" + + /** Dash's 16-bit advertisement service UUID, used as a BLE scan filter. */ + const val DASH_ADVERTISEMENT_UUID = "00004024-0000-1000-8000-00805f9b34fb" + + /** + * O5's 128-bit advertisement service UUID *before pairing* (embeds a placeholder + * PDM id of 0xFFFFFFFE), used as a BLE scan filter. After pairing, a real pod's + * advertisement embeds the actual PDM id in the same position instead - see + * [o5AdvertisementUuidForPdmId]. + */ + const val O5_UNPAIRED_ADVERTISEMENT_UUID = "CE1F923D-C539-48EA-7300-0AFFFFFFFE00" + + /** + * O5 Heartbeat service, used for pod keep-alive. Distinct from the main pod + * service/characteristics above. + */ + const val O5_HEARTBEAT_SERVICE_UUID = "7DED7A6C-CA72-46A7-A3A2-6061F6FDCAEB" + const val O5_HEARTBEAT_ADVERTISEMENT_UUID = "ECF301E2-674B-4474-94D0-364F3AA653E6" + const val O5_HEARTBEAT_CHARACTERISTIC_UUID = "7DED7A6D-CA72-46A7-A3A2-6061F6FDCAEB" + + /** Builds the O5 advertisement UUID embedding a specific (already-paired) PDM id. */ + fun o5AdvertisementUuidForPdmId(pdmId: Long): String = + "CE1F923D-C539-48EA-7300-0A%08X00".format(pdmId and 0xFFFFFFFFL) + + /** The data characteristic UUID to use for a given [podType] (Dash or O5). */ + fun dataCharacteristicUuid(podType: PodType): String = when (podType) { + PodType.OMNIPOD_5 -> O5_DATA_CHARACTERISTIC_UUID + else -> DASH_DATA_CHARACTERISTIC_UUID + } + + /** The pre-pairing advertisement UUID to scan for, for a given [podType]. */ + fun unpairedAdvertisementUuid(podType: PodType): String = when (podType) { + PodType.OMNIPOD_5 -> O5_UNPAIRED_ADVERTISEMENT_UUID + else -> DASH_ADVERTISEMENT_UUID + } +} diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/ui/compose/OmnipodComposeHost.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/ui/compose/OmnipodComposeHost.kt index 4afe155ac153..2b30c7381174 100644 --- a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/ui/compose/OmnipodComposeHost.kt +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/ui/compose/OmnipodComposeHost.kt @@ -26,6 +26,7 @@ import app.aaps.core.ui.compose.pump.BlePreCheckHost import app.aaps.core.ui.compose.pump.KeepScreenOnEffect import app.aaps.core.ui.compose.pump.PumpOverviewScreen import app.aaps.core.ui.compose.pump.PumpOverviewUiState +import app.aaps.pump.omnipod.common.R import app.aaps.pump.omnipod.common.ui.wizard.compose.ActivationType import app.aaps.pump.omnipod.common.ui.wizard.compose.OmnipodOverviewEvent import app.aaps.pump.omnipod.common.ui.wizard.compose.OmnipodWizardScreen @@ -47,11 +48,15 @@ fun OmnipodComposeHost( wizardViewModel: @Composable () -> OmnipodWizardViewModel, onConfirmDiscardPod: () -> Unit, activationNeedsExtraContent: () -> Boolean = { false }, + showExtraContentForHistory: Boolean = false, + extraContent: (@Composable (onBack: () -> Unit) -> Unit)? = null, + credentialImportContent: (@Composable (onImported: () -> Unit, onBack: () -> Unit) -> Unit)? = null, historyContent: (@Composable (onBack: () -> Unit) -> Unit)? = null ) { val context = LocalContext.current var showWizard by remember { mutableStateOf(false) } var showExtraContent by remember { mutableStateOf(false) } + var showCredentialImport by remember { mutableStateOf(false) } var wizardActivationType by remember { mutableStateOf(null) } var isDeactivation by remember { mutableStateOf(false) } var showDialog by remember { mutableStateOf(false) } @@ -75,8 +80,8 @@ fun OmnipodComposeHost( } } - LaunchedEffect(showWizard, showExtraContent) { - if (!showWizard && !showExtraContent) { + LaunchedEffect(showWizard, showExtraContent, showCredentialImport) { + if (!showWizard && !showExtraContent && !showCredentialImport) { setToolbarConfig(ToolbarConfig(title = pluginName, navigationIcon = overviewNavIcon, actions = settingsAction)) } } @@ -86,9 +91,10 @@ fun OmnipodComposeHost( // The wizard has its own handler in WizardScreen, so it is not covered here. NavigationBackHandler( state = rememberNavigationEventState(NavigationEventInfo.None), - isBackEnabled = showExtraContent, + isBackEnabled = showExtraContent || showCredentialImport, onBackCompleted = { showExtraContent = false + showCredentialImport = false wizardActivationType = null } ) @@ -97,11 +103,13 @@ fun OmnipodComposeHost( overviewEvents.collect { event -> when (event) { is OmnipodOverviewEvent.StartActivation -> { - if (activationNeedsExtraContent()) { + wizardActivationType = event.activationType + isDeactivation = false + if (activationNeedsExtraContent() && credentialImportContent != null) { + showCredentialImport = true + } else if (activationNeedsExtraContent()) { showExtraContent = true } else { - wizardActivationType = event.activationType - isDeactivation = false showWizard = true } } @@ -112,13 +120,19 @@ fun OmnipodComposeHost( } is OmnipodOverviewEvent.ShowHistory -> { - if (historyContent != null) showExtraContent = true + if (showExtraContentForHistory || extraContent != null || historyContent != null) { + showExtraContent = true + } } is OmnipodOverviewEvent.ShowDialog -> { dialogTitle = event.title dialogMessage = event.message - showDialog = true + if (event.title == context.getString(R.string.omnipod_common_pod_management_button_discard_pod)) { + showDiscardConfirm = true + } else { + showDialog = true + } } is OmnipodOverviewEvent.ConfirmDiscardPod -> { @@ -160,6 +174,17 @@ fun OmnipodComposeHost( } when { + showCredentialImport -> credentialImportContent?.invoke( + { + showCredentialImport = false + showWizard = true + }, + { + showCredentialImport = false + wizardActivationType = null + } + ) + showWizard -> { KeepScreenOnEffect() // The wizard uses Bluetooth, so it starts only after the check has passed @@ -184,7 +209,7 @@ fun OmnipodComposeHost( } } - showExtraContent -> historyContent?.invoke { showExtraContent = false } + showExtraContent -> (historyContent ?: extraContent)?.invoke { showExtraContent = false } else -> { val uiState by overviewState.collectAsStateWithLifecycle() PumpOverviewScreen(state = uiState, customContent = { PodImage() }) diff --git a/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/util/OmnipodTimeChange.kt b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/util/OmnipodTimeChange.kt new file mode 100644 index 000000000000..b55821f0aa4f --- /dev/null +++ b/pump/omnipod/common/src/main/kotlin/app/aaps/pump/omnipod/common/util/OmnipodTimeChange.kt @@ -0,0 +1,72 @@ +package app.aaps.pump.omnipod.common.util + +import java.util.TimeZone + +/** The time zone used to build a basal command, not the time zone at a later confirmation. */ +data class PodTimeZone(val id: String, val offset: Int, val updatedAt: Long) { + + companion object { + + fun now(timestamp: Long = System.currentTimeMillis()): PodTimeZone { + val zone = TimeZone.getDefault() + return PodTimeZone(zone.id, zone.getOffset(timestamp), timestamp) + } + } +} + +/** + * Shared automatic DST/time-zone policy for Dash and O5. + * + * The drivers check stored offsets on startup and every minute, so a missed Android time event + * still gets handled. They block loop invocation until the basal program is confirmed. A bolus or + * a user-suspended pod is left alone. An automatic suspend can be recovered after restart. + * + * Any active temp basal is lost when the pod is suspended to reprogram its clock, the same way the + * Medtrum driver accepts a temp basal may be cancelled by its own time update: the loop sets a new + * one next cycle rather than this driver reconstructing the old one. + */ +class OmnipodTimeChange { + + private var inProgress = false + private var retryAt = Long.MIN_VALUE + private var failureAlerted = false + + @Synchronized + fun isInProgress(): Boolean = inProgress + + @Synchronized + fun tryStart(now: Long): Boolean { + if (inProgress || now < retryAt) return false + inProgress = true + return true + } + + @Synchronized + fun finish(now: Long) { + inProgress = false + retryAt = now + 60000 + } + + /** True only for the first of a run of failures, so the retry every minute does not keep sounding an alarm. */ + @Synchronized + fun shouldSoundOnFailure(): Boolean { + if (failureAlerted) return false + failureAlerted = true + return true + } + + /** Called once the correction succeeds, so the next unrelated failure sounds again. */ + @Synchronized + fun resetFailureAlert() { + failureAlerted = false + } + + companion object { + + fun needsCorrection(podOffset: Int?, phoneOffset: Int, recovering: Boolean): Boolean = + recovering || (podOffset != null && podOffset != phoneOffset) + + fun canProgram(running: Boolean, suspended: Boolean, bolusActive: Boolean, unconfirmed: Boolean, recovering: Boolean): Boolean = + running && !bolusActive && !unconfirmed && (!suspended || recovering) + } +} diff --git a/pump/omnipod/common/src/main/res/values/strings.xml b/pump/omnipod/common/src/main/res/values/strings.xml index 7491f7082260..847b18f777b1 100644 --- a/pump/omnipod/common/src/main/res/values/strings.xml +++ b/pump/omnipod/common/src/main/res/values/strings.xml @@ -22,6 +22,7 @@ Failed to set time Failed to resume delivery Failed to initialize the Pod + Failed to deactivate the Pod Failed to insert cannula The Pod\'s activation time has been exceeded. This Pod can no longer be activated. Failed to verify activation progress. Please retry. @@ -33,6 +34,8 @@ Alert configuration has been updated in the Pod. The time on the Pod has been updated. + Waiting for the Pod time to update. + The automatic Pod time update failed. The loop is suspended until the time update is confirmed. Check the Pod status. Set time @@ -52,6 +55,7 @@ Active Pod Alerts Firmware Version Time on Pod + Pod Activated At uncertain @@ -119,25 +123,14 @@ Pod Fault Inactive Pod Fault: %1$03d %2$s + Fault Occurred + PDM Notification Ref: %1$s - - Empty Reservoir - Insulin delivery stopped. Change Pod now. - Auto-Off - Insulin delivery stopped. Your PDM and Pod have not communicated in the last 4 hours. To resume insulin delivery, change Pod now. - Pod Expired - Insulin delivery stopped. Change Pod now. - Occlusion Detected - Insulin delivery stopped. Change Pod now. Check your BG - Pod error - Insulin delivery stopped. Change Pod now. - Pod will expire soon Pod will expire soon @@ -200,8 +193,62 @@ Pod Alert: %1$s Pod Alerts: %1$s + + + https://api.osaid-keymanager.org/o5/aaps/start + Certificates + Omnipod 5 + O5 + Unconfirmed command + Pump integration for Omnipod 5. + Certificate store + Import and manage the Omnipod 5 pairing certificate. + Import certificate + Imported certificate for controller %1$s + Controller %1$s + Installed certificates + Certificate can only be removed when there is no active pod + Import Omnipod 5 certificate + Paste a certificate string obtained from a trusted source. This does not pair with a pod by itself - it only makes the certificate available for pairing. + Certificate string + Paste a certificate string first + Empty certificate received + Could not parse that certificate - check it was copied completely + Could not import the certificate. Please try again. + Try again + Internet connection needed + Unable to connect. An internet connection is needed to retrieve your Omnipod 5 certificate. This is a one-time step before pairing your first pod. Once the certificate is retrieved, you can pair later pods without internet. Please try again once you have a network connection. + Omnipod 5 certificate imported + Error importing certificate + This device\'s WebView does not support the certificate bridge. Please update Android System WebView and try again. + Not enough insulin left in the reservoir for this bolus. + A bolus is already in progress. + Setting the new basal profile might have failed. Refresh pod status to confirm or deny this. + Unable to verify whether the SMB bolus (%1$s U) succeeded. Refresh pod status to confirm or deny this command. + Bolus delivery status is uncertain. Refresh pod status to confirm or deny this command. + Setting the temp basal might have failed. Refresh pod status to confirm or deny this. + Failed to update Pod alert settings. + Cancelling the temp basal result is uncertain. Refresh pod status to confirm or deny this. + An earlier dose could not be confirmed with the pod, so a new one was not sent. Refresh pod status once the pod is reachable again. + Omnipod 5 driver does not support extended boluses + Omnipod 5 driver does not support TDD + No active alerts + No profile active + Fill a new Pod + with enough insulin for 3 days.\n\nListen for two beeps from the Pod during the filling process. These indicate that the minimum amount of 80U has been inserted. Be sure to completely empty the fill syringe, even after hearing the two beeps.\n\nAfter filling the Pod, please press Next.\n\nNote: do not remove the Pod\'s needle cap at this time. + Trying to pair with the new Pod and prime it.\n\nWhen the initialization process has successfully been completed, you can press Next. + + + Bluetooth Address + Connection quality + Delivery Status + Firmware %1$s / Bluetooth %2$s + Insulin delivery is suspended Pod Hard End %1$s (%2$s) + Timezone on pod is different from the timezone on phone. Basal rate is incorrect. Switch profile to fix %1$.2f U/h, %2$d minutes diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIOTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIOTest.kt new file mode 100644 index 000000000000..ea20d45ec574 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/legacy/io/BleIOTest.kt @@ -0,0 +1,52 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.legacy.io + +import android.bluetooth.BluetoothGattCharacteristic +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * [BleIO.usesIndicate] - the notify-vs-indicate CCCD decision `readyToRead()` uses to set + * up the CMD/DATA characteristics. Real O5 pairing attempts consistently disconnect a few + * seconds after SPS0 is sent with no response ever received - this used to unconditionally + * assume indicate (correct for Dash, never verified for O5), so this pins the fix: the + * choice must follow the characteristic's own declared properties, the same way + * [app.aaps.pump.omnipod.common.bledriver.comm.legacy.session.O5Connection + * .enableHeartbeatNotifications] already does for the heartbeat characteristic. + */ +class BleIOTest { + + @Test + fun `usesIndicate is true when the characteristic declares PROPERTY_INDICATE`() { + val characteristic = mock() + whenever(characteristic.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_INDICATE) + + assertThat(BleIO.usesIndicate(characteristic)).isTrue() + } + + @Test + fun `usesIndicate is false when the characteristic only declares PROPERTY_NOTIFY`() { + val characteristic = mock() + whenever(characteristic.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY) + + assertThat(BleIO.usesIndicate(characteristic)).isFalse() + } + + @Test + fun `usesIndicate is true when the characteristic declares both properties - indicate is chosen`() { + val characteristic = mock() + whenever(characteristic.properties) + .thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY or BluetoothGattCharacteristic.PROPERTY_INDICATE) + + assertThat(BleIO.usesIndicate(characteristic)).isTrue() + } + + @Test + fun `usesIndicate is false when the characteristic declares neither property`() { + val characteristic = mock() + whenever(characteristic.properties).thenReturn(0) + + assertThat(BleIO.usesIndicate(characteristic)).isFalse() + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacketTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacketTest.kt new file mode 100644 index 000000000000..df6506ef48b4 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/MessagePacketTest.kt @@ -0,0 +1,57 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.message + +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * [MessagePacket.signatureData] (O5 Type-4/ENCRYPTED_SIGNED commands, see + * `Session.sign()`) must be appended after the payload on the wire but stay outside the + * 16-byte header's size field - the exact subtlety that would otherwise make a + * receiver's AAD reconstruction disagree with the sender's, silently breaking every + * signed command's AES-CCM tag. + */ +class MessagePacketTest { + + private fun packet(payload: ByteArray, signatureData: ByteArray? = null) = MessagePacket( + type = MessageType.ENCRYPTED_SIGNED, + source = Id.fromInt(1), + destination = Id.fromInt(2), + payload = payload, + sequenceNumber = 1, + signatureData = signatureData + ) + + @Test + fun `signatureData is appended after the payload on the wire`() { + val payload = byteArrayOf(0x01, 0x02, 0x03) + val signature = ByteArray(64) { 0x7F } + + val bytes = packet(payload, signature).asByteArray() + + assertThat(bytes.size).isEqualTo(16 + payload.size + signature.size) + assertThat(bytes.copyOfRange(16, 16 + payload.size)).isEqualTo(payload) + assertThat(bytes.copyOfRange(16 + payload.size, bytes.size)).isEqualTo(signature) + } + + @Test + fun `the header's size field is unaffected by a trailing signature - only payload counts`() { + val payload = byteArrayOf(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08) + val signature = ByteArray(64) { 0x11 } + + val unsigned = packet(payload, signatureData = null).asByteArray() + val signed = packet(payload, signatureData = signature).asByteArray() + + assertThat(signed.copyOfRange(6, 8)).isEqualTo(unsigned.copyOfRange(6, 8)) + assertThat(signed.copyOfRange(0, 16)).isEqualTo(unsigned.copyOfRange(0, 16)) + } + + @Test + fun `no signatureData means nothing extra is appended`() { + val payload = byteArrayOf(0x0A, 0x0B) + + val bytes = packet(payload, signatureData = null).asByteArray() + + assertThat(bytes.size).isEqualTo(16 + payload.size) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacketLayoutTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacketLayoutTest.kt new file mode 100644 index 000000000000..d5893d525938 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/BlePacketLayoutTest.kt @@ -0,0 +1,48 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.packet + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * Pins [BlePacketLayout]'s derived capacities against the values that used to be hardcoded + * constants in [BlePacket] (Dash) and against OmnipodKit's BlePodProfile.swift (O5), so a + * future edit to the formulas can't silently drift from either. + */ +class BlePacketLayoutTest : TestBase() { + + @Test + fun `Dash layout reproduces the previously-hardcoded packet constants exactly`() { + val layout = BlePacketLayout.DASH + + assertThat(layout.maxPayloadSize).isEqualTo(20) + assertThat(layout.maxFragments).isEqualTo(15) + assertThat(layout.firstPacketCapacityWithoutMiddlePackets).isEqualTo(13) + assertThat(layout.firstPacketCapacityWithMiddlePackets).isEqualTo(18) + assertThat(layout.firstPacketCapacityWithOptionalPlusOnePacket).isEqualTo(18) + assertThat(layout.middlePacketCapacity).isEqualTo(19) + assertThat(layout.lastPacketCapacity).isEqualTo(14) + } + + @Test + fun `O5 layout matches OmnipodKit's BlePodProfile omnipod5 preset`() { + val layout = BlePacketLayout.OMNIPOD_5 + + assertThat(layout.maxPayloadSize).isEqualTo(244) + assertThat(layout.maxFragments).isEqualTo(15) + assertThat(layout.firstPacketCapacityWithoutMiddlePackets).isEqualTo(237) + assertThat(layout.firstPacketCapacityWithMiddlePackets).isEqualTo(242) + assertThat(layout.firstPacketCapacityWithOptionalPlusOnePacket).isEqualTo(242) + assertThat(layout.middlePacketCapacity).isEqualTo(243) + assertThat(layout.lastPacketCapacity).isEqualTo(238) + } + + @Test + fun `PodType blePacketLayout picks OMNIPOD_5 only for the O5 pod type`() { + assertThat(PodType.OMNIPOD_5.blePacketLayout).isEqualTo(BlePacketLayout.OMNIPOD_5) + assertThat(PodType.DASH.blePacketLayout).isEqualTo(BlePacketLayout.DASH) + assertThat(PodType.EROS.blePacketLayout).isEqualTo(BlePacketLayout.DASH) + assertThat(PodType.UNKNOWN.blePacketLayout).isEqualTo(BlePacketLayout.DASH) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitterJoinerTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitterJoinerTest.kt new file mode 100644 index 000000000000..b442ebe9a947 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/packet/PayloadSplitterJoinerTest.kt @@ -0,0 +1,190 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.packet + +import app.aaps.pump.omnipod.common.bledriver.comm.message.CrcMismatchException +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import kotlin.random.Random + +/** + * Round-trips payloads through [PayloadSplitter] -> [BlePacket.toByteArray] -> [PayloadJoiner] + * for both [BlePacketLayout.DASH] and [BlePacketLayout.OMNIPOD_5]. + * + * The O5 sweep in particular targets the bug fixed alongside the O5 layout support: packet + * "rest"/size fields are on-wire unsigned bytes (0..255), but Kotlin's Byte is signed, so any + * payload whose last-packet remainder exceeds 127 previously sign-extended into a negative + * length and broke [PayloadJoiner] parsing. Dash never produced a remainder over 127 (its + * packets max out at 20 bytes), so this was unreachable there - O5's 244-byte packets reach it + * routinely for realistic message sizes (e.g. certificate-carrying pairing messages). + */ +class PayloadSplitterJoinerTest : TestBase() { + + private fun payloadOf(size: Int, seed: Int): ByteArray = Random(seed).nextBytes(size) + + private fun roundTrip(payload: ByteArray, layout: BlePacketLayout): ByteArray { + val packets = PayloadSplitter(payload, layout).splitInPackets() + val encoded = packets.map { it.toByteArray(layout) } + + val joiner = PayloadJoiner(encoded.first(), layout) + for (packetBytes in encoded.drop(1)) { + joiner.accumulate(packetBytes) + } + return joiner.finalize() + } + + @Test + fun `Dash round-trip holds for every supported payload size`() { + for (size in 1..283) { + val payload = payloadOf(size, seed = size) + val result = roundTrip(payload, BlePacketLayout.DASH) + assertThat(result).isEqualTo(payload) + } + } + + @Test + fun `O5 round-trip holds for every payload size from 1 to 2000 bytes`() { + for (size in 1..2000) { + val payload = payloadOf(size, seed = size) + val result = roundTrip(payload, BlePacketLayout.OMNIPOD_5) + assertThat(result).isEqualTo(payload) + } + } + + + @Test + fun `O5 layout constants match OmnipodKit's asserted values`() { + val layout = BlePacketLayout.OMNIPOD_5 + assertThat(layout.maxPayloadSize).isEqualTo(244) + assertThat(layout.maxFragments).isEqualTo(15) + assertThat(layout.firstPacketCapacityWithoutMiddlePackets).isEqualTo(237) + assertThat(layout.firstPacketCapacityWithMiddlePackets).isEqualTo(242) + assertThat(layout.firstPacketCapacityWithOptionalPlusOnePacket).isEqualTo(242) + assertThat(layout.middlePacketCapacity).isEqualTo(243) + assertThat(layout.lastPacketCapacity).isEqualTo(238) + } + + @Test + fun `O5 split produces the same packet counts OmnipodKit asserts`() { + val expected = mapOf( + 0 to 1, + 100 to 1, + 300 to 2, + 242 to 2, + 243 to 2, + 500 to 3, + 641 to 3, + 642 to 3, + 893 to 4, + 953 to 4, + 18 to 1, + 15 to 1, + 11 to 1, + 17 to 1, + 204 to 1, + 176 to 1, + 20 to 1 + ) + + for ((size, packetCount) in expected) { + val packets = PayloadSplitter(payloadOf(size, seed = size), BlePacketLayout.OMNIPOD_5).splitInPackets() + assertThat(packets).hasSize(packetCount) + } + } + + @Test + fun `O5 953-byte payload reports three full fragments, as OmnipodKit asserts`() { + val packets = PayloadSplitter(payloadOf(953, seed = 2), BlePacketLayout.OMNIPOD_5).splitInPackets() + + assertThat(packets).hasSize(4) + assertThat(packets.filterIsInstance().single().fullFragments).isEqualTo(3) + } + + @Test + fun `O5 last-packet remainder over 127 round-trips correctly (regression for the signed-Byte bug)`() { + val size = 242 + 2 * 243 + 200 + val payload = payloadOf(size, seed = 4242) + + val packets = PayloadSplitter(payload, BlePacketLayout.OMNIPOD_5).splitInPackets() + val lastPacket = packets.filterIsInstance().single() + assertThat(lastPacket.size.toUnsignedInt()).isEqualTo(200) + + val result = roundTrip(payload, BlePacketLayout.OMNIPOD_5) + assertThat(result).isEqualTo(payload) + } + + @Test + fun `LastOptionalPlusOneBlePacket round-trips a size byte over 127`() { + val layout = BlePacketLayout.OMNIPOD_5 + val payload = payloadOf(200, seed = 55) + val packet = LastOptionalPlusOneBlePacket(index = 5, payload = payload, size = 200.toByte()) + + val encoded = packet.toByteArray(layout) + val parsed = LastOptionalPlusOneBlePacket.parse(encoded, layout) + + assertThat(parsed.size.toUnsignedInt()).isEqualTo(200) + assertThat(parsed.payload).isEqualTo(payload) + } + + + @Test + fun `O5 packets are written at their exact length, not padded to the 244-byte MTU`() { + val payload = payloadOf(44, seed = 7) + + val packets = PayloadSplitter(payload, BlePacketLayout.OMNIPOD_5).splitInPackets() + val encoded = packets.single().toByteArray(BlePacketLayout.OMNIPOD_5) + + assertThat(encoded.size).isEqualTo(51) + } + + @Test + fun `O5 multi-packet messages pad no packet, including the last`() { + val payload = payloadOf(642, seed = 8) + + val packets = PayloadSplitter(payload, BlePacketLayout.OMNIPOD_5).splitInPackets() + val encoded = packets.map { it.toByteArray(BlePacketLayout.OMNIPOD_5) } + + assertThat(encoded.last().size).isLessThan(BlePacketLayout.OMNIPOD_5.maxPayloadSize) + val headerBytes = encoded.size * 1 + 1 + 4 + 1 + assertThat(encoded.sumOf { it.size }).isEqualTo(payload.size + headerBytes) + assertThat(roundTrip(payload, BlePacketLayout.OMNIPOD_5)).isEqualTo(payload) + } + + @Test + fun `Dash packets keep their existing full-length padding`() { + val payload = payloadOf(5, seed = 9) + + val encoded = PayloadSplitter(payload, BlePacketLayout.DASH) + .splitInPackets().single().toByteArray(BlePacketLayout.DASH) + + assertThat(encoded.size).isEqualTo(BlePacketLayout.DASH.maxPayloadSize) + } + + @Test + fun `Byte toUnsignedInt reinterprets the full 0-255 range correctly`() { + assertThat(0.toByte().toUnsignedInt()).isEqualTo(0) + assertThat(127.toByte().toUnsignedInt()).isEqualTo(127) + assertThat(128.toByte().toUnsignedInt()).isEqualTo(128) + assertThat(200.toByte().toUnsignedInt()).isEqualTo(200) + assertThat(255.toByte().toUnsignedInt()).isEqualTo(255) + } + + @Test + fun `corrupted payload is still detected via CRC mismatch after joining (O5)`() { + val payload = payloadOf(500, seed = 99) + val packets = PayloadSplitter(payload, BlePacketLayout.OMNIPOD_5).splitInPackets() + val encoded = packets.map { it.toByteArray(BlePacketLayout.OMNIPOD_5) }.toMutableList() + + val corruptIndex = 6 + encoded[encoded.lastIndex][corruptIndex] = (encoded.last()[corruptIndex] + 1).toByte() + + val joiner = PayloadJoiner(encoded.first(), BlePacketLayout.OMNIPOD_5) + for (packetBytes in encoded.drop(1)) { + joiner.accumulate(packetBytes) + } + + assertThrows(CrcMismatchException::class.java) { + joiner.finalize() + } + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionAlarmResponseTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionAlarmResponseTest.kt new file mode 100644 index 000000000000..212ad21812a0 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionAlarmResponseTest.kt @@ -0,0 +1,102 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.session + +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.Nonce +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessagePacket +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendErrorSending +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendSuccess +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageType +import app.aaps.pump.omnipod.common.bledriver.comm.message.StringLengthPrefixEncoding +import app.aaps.pump.omnipod.common.bledriver.comm.pair.CommandSigner +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertInstanceOf +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class SessionAlarmResponseTest { + + private val msgIO: MessageIO = mock() + private val enDecrypt: EnDecrypt = mock() + + // The reported Dash fault response, with a test pod ID in the envelope. + private val dashAlarm = "0000000214180216020d0000000e003e10000403ff0004000008000000000000" + private val o5Alarm = "002a1c6e301802160209020000010c92000000030d0cc8000000000070410258" + + @Test + fun `a Dash alarm is a received response so status processing can reach the notification`() { + val result = session(dashAlarm).readAndAckResponse() + + val response = assertInstanceOf(assertInstanceOf(result).result) + assertThat(response.alarmType).isEqualTo(AlarmType.ALARM_SAWCOP_RESET) + assertThat(response.podStatus).isEqualTo(PodStatus.ALARM) + assertThat(response.deliveryStatus).isEqualTo(DeliveryStatus.SUSPENDED) + assertAckSent() + } + + @Test + fun `an Omnipod 5 alarm still fails the command and carries the fault response`() { + val result = session(o5Alarm, commandSigner = mock()).readAndAckResponse() + + assertInstanceOf(assertInstanceOf(result).result) + assertAckSent() + } + + @Test + fun `a Dash alarm is preserved when sending its ACK fails`() { + val session = session(dashAlarm) + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendErrorSending("Test ACK failure")) + + val result = session.readAndAckResponse() + + val response = assertInstanceOf(assertInstanceOf(result).result) + assertThat(response.alarmType).isEqualTo(AlarmType.ALARM_SAWCOP_RESET) + assertAckSent() + } + + @Test + fun `a missing response still fails without a fault response`() { + val session = session(dashAlarm) + whenever(msgIO.receiveMessage()).thenReturn(null) + + val result = assertInstanceOf(session.readAndAckResponse()) + + assertThat(result.result).isNull() + } + + private fun session(envelopeHex: String, commandSigner: CommandSigner? = null): Session { + val envelope = ByteArray(envelopeHex.length / 2) { envelopeHex.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + val ids = Ids.forController(Id.fromInt(1), Id.fromInt(2)) + val packet = MessagePacket( + type = MessageType.ENCRYPTED, + source = ids.podId, + destination = ids.myId, + payload = StringLengthPrefixEncoding.formatKeys(arrayOf("0.0="), arrayOf(envelope)), + sequenceNumber = 2 + ) + whenever(msgIO.receiveMessage()).thenReturn(packet) + whenever(enDecrypt.decrypt(packet)).thenReturn(packet) + whenever(enDecrypt.encrypt(any())).thenAnswer { it.getArgument(0) } + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + val keys = SessionKeys(ByteArray(16), Nonce(ByteArray(8), 0), 1) + return Session(AAPSLoggerTest(), msgIO, ids, keys, enDecrypt, commandSigner) + } + + private fun assertAckSent() { + val ack = argumentCaptor() + verify(msgIO).sendMessage(ack.capture()) + assertThat(ack.firstValue.ack).isTrue() + assertThat(ack.firstValue.ackNumber.toInt()).isEqualTo(3) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionResponseCrcTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionResponseCrcTest.kt new file mode 100644 index 000000000000..f5fbd68c6b37 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionResponseCrcTest.kt @@ -0,0 +1,163 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.session + +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.Nonce +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.CouldNotParseResponseException +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock + +/** + * [Session.validateCrc] - the O5-only response-envelope CRC check. + * + * Every vector below is real captured traffic, not synthesised, because the point of the test + * is that the CRC is genuinely computable on Omnipod 5 responses. An earlier revision of the + * driver asserted the opposite in a code comment and skipped the check entirely, on the + * strength of Dash traffic that had been mistaken for O5. + */ +class SessionResponseCrcTest { + + private fun session(): Session { + val ids = Ids.forController(Id.fromInt(1), Id.fromInt(2)) + val nonce = Nonce(ByteArray(8), 0) + val sessionKeys = SessionKeys(ck = ByteArray(16), nonce = nonce, msgSequenceNumber = 1) + val enDecrypt = EnDecrypt(AAPSLoggerTest(), nonce, sessionKeys.ck) + return Session(AAPSLoggerTest(), mock(), ids, sessionKeys, enDecrypt) + } + + private fun hex(s: String): ByteArray = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + + /** + * Omnipod 5 pod `002a1c6e`, captured from a Trio installation. Pod-generated responses - + * the direction that matters, since these are what the driver acts on. + */ + private val podResponses = listOf( + "002a1c6e300a1d2803f04000001d83ff83db", + "002a1c6e380a1d1803f06800001d83ff036a", + "002a1c6e000a1d2803f07800001d83ff03eb", + "002a1c6e301802160209020000010c92000000030d0cc8000000000070410258" + ) + + /** Same pod, phone-generated. This driver builds these itself, so they close the loop. */ + private val outgoingMessages = listOf( + "002a1c6e2c030e0100802f", + "002a1c6e34071f05494e532e02818b", + "002a1c6e3c201a0e494e532e010091013840000c000c160e0000007d00dbba00007d00dbba008103" + ) + + /** + * The two envelopes logged either side of a real `MessageError.invalidCrc` incident, where + * five minutes of corrupted comms cost the user a loop cycle and raised a critical + * delivery-uncertain alert. Both are well formed - the corrupt frames never reached the + * log - so they belong with the passing vectors. + */ + private val incidentEnvelopes = listOf( + "002a1c6e08030e010002b6", + "002a1c6e08030e010782a7" + ) + + @Test + fun `real captured O5 pod responses all satisfy the envelope CRC`() { + val session = session() + for (message in podResponses) { + session.validateCrc(hex(message)) + } + } + + @Test + fun `real captured O5 outgoing messages all satisfy the envelope CRC`() { + val session = session() + for (message in outgoingMessages) { + session.validateCrc(hex(message)) + } + } + + @Test + fun `envelopes captured around a real invalidCrc incident are themselves valid`() { + val session = session() + for (message in incidentEnvelopes) { + session.validateCrc(hex(message)) + } + } + + @Test + fun `a single flipped bit anywhere in the envelope is rejected`() { + val session = session() + val original = hex(podResponses.first()) + + for (index in 0 until original.size - 2) { + val corrupted = original.copyOf() + corrupted[index] = (corrupted[index].toInt() xor 0x01).toByte() + assertThrows(CouldNotParseResponseException::class.java) { + session.validateCrc(corrupted) + } + } + } + + @Test + fun `a corrupted CRC field itself is rejected`() { + val session = session() + val corrupted = hex(podResponses.first()) + corrupted[corrupted.size - 1] = (corrupted[corrupted.size - 1].toInt() xor 0x01).toByte() + + assertThrows(CouldNotParseResponseException::class.java) { + session.validateCrc(corrupted) + } + } + + @Test + fun `the failure message reports both the expected and the received CRC`() { + val session = session() + val corrupted = hex(podResponses.first()) + corrupted[corrupted.size - 1] = 0x00 + + val thrown = assertThrows(CouldNotParseResponseException::class.java) { + session.validateCrc(corrupted) + } + assertThat(thrown.message).contains("83db") + assertThat(thrown.message).contains("8300") + } + + /** + * Why [Session.parseResponse] gates this check on an O5 connection. These are Dash + * responses (pod `1749dbcb`, `podTypeValue: 4` in the Loop Report they came from) and they + * satisfy no CRC this driver can compute - no initial value in the entire 16-bit space and + * no byte range reproduces their trailer. Running the check on a Dash connection would + * reject every response the pod sends, which is exactly the regression this test guards. + */ + @Test + fun `Dash pod responses do NOT satisfy this CRC - hence the O5-only gate`() { + val session = session() + val dashResponses = listOf( + "1749dbcb3c0a1d180403700000472fff0310", + "1749dbcb040a1d280403000000472fff83db", + "1749dbcb080a1d280403000000473bff8219", + "1749dbcb0c0a1d280403800000474bff03c9", + "1749dbcb100a1d2804038000004757ff0192" + ) + for (message in dashResponses) { + assertThrows(CouldNotParseResponseException::class.java) { + session.validateCrc(hex(message)) + } + } + } + + /** Dash *outgoing* messages do satisfy it - this driver wrote them with the same function. */ + @Test + fun `Dash outgoing messages satisfy the CRC even though its responses do not`() { + val session = session() + val dashRequests = listOf( + "1749dbcb38071f05494e532e028173", + "1749dbcb04030e010782e2", + "1749dbcb08030e010700e7" + ) + for (message in dashRequests) { + session.validateCrc(hex(message)) + } + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionResponseValidationTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionResponseValidationTest.kt new file mode 100644 index 000000000000..36910c13f478 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/session/SessionResponseValidationTest.kt @@ -0,0 +1,112 @@ +package app.aaps.pump.omnipod.common.bledriver.comm.session + +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.Nonce +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.CouldNotParseResponseException +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import java.nio.ByteBuffer + +/** + * [Session.validateSequenceNumber] - the O5-only response-envelope sequence check that runs + * alongside `Session.validateCrc` (covered separately in [SessionResponseCrcTest]). + * + * The rule under test is that a pod's response carries the request's sequence number **plus + * one**, which is pinned below against real request/response pairs captured from a working + * Loop/Trio installation's Device Communication Log. An earlier revision compared against the + * request's own sequence number and would have rejected every response a real pod ever sent. + * + * Note these particular pairs are **Dash** traffic (`podTypeValue: 4` in the source report) - + * the sequence rule is identical on both pod generations, unlike the CRC. + */ +class SessionResponseValidationTest { + + private fun session(): Session { + val ids = Ids.forController(Id.fromInt(1), Id.fromInt(2)) + val nonce = Nonce(ByteArray(8), 0) + val sessionKeys = SessionKeys(ck = ByteArray(16), nonce = nonce, msgSequenceNumber = 1) + val enDecrypt = EnDecrypt(AAPSLoggerTest(), nonce, sessionKeys.ck) + return Session(AAPSLoggerTest(), mock(), ids, sessionKeys, enDecrypt) + } + + private fun hex(s: String): ByteArray = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() } + + /** Bytes 4..6 of an inner Omnipod message: uniqueId(4) + length/sequence(2) + body + CRC(2). */ + private fun lengthAndSequenceBytesOf(message: String): ByteArray = hex(message).copyOfRange(4, 6) + + private fun sequenceNumberOf(message: String): Short = + (((ByteBuffer.wrap(lengthAndSequenceBytesOf(message)).short.toInt() shr 10) and 0x0f)).toShort() + + /** + * Real Omnipod 5 traffic (pod address 1749dbcb), request paired with the response it drew. + * Includes a request at sequence 14 so the pairing is pinned near the 4-bit wrap, not only + * for small numbers. + */ + private val capturedPairs = listOf( + "1749dbcb38071f05494e532e028173" to "1749dbcb3c0a1d180403700000472fff0310", + "1749dbcb00201a0e494e532e01008501384000060006160e0000003c01c9c380003c01c9c380010c" to + "1749dbcb040a1d280403000000472fff83db", + "1749dbcb04030e010782e2" to "1749dbcb080a1d280403000000473bff8219", + "1749dbcb08030e010700e7" to "1749dbcb0c0a1d280403800000474bff03c9", + "1749dbcb0c030e010781ec" to "1749dbcb100a1d2804038000004757ff0192" + ) + + @Test + fun `real captured O5 traffic - every response carries the request sequence number plus one`() { + val session = session() + for ((request, response) in capturedPairs) { + val sent = sequenceNumberOf(request) + assertThat(sequenceNumberOf(response).toInt()).isEqualTo((sent.toInt() + 1) and 0x0f) + session.validateSequenceNumber(lengthAndSequenceBytesOf(response), sent) + } + } + + @Test + fun `a response echoing the request's own sequence number is rejected`() { + val session = session() + val (request, _) = capturedPairs.first() + val sent = sequenceNumberOf(request) + + assertThrows(CouldNotParseResponseException::class.java) { + session.validateSequenceNumber(lengthAndSequenceBytesOf(request), sent) + } + } + + @Test + fun `sequence numbers wrap at 4 bits - a request at 15 expects a response at 0`() { + val session = session() + val response = packedLengthAndSequenceNumber(sequenceNumber = 0, length = 10, multiCommandFlag = false) + + session.validateSequenceNumber(response, sentSequenceNumber = 15) + } + + @Test + fun `the length and multiCommandFlag bits sharing the field are ignored`() { + val session = session() + val response = packedLengthAndSequenceNumber(sequenceNumber = 4, length = 1000, multiCommandFlag = true) + + session.validateSequenceNumber(response, sentSequenceNumber = 3) + } + + @Test + fun `a genuinely out-of-order response is rejected`() { + val session = session() + val response = packedLengthAndSequenceNumber(sequenceNumber = 9, length = 10, multiCommandFlag = false) + + assertThrows(CouldNotParseResponseException::class.java) { + session.validateSequenceNumber(response, sentSequenceNumber = 3) + } + } + + /** Mirrors HeaderEnabledCommand.encodeHeader()'s second Short, minus the leading uniqueId. */ + private fun packedLengthAndSequenceNumber(sequenceNumber: Short, length: Short, multiCommandFlag: Boolean): ByteArray { + val packed = (sequenceNumber.toInt() and 0x0f shl 10 or length.toInt() or ((if (multiCommandFlag) 1 else 0) shl 15)).toShort() + return ByteBuffer.allocate(2).putShort(packed).array() + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/CommandEncodingTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/CommandEncodingTest.kt new file mode 100644 index 000000000000..2f5a2766375f --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/CommandEncodingTest.kt @@ -0,0 +1,365 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.command + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertConfiguration +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertTrigger +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepRepetitionType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepType +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType +import app.aaps.pump.omnipod.common.bledriver.pod.util.AlertUtil +import app.aaps.pump.omnipod.common.bledriver.pod.util.MessageUtil +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.util.EnumSet + +/** + * Byte-level encoding checks for a handful of read-only / non-dosing commands, each + * verified against the real, production [MessageUtil.createCrc] rather than a + * re-implementation of it. These commands ([GetVersionCommand], [GetStatusCommand], + * [SilenceAlertsCommand]) are built on [app.aaps.pump.omnipod.common.bledriver.pod.command + * .base.HeaderEnabledCommand] / [app.aaps.pump.omnipod.common.bledriver.pod.command.base + * .NonceEnabledCommand], which have no pod-type-specific assumptions - these tests exist + * to pin that down with concrete byte checks, not just an architectural argument. + * + * Deliberately excludes anything with dosing-affecting logic (bolus, basal, temp basal) - + * that's out of scope for this test's purpose. + */ +class CommandEncodingTest : TestBase() { + + + @Test + fun `GetVersionCommand encodes to the documented 14-byte layout`() { + val uniqueId = 0x12345678 + val sequenceNumber: Short = 5 + val cmd = GetVersionCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(14) + + val headerUniqueId = readInt(encoded, 0) + assertThat(headerUniqueId).isEqualTo(uniqueId) + + val bodyUniqueId = readInt(encoded, 8) + assertThat(bodyUniqueId).isEqualTo(uniqueId) + + assertCrcMatches(encoded, crcOffset = 12) + } + + @Test + fun `GetVersionCommand with different sequence numbers produces different encodings`() { + val uniqueId = 0x12345678 + val cmd1 = GetVersionCommand.Builder().setUniqueId(uniqueId).setSequenceNumber(1).build() + val cmd2 = GetVersionCommand.Builder().setUniqueId(uniqueId).setSequenceNumber(2).build() + + assertThat(cmd1.encoded).isNotEqualTo(cmd2.encoded) + } + + + @Test + fun `GetStatusCommand encodes to the documented 11-byte layout`() { + val uniqueId = 0x0A0B0C0D + val sequenceNumber: Short = 2 + + val cmd = GetStatusCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(11) + assertThat(encoded[8]).isEqualTo(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE.value) + + assertCrcMatches(encoded, crcOffset = 9) + } + + @Test + fun `GetStatusCommand reflects a different requested status page in its encoding`() { + val uniqueId = 0x0A0B0C0D + val sequenceNumber: Short = 2 + + val defaultPage = GetStatusCommand.Builder() + .setUniqueId(uniqueId).setSequenceNumber(sequenceNumber) + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) + .build() + val alarmPage = GetStatusCommand.Builder() + .setUniqueId(uniqueId).setSequenceNumber(sequenceNumber) + .setStatusResponseType(ResponseType.StatusResponseType.ALARM_STATUS) + .build() + + assertThat(defaultPage.encoded).isNotEqualTo(alarmPage.encoded) + assertThat(alarmPage.encoded[8]).isEqualTo(ResponseType.StatusResponseType.ALARM_STATUS.value) + } + + + @Test + fun `SilenceAlertsCommand encodes to the documented 15-byte layout`() { + val uniqueId = 0x2233AABB.toInt() + val sequenceNumber: Short = 9 + val nonce = 0x0A0B0C0D + val alertTypes = EnumSet.of(AlertType.LOW_RESERVOIR, AlertType.SUSPEND_ENDED) + + val cmd = SilenceAlertsCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .setNonce(nonce) + .setAlertTypes(alertTypes) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(15) + + val encodedNonce = readInt(encoded, 8) + assertThat(encodedNonce).isEqualTo(nonce) + + assertCrcMatches(encoded, crcOffset = 13) + } + + @Test + fun `SilenceAlertsCommand alert byte round-trips through AlertUtil`() { + val alertTypes = EnumSet.of(AlertType.LOW_RESERVOIR, AlertType.SUSPEND_ENDED) + val cmd = SilenceAlertsCommand.Builder() + .setUniqueId(0x2233AABB.toInt()) + .setSequenceNumber(9) + .setNonce(0x0A0B0C0D) + .setAlertTypes(alertTypes) + .build() + + val decoded = AlertUtil.decodeAlertSet(cmd.encoded[12]) + + assertThat(decoded).isEqualTo(alertTypes) + } + + @Test + fun `SilenceAlertsCommand with an empty alert set encodes to zero`() { + val cmd = SilenceAlertsCommand.Builder() + .setUniqueId(0x2233AABB.toInt()) + .setSequenceNumber(9) + .setNonce(0x0A0B0C0D) + .setAlertTypes(EnumSet.noneOf(AlertType::class.java)) + .build() + + assertThat(cmd.encoded[12]).isEqualTo(0.toByte()) + assertThat(AlertUtil.decodeAlertSet(cmd.encoded[12])).isEmpty() + } + + + @Test + fun `DeactivateCommand encodes to the documented 14-byte layout`() { + val uniqueId = 0x33445566.toInt() + val sequenceNumber: Short = 3 + val nonce = 0x0F0E0D0C + + val cmd = DeactivateCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .setNonce(nonce) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(14) + assertThat(encoded[6]).isEqualTo(0x1c.toByte()) + + val encodedNonce = readInt(encoded, 8) + assertThat(encodedNonce).isEqualTo(nonce) + + assertCrcMatches(encoded, crcOffset = 12) + } + + @Test + fun `DeactivateCommand with different nonces produces different encodings`() { + val uniqueId = 0x33445566.toInt() + val cmd1 = DeactivateCommand.Builder().setUniqueId(uniqueId).setSequenceNumber(1).setNonce(100).build() + val cmd2 = DeactivateCommand.Builder().setUniqueId(uniqueId).setSequenceNumber(1).setNonce(101).build() + + assertThat(cmd1.encoded).isNotEqualTo(cmd2.encoded) + } + + + @Test + fun `StopDeliveryCommand encodes ALL plus LONG_SINGLE_BEEP to the documented 15-byte layout`() { + val uniqueId = 0x11223344.toInt() + val sequenceNumber: Short = 4 + val nonce = 0x0A0B0C0D + + val cmd = StopDeliveryCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .setNonce(nonce) + .setDeliveryType(StopDeliveryCommand.DeliveryType.ALL) + .setBeepType(BeepType.LONG_SINGLE_BEEP) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(15) + assertThat(encoded[6]).isEqualTo(0x1f.toByte()) + + val encodedNonce = readInt(encoded, 8) + assertThat(encodedNonce).isEqualTo(nonce) + + assertThat(encoded[12]).isEqualTo(0x67.toByte()) + + assertCrcMatches(encoded, crcOffset = 13) + } + + @Test + fun `StopDeliveryCommand DeliveryType BASAL produces a different, correctly-masked encoding`() { + val uniqueId = 0x11223344.toInt() + val nonce = 0x0A0B0C0D + + val allCmd = StopDeliveryCommand.Builder() + .setUniqueId(uniqueId).setSequenceNumber(4).setNonce(nonce) + .setDeliveryType(StopDeliveryCommand.DeliveryType.ALL).setBeepType(BeepType.LONG_SINGLE_BEEP) + .build() + val basalOnlyCmd = StopDeliveryCommand.Builder() + .setUniqueId(uniqueId).setSequenceNumber(4).setNonce(nonce) + .setDeliveryType(StopDeliveryCommand.DeliveryType.BASAL).setBeepType(BeepType.SILENT) + .build() + + assertThat(basalOnlyCmd.encoded[12]).isEqualTo(0x01.toByte()) + assertThat(allCmd.encoded).isNotEqualTo(basalOnlyCmd.encoded) + } + + + @Test + fun `ProgramAlertsCommand encodes a single AlertConfiguration to the documented 20-byte layout`() { + val uniqueId = 0x22334455.toInt() + val sequenceNumber: Short = 6 + val nonce = 0x01020304 + + val alertConfig = AlertConfiguration( + type = AlertType.SUSPEND_ENDED, + enabled = true, + durationInMinutes = 0, + autoOff = false, + trigger = AlertTrigger.TimerTrigger(20), + beepType = BeepType.FOUR_TIMES_BIP_BEEP, + beepRepetition = BeepRepetitionType.EVERY_MINUTE_AND_EVERY_15_MIN + ) + + val cmd = ProgramAlertsCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .setNonce(nonce) + .setAlertConfigurations(listOf(alertConfig)) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(20) + assertThat(encoded[6]).isEqualTo(0x19.toByte()) + assertThat(encoded[7]).isEqualTo(10.toByte()) + + assertThat(readInt(encoded, 8)).isEqualTo(nonce) + + assertThat(encoded[12]).isEqualTo(0x68.toByte()) + assertThat(encoded[13]).isEqualTo(0.toByte()) + assertThat(encoded[14]).isEqualTo(0.toByte()) + assertThat(encoded[15]).isEqualTo(20.toByte()) + assertThat(encoded[16]).isEqualTo(BeepRepetitionType.EVERY_MINUTE_AND_EVERY_15_MIN.value) + assertThat(encoded[17]).isEqualTo(BeepType.FOUR_TIMES_BIP_BEEP.value) + + assertCrcMatches(encoded, crcOffset = 18) + } + + + @Test + fun `SuspendDeliveryCommand composes StopDelivery ALL plus embedded ProgramAlerts correctly`() { + val uniqueId = 0x22334455.toInt() + val sequenceNumber: Short = 6 + val nonce = 0x01020304 + + val cmd = SuspendDeliveryCommand.Builder() + .setUniqueId(uniqueId) + .setSequenceNumber(sequenceNumber) + .setNonce(nonce) + .setBeepType(BeepType.LONG_SINGLE_BEEP) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(27) + assertThat(encoded[6]).isEqualTo(0x1f.toByte()) + + assertThat(readInt(encoded, 8)).isEqualTo(nonce) + + assertThat(encoded[12]).isEqualTo(0x67.toByte()) + + assertThat(encoded[13]).isEqualTo(0x19.toByte()) + assertThat(encoded[14]).isEqualTo(10.toByte()) + assertThat(readInt(encoded, 15)).isEqualTo(nonce) + assertThat(encoded[19]).isEqualTo(0x68.toByte()) + + assertCrcMatches(encoded, crcOffset = 25) + } + + + @Test + fun `SetUniqueIdCommand encodes to the documented 29-byte layout`() { + val targetUniqueId = 0x12345678 + val sequenceNumber: Short = 7 + val lotNumber = 123456 + val podSequenceNumber = 654321 + + val cal = java.util.Calendar.getInstance() + cal.set(2024, java.util.Calendar.MARCH, 15, 10, 30, 0) + + val cmd = SetUniqueIdCommand.Builder() + .setUniqueId(targetUniqueId) + .setSequenceNumber(sequenceNumber) + .setLotNumber(lotNumber) + .setPodSequenceNumber(podSequenceNumber) + .setInitializationTime(cal.time) + .build() + + val encoded = cmd.encoded + + assertThat(encoded.size).isEqualTo(29) + + assertThat(readInt(encoded, 0)).isEqualTo(-1) + + assertThat(encoded[6]).isEqualTo(0x03.toByte()) + + assertThat(readInt(encoded, 8)).isEqualTo(targetUniqueId) + + assertThat(encoded[12]).isEqualTo(0x14.toByte()) + assertThat(encoded[13]).isEqualTo(0x04.toByte()) + + assertThat(encoded[14]).isEqualTo(3.toByte()) + assertThat(encoded[15]).isEqualTo(15.toByte()) + assertThat(encoded[16]).isEqualTo(24.toByte()) + assertThat(encoded[17]).isEqualTo(10.toByte()) + assertThat(encoded[18]).isEqualTo(30.toByte()) + + assertThat(readInt(encoded, 19)).isEqualTo(lotNumber) + assertThat(readInt(encoded, 23)).isEqualTo(podSequenceNumber) + + assertCrcMatches(encoded, crcOffset = 27) + } + + + private fun readInt(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) + + /** Recomputes the CRC over everything before [crcOffset] using the real, production + * [MessageUtil.createCrc] and checks it matches the two CRC bytes at [crcOffset]. */ + private fun assertCrcMatches(encoded: ByteArray, crcOffset: Int) { + val withoutCrc = encoded.copyOfRange(0, crcOffset) + val expectedCrc = MessageUtil.createCrc(withoutCrc) + val embeddedCrc = (((encoded[crcOffset].toInt() and 0xFF) shl 8) or + (encoded[crcOffset + 1].toInt() and 0xFF)).toShort() + assertThat(embeddedCrc).isEqualTo(expectedCrc) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtilTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtilTest.kt new file mode 100644 index 000000000000..5b0860f7f0af --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/command/insulin/program/util/ProgramBasalUtilTest.kt @@ -0,0 +1,22 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.command.insulin.program.util + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class ProgramBasalUtilTest { + + @Test + fun `mapTenthPulsesPerSlotToLongInsulinProgramElements advances startSlotIndex by the finished element's slot count`() { + val tenthPulsesPerSlot = shortArrayOf(10, 10, 10, 20, 20, 30, 30, 30, 30) + + val elements = ProgramBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) + + assertThat(elements).hasSize(3) + assertThat(elements[0].startSlotIndex).isEqualTo(0) + assertThat(elements[0].numberOfSlots).isEqualTo(3) + assertThat(elements[1].startSlotIndex).isEqualTo(3) + assertThat(elements[1].numberOfSlots).isEqualTo(2) + assertThat(elements[2].startSlotIndex).isEqualTo(5) + assertThat(elements[2].numberOfSlots).isEqualTo(4) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/AlertConfigurationTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/AlertConfigurationTest.kt new file mode 100644 index 000000000000..b81abc271955 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/AlertConfigurationTest.kt @@ -0,0 +1,71 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.definition + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * [AlertConfiguration]'s 6-byte bit-packed encoding, verified by hand against the field + * layout in [AlertConfiguration.encoded] - see this file's two test cases for the full + * worked byte-by-byte derivation (one per [AlertTrigger] variant). + */ +class AlertConfigurationTest { + + @Test + fun `encodes a TimerTrigger alert with all flag bits set`() { + val config = AlertConfiguration( + type = AlertType.LOW_RESERVOIR, + enabled = true, + durationInMinutes = 300, + autoOff = true, + trigger = AlertTrigger.TimerTrigger(offsetInMinutes = 500), + beepType = BeepType.FOUR_TIMES_BIP_BEEP, + beepRepetition = BeepRepetitionType.XXX + ) + + assertThat(config.encoded).isEqualTo( + byteArrayOf(0x4B, 0x2C, 0x01, 0xF4.toByte(), 0x01, 0x02) + ) + } + + @Test + fun `encodes a ReservoirVolumeTrigger alert with all flag bits clear`() { + val config = AlertConfiguration( + type = AlertType.EXPIRATION, + enabled = false, + durationInMinutes = 0, + autoOff = false, + trigger = AlertTrigger.ReservoirVolumeTrigger(thresholdInMicroLiters = 1000), + beepType = BeepType.SILENT, + beepRepetition = BeepRepetitionType.EVERY_MINUTE_AND_EVERY_15_MIN + ) + + assertThat(config.encoded).isEqualTo( + byteArrayOf(0x74, 0x00, 0x03, 0xE8.toByte(), 0x03, 0x00) + ) + } + + @Test + fun `the reservoir-trigger flag bit distinguishes trigger type independent of other flags`() { + val timerBased = AlertConfiguration( + type = AlertType.AUTO_OFF, + enabled = false, + durationInMinutes = 0, + autoOff = false, + trigger = AlertTrigger.TimerTrigger(offsetInMinutes = 0), + beepType = BeepType.SILENT, + beepRepetition = BeepRepetitionType.XXX + ) + val reservoirBased = AlertConfiguration( + type = AlertType.AUTO_OFF, + enabled = false, + durationInMinutes = 0, + autoOff = false, + trigger = AlertTrigger.ReservoirVolumeTrigger(thresholdInMicroLiters = 0), + beepType = BeepType.SILENT, + beepRepetition = BeepRepetitionType.XXX + ) + + assertThat(timerBased.encoded[0]).isEqualTo(0x00.toByte()) + assertThat(reservoirBased.encoded[0]).isEqualTo(0x04.toByte()) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgramTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgramTest.kt new file mode 100644 index 000000000000..ec45d529541d --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/BasalProgramTest.kt @@ -0,0 +1,146 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.definition + +import com.google.common.truth.Truth.assertThat +import com.google.gson.Gson +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import java.util.Calendar + +/** + * [BasalProgram] - dosing-schedule encode/query logic. [rateAt] reads the local default + * timezone via `Calendar.getInstance()`, so test timestamps are built the same way (rather + * than hardcoded epoch millis) to stay timezone-independent - see this codebase's own + * O5PodStateManagerExtensionsTest doc comment for the same caution about a previous flaky + * test caused by exactly this pattern. + */ +class BasalProgramTest { + + private fun millisAt(hour: Int, minute: Int): Long { + val calendar = Calendar.getInstance() + calendar.set(Calendar.HOUR_OF_DAY, hour) + calendar.set(Calendar.MINUTE, minute) + calendar.set(Calendar.SECOND, 0) + return calendar.timeInMillis + } + + @Test + fun `rateAt returns the rate of the segment covering that half-hour slot`() { + val program = BasalProgram( + listOf( + BasalProgram.Segment(0, 24, 100), + BasalProgram.Segment(24, 48, 150) + ) + ) + + assertThat(program.rateAt(millisAt(10, 15), null)).isEqualTo(1.0) + assertThat(program.rateAt(millisAt(14, 45), null)).isEqualTo(1.5) + } + + @Test + fun `rateAt treats startSlotIndex as inclusive and endSlotIndex as exclusive`() { + val program = BasalProgram(listOf(BasalProgram.Segment(20, 22, 200))) + + assertThat(program.rateAt(millisAt(10, 0), null)).isEqualTo(2.0) + assertThat(program.rateAt(millisAt(10, 29), null)).isEqualTo(2.0) + assertThat(program.rateAt(millisAt(11, 0), null)).isEqualTo(0.0) + } + + @Test + fun `rateAt returns zero when no segment covers the slot`() { + val program = BasalProgram(listOf(BasalProgram.Segment(0, 10, 100))) + + assertThat(program.rateAt(millisAt(23, 0), null)).isEqualTo(0.0) + } + + @Test + fun `hasZeroUnitSegments is true only when some segment has a zero rate`() { + val withZero = BasalProgram(listOf(BasalProgram.Segment(0, 24, 0), BasalProgram.Segment(24, 48, 100))) + val withoutZero = BasalProgram(listOf(BasalProgram.Segment(0, 48, 50))) + + assertThat(withZero.hasZeroUnitSegments()).isTrue() + assertThat(withoutZero.hasZeroUnitSegments()).isFalse() + } + + @Test + fun `addSegment appends to the segment list`() { + val program = BasalProgram(listOf(BasalProgram.Segment(0, 24, 100))) + + program.addSegment(BasalProgram.Segment(24, 48, 200)) + + assertThat(program.segments).hasSize(2) + assertThat(program.segments[1].basalRateInHundredthUnitsPerHour).isEqualTo(200) + } + + @Test + fun `segments is unmodifiable from the outside`() { + val program = BasalProgram(listOf(BasalProgram.Segment(0, 24, 100))) + + assertThrows(UnsupportedOperationException::class.java) { + program.segments.add(BasalProgram.Segment(24, 48, 200)) + } + } + + @Test + fun `Segment getPulsesPerHour converts hundredth-units-per-hour to pulses using the 0-05U pulse size`() { + val segment = BasalProgram.Segment(0, 48, 100) + + assertThat(segment.getPulsesPerHour()).isEqualTo(20.toShort()) + } + + @Test + fun `Segment getNumberOfSlots is the half-open slot range width`() { + val segment = BasalProgram.Segment(10, 34, 100) + + assertThat(segment.getNumberOfSlots()).isEqualTo(24.toShort()) + } + + @Test + fun `Segment equals and hashCode are structural`() { + val a = BasalProgram.Segment(0, 24, 100) + val b = BasalProgram.Segment(0, 24, 100) + val different = BasalProgram.Segment(0, 24, 150) + + assertThat(a).isEqualTo(b) + assertThat(a.hashCode()).isEqualTo(b.hashCode()) + assertThat(a).isNotEqualTo(different) + } + + /** + * Pins the actual JSON key this class reads/writes, not just that some key round-trips: + * Gson serializes by field name (or `@SerializedName`) and this class's backing field has + * already been renamed once without keeping the annotation in sync, which silently + * dropped a saved basal program for any user who upgraded across that change (the renamed + * field never matched their on-disk "segments" key, so it quietly came back empty). + */ + @Test + fun `segments round-trips through Gson under the "segments" JSON key, surviving a field rename`() { + val program = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + + val json = Gson().toJson(program) + val restoredFromOwnJson = Gson().fromJson(json, BasalProgram::class.java) + val restoredFromOldFormat = Gson().fromJson("""{"segments":[{"startSlotIndex":0,"endSlotIndex":48,"basalRateInHundredthUnitsPerHour":100}]}""", BasalProgram::class.java) + + assertThat(json).contains("\"segments\"") + assertThat(restoredFromOwnJson.segments).isEqualTo(program.segments) + assertThat(restoredFromOldFormat.segments).isEqualTo(program.segments) + } + + @Test + fun `segments self-heals instead of crashing when Gson deserialization bypasses the constructor`() { + val deserialized = Gson().fromJson("{}", BasalProgram::class.java) + + assertThat(deserialized.segments).isEmpty() + assertThat(deserialized.rateAt(millisAt(10, 0), null)).isEqualTo(0.0) + } + + @Test + fun `BasalProgram equals and hashCode compare by segment list`() { + val a = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + val b = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + val different = BasalProgram(listOf(BasalProgram.Segment(0, 48, 200))) + + assertThat(a).isEqualTo(b) + assertThat(a.hashCode()).isEqualTo(b.hashCode()) + assertThat(a).isNotEqualTo(different) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PulseLogEntryTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PulseLogEntryTest.kt new file mode 100644 index 000000000000..b2a64069ed88 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/definition/PulseLogEntryTest.kt @@ -0,0 +1,73 @@ +package app.aaps.pump.omnipod.common.bledriver.pod.definition + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +/** + * [PulseLogEntry.decode] against the openaps/openomni wiki's documented bit layout - see + * [PulseLogEntry]'s class doc for the source and the manual bit-by-bit verification this + * golden value was checked against. + */ +class PulseLogEntryTest { + + @Test + fun `decodes the openomni wiki's own worked example`() { + val entry = PulseLogEntry.decode(0x51213E00.toInt()) + + assertThat(entry.encoder).isEqualTo(20) + assertThat(entry.load2Active).isTrue() + assertThat(entry.pulseMode).isEqualTo(PulseLogEntryType.BASAL) + assertThat(entry.lowReservoir).isFalse() + assertThat(entry.immediateBolusTick).isEqualTo(0) + assertThat(entry.loadCountVal).isEqualTo(125) + assertThat(entry.lastComparatorRead).isFalse() + assertThat(entry.faultFlag).isFalse() + assertThat(entry.lastEncoderValue).isEqualTo(0) + } + + @Test + fun `decodes a synthetic entry exercising every field`() { + val entry = PulseLogEntry.decode(0x147C96FB.toInt()) + + assertThat(entry.encoder).isEqualTo(5) + assertThat(entry.load2Active).isFalse() + assertThat(entry.pulseMode).isEqualTo(PulseLogEntryType.BOLUS) + assertThat(entry.lowReservoir).isTrue() + assertThat(entry.immediateBolusTick).isEqualTo(6) + assertThat(entry.loadCountVal).isEqualTo(300) + assertThat(entry.lastComparatorRead).isTrue() + assertThat(entry.faultFlag).isTrue() + assertThat(entry.lastEncoderValue).isEqualTo(-5) + } + + @Test + fun `pulseMode covers every documented mode`() { + assertThat(PulseLogEntry.decode(0x00000000.toInt()).pulseMode).isEqualTo(PulseLogEntryType.NONE) + assertThat(PulseLogEntry.decode(0x00200000.toInt()).pulseMode).isEqualTo(PulseLogEntryType.BASAL) + assertThat(PulseLogEntry.decode(0x00400000.toInt()).pulseMode).isEqualTo(PulseLogEntryType.TEMP_BASAL) + assertThat(PulseLogEntry.decode(0x00600000.toInt()).pulseMode).isEqualTo(PulseLogEntryType.BOLUS) + assertThat(PulseLogEntry.decode(0x00800000.toInt()).pulseMode).isEqualTo(PulseLogEntryType.EXTENDED_BOLUS) + } + + @Test + fun `pulseMode falls back to UNKNOWN for undefined raw values`() { + assertThat(PulseLogEntry.decode(0x00E00000.toInt()).pulseMode).isEqualTo(PulseLogEntryType.UNKNOWN) + } + + @Test + fun `lastEncoderValue sign-extends the 6-bit field correctly`() { + assertThat(PulseLogEntry.decode(0x00000000.toInt()).lastEncoderValue).isEqualTo(0) + assertThat(PulseLogEntry.decode(0x0000001F.toInt()).lastEncoderValue).isEqualTo(31) + assertThat(PulseLogEntry.decode(0x00000020.toInt()).lastEncoderValue).isEqualTo(-32) + assertThat(PulseLogEntry.decode(0x0000003F.toInt()).lastEncoderValue).isEqualTo(-1) + } + + @Test + fun `decodeAll maps a list of dwords in order`() { + val entries = PulseLogEntry.decodeAll(listOf(0x00000000.toInt(), 0x00600000.toInt())) + + assertThat(entries).hasSize(2) + assertThat(entries[0].pulseMode).isEqualTo(PulseLogEntryType.NONE) + assertThat(entries[1].pulseMode).isEqualTo(PulseLogEntryType.BOLUS) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/NeedsBasalCorrectionTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/NeedsBasalCorrectionTest.kt index 070628a5166e..58497cfe3651 100644 --- a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/NeedsBasalCorrectionTest.kt +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/NeedsBasalCorrectionTest.kt @@ -2,14 +2,19 @@ package app.aaps.pump.omnipod.common.bledriver.pod.state import app.aaps.core.keys.interfaces.Preferences import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram import app.aaps.pump.omnipod.common.bledriver.pod.definition.BolusType import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.util.PodTimeZone import app.aaps.shared.tests.TestBase import com.google.common.truth.Truth.assertThat +import com.google.gson.Gson import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock +import java.util.EnumSet /** * Tests for [OmnipodDashPodStateManagerImpl.needsBasalCorrection]. @@ -177,6 +182,91 @@ class NeedsBasalCorrectionTest : TestBase() { // ---- cooldown expiry ---------------------------------------------------------------------- + @Test + fun `reported zero counts the old rate first and resume does not count the pause twice`() { + val hour = 3_600_000L + val start = 1_700_000_000_000L + sut.confirmTimeZone(PodTimeZone("UTC", 0, start)) + sut.basalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + sut.podState.lastUpdatedSystem = start + sut.podState.basalExpected = 2.0 + sut.tempBasal = OmnipodDashPodStateManager.TempBasal(start, 2.0, 600) + + sut.updateBasalExpected(start + hour) + sut.tempBasal = OmnipodDashPodStateManager.TempBasal(start + hour, 0.0, 4800) + assertThat(sut.podState.basalExpected).isEqualTo(4.0) + sut.podState.deliveryStatus = DeliveryStatus.SUSPENDED + sut.updateBasalExpected(start + 2 * hour) + assertThat(sut.podState.basalExpected).isEqualTo(4.0) + sut.updateBasalExpected(start + 2 * hour) + assertThat(sut.podState.basalExpected).isEqualTo(4.0) + + sut.tempBasal = null + sut.updateBasalExpected(start + 3 * hour) + assertThat(sut.podState.basalExpected).isEqualTo(5.0) + assertThat(sut.lastUpdatedSystem).isEqualTo(start) + assertThat(sut.podState.basalExpectedUpdatedAt).isEqualTo(start + 3 * hour) + } + + @Test + fun `an older reported time does not rewind or reset expected basal`() { + val hour = 3_600_000L + val start = 1_700_000_000_000L + sut.confirmTimeZone(PodTimeZone("UTC", 0, start)) + sut.basalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + sut.podState.lastUpdatedSystem = start + sut.podState.basalExpected = 2.0 + sut.updateBasalExpected(start + hour) + + sut.updateBasalExpected(start + hour / 2) + + assertThat(sut.podState.basalExpected).isEqualTo(3.0) + assertThat(sut.podState.basalExpectedUpdatedAt).isEqualTo(start + hour) + assertThat(sut.lastUpdatedSystem).isEqualTo(start) + } + + @Test + fun `status counts from the basal timestamp and then updates the status timestamp`() { + val hour = 3_600_000L + val start = System.currentTimeMillis() - 2 * hour + sut.confirmTimeZone(PodTimeZone("UTC", 0, start)) + sut.basalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + sut.podState.lastUpdatedSystem = start + sut.podState.basalExpected = 2.0 + sut.updateBasalExpected(start + hour) + sut.tempBasal = OmnipodDashPodStateManager.TempBasal(start + hour, 0.0, 4800) + + sut.updatePodState( + DeliveryStatus.SUSPENDED, PodStatus.RUNNING_ABOVE_MIN_VOLUME, + 40, 1000, 0, 60, EnumSet.noneOf(AlertType::class.java), 0 + ) + + assertThat(sut.podState.basalExpected).isEqualTo(3.0) + assertThat(sut.podState.basalExpectedUpdatedAt).isEqualTo(sut.lastUpdatedSystem) + assertThat(sut.lastUpdatedSystem).isAtLeast(start + 2 * hour) + } + + @Test + fun `old saved state uses the status timestamp and new state preserves the basal timestamp`() { + val gson = Gson() + val hour = 3_600_000L + val start = 1_700_000_000_000L + sut.podState = gson.fromJson( + """{"lastUpdatedSystem":$start,"basalExpected":2.0}""", + OmnipodDashPodStateManagerImpl.PodState::class.java + ) + assertThat(sut.podState.basalExpectedUpdatedAt).isNull() + sut.confirmTimeZone(PodTimeZone("UTC", 0, start)) + sut.basalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + sut.updateBasalExpected(start + hour) + + sut.podState = gson.fromJson(gson.toJson(sut.podState), OmnipodDashPodStateManagerImpl.PodState::class.java) + assertThat(sut.podState.basalExpectedUpdatedAt).isEqualTo(start + hour) + assertThat(sut.lastUpdatedSystem).isEqualTo(start) + sut.updateBasalExpected(start + 2 * hour) + assertThat(sut.podState.basalExpected).isEqualTo(4.0) + } + @Test fun `past cooldown window — does not block correction`() { sut.lastBasalCorrectionTime = System.currentTimeMillis() - 3 * 60_000L // 3 min ago, > 2 min setDrift(10, 0, 0.55) // drift = -0.05 diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/UpdatePodStateBolusTrackingTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/UpdatePodStateBolusTrackingTest.kt index b838f881c17d..45022cce376c 100644 --- a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/UpdatePodStateBolusTrackingTest.kt +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/pod/state/UpdatePodStateBolusTrackingTest.kt @@ -23,7 +23,7 @@ import java.util.TimeZone * - a basal correction is NOT currently delivering ([PodState.basalCorrectionInProgress] == false). * * When a basal correction is in progress its pulses must NOT be counted as bolus pulses, - * otherwise [basalDelivered] (= total − bolus) would decrease and mask the correction + * otherwise `basalDelivered` (= total − bolus) would decrease and mask the correction * against [basalExpected], corrupting the drift calculation. */ class UpdatePodStateBolusTrackingTest : TestBase() { diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/util/OmnipodTimeChangeTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/util/OmnipodTimeChangeTest.kt new file mode 100644 index 000000000000..0b32d3f14f5e --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/util/OmnipodTimeChangeTest.kt @@ -0,0 +1,72 @@ +package app.aaps.pump.omnipod.common.util + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class OmnipodTimeChangeTest { + + @Test + fun `both DST directions need correction`() { + assertThat(OmnipodTimeChange.needsCorrection(3600000, 7200000, false)).isTrue() + assertThat(OmnipodTimeChange.needsCorrection(7200000, 3600000, false)).isTrue() + assertThat(OmnipodTimeChange.needsCorrection(3600000, 3600000, false)).isFalse() + } + + @Test + fun `an unfinished correction needs recovery even when offsets match`() { + assertThat(OmnipodTimeChange.needsCorrection(3600000, 3600000, true)).isTrue() + } + + @Test + fun `unknown offset is not guessed`() { + assertThat(OmnipodTimeChange.needsCorrection(null, 3600000, false)).isFalse() + } + + @Test + fun `automatic correction waits for bolus and unconfirmed commands`() { + assertThat(OmnipodTimeChange.canProgram(true, false, true, false, false)).isFalse() + assertThat(OmnipodTimeChange.canProgram(true, false, false, true, false)).isFalse() + assertThat(OmnipodTimeChange.canProgram(true, false, false, false, false)).isTrue() + } + + @Test + fun `only our own interrupted correction may resume a suspended pod`() { + assertThat(OmnipodTimeChange.canProgram(true, true, false, false, false)).isFalse() + assertThat(OmnipodTimeChange.canProgram(true, true, false, false, true)).isTrue() + assertThat(OmnipodTimeChange.canProgram(false, false, false, false, true)).isFalse() + } + + @Test + fun `attempts are single and retries have a bounded delay`() { + val handler = OmnipodTimeChange() + assertThat(handler.tryStart(0)).isTrue() + assertThat(handler.tryStart(60000)).isFalse() + handler.finish(60000) + assertThat(handler.tryStart(119999)).isFalse() + assertThat(handler.tryStart(120000)).isTrue() + } + + @Test + fun `only the first of a run of failures sounds an alarm`() { + val handler = OmnipodTimeChange() + assertThat(handler.shouldSoundOnFailure()).isTrue() + assertThat(handler.shouldSoundOnFailure()).isFalse() + assertThat(handler.shouldSoundOnFailure()).isFalse() + handler.resetFailureAlert() + assertThat(handler.shouldSoundOnFailure()).isTrue() + } + + @Test + fun `rate follows the fixed pod offset across both DST transitions`() { + val program = BasalProgram(listOf( + BasalProgram.Segment(0, 4, 100), + BasalProgram.Segment(4, 6, 200), + BasalProgram.Segment(6, 48, 300) + )) + val epochAtOneUtc = 3600000L + assertThat(program.rateAt(epochAtOneUtc, 3600000)).isEqualTo(2.0) + assertThat(program.rateAt(epochAtOneUtc, 7200000)).isEqualTo(3.0) + assertThat(program.rateAt(epochAtOneUtc, -3600000)).isEqualTo(1.0) + } +} diff --git a/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/util/PodTimeChangePersistenceTest.kt b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/util/PodTimeChangePersistenceTest.kt new file mode 100644 index 000000000000..e37a437d48d2 --- /dev/null +++ b/pump/omnipod/common/src/test/kotlin/app/aaps/pump/omnipod/common/util/PodTimeChangePersistenceTest.kt @@ -0,0 +1,43 @@ +package app.aaps.pump.omnipod.common.util + +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManagerImpl +import app.aaps.pump.omnipod.common.keys.DashStringNonPreferenceKey +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class PodTimeChangePersistenceTest { + + @Test + fun `Dash restart preserves the in-progress flag and the sent command time zone`() { + val storage = mock() + var json: String? = null + whenever(storage.put(eq(DashStringNonPreferenceKey.PodState), any())).thenAnswer { + json = it.getArgument(1) + Unit + } + whenever(storage.getIfExists(DashStringNonPreferenceKey.PodState)).thenAnswer { json } + whenever(storage.get(DashStringNonPreferenceKey.PodState)).thenAnswer { json ?: "" } + val writer = OmnipodDashPodStateManagerImpl(mock(), mock(), storage) + val oldZone = PodTimeZone("Europe/Amsterdam", 3600000, 1000) + val sentZone = oldZone.copy(offset = 7200000, updatedAt = 2000) + writer.confirmTimeZone(oldZone) + writer.timeChangeInProgress = true + writer.createActiveCommand(7, BasalProgram(listOf(BasalProgram.Segment(0, 48, 100)))).blockingGet() + writer.recordBasalProgramTimeZone(sentZone) + + val reader = OmnipodDashPodStateManagerImpl(mock(), mock(), storage) + assertThat(reader.timeChangeInProgress).isTrue() + assertThat(reader.timeZoneOffset).isEqualTo(oldZone.offset) + assertThat(reader.activeCommand!!.basalTimeZone).isEqualTo(sentZone) + reader.confirmTimeZone(sentZone) + assertThat(reader.timeZoneOffset).isEqualTo(sentZone.offset) + reader.reset() + assertThat(OmnipodDashPodStateManagerImpl(mock(), mock(), storage).timeChangeInProgress).isFalse() + } +} diff --git a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index 7aa569def182..994c4a4051e7 100644 --- a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -10,6 +10,8 @@ import app.aaps.core.data.pump.defs.PumpDescription import app.aaps.core.data.pump.defs.PumpType import app.aaps.core.data.pump.defs.TimeChangeType import app.aaps.core.data.time.T +import app.aaps.core.interfaces.constraints.Constraint +import app.aaps.core.interfaces.constraints.PluginConstraints import app.aaps.core.interfaces.di.PumpDriver import app.aaps.core.interfaces.logging.AAPSLogger import app.aaps.core.interfaces.logging.LTag @@ -73,8 +75,11 @@ import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange import app.aaps.pump.omnipod.common.queue.command.CommandPlayTestBeep import app.aaps.pump.omnipod.common.queue.command.CommandResumeDelivery import app.aaps.pump.omnipod.common.queue.command.CommandSilenceAlerts +import app.aaps.pump.omnipod.common.queue.command.CommandSuspendDelivery import app.aaps.pump.omnipod.common.queue.command.CommandUpdateAlertConfiguration import app.aaps.pump.omnipod.common.util.mapProfileToBasalProgram +import app.aaps.pump.omnipod.common.util.OmnipodTimeChange +import app.aaps.pump.omnipod.common.util.PodTimeZone import app.aaps.pump.omnipod.dash.driver.OmnipodDashManager import app.aaps.pump.omnipod.dash.history.DashHistory import app.aaps.pump.omnipod.common.history.data.BasalValuesRecord @@ -92,6 +97,7 @@ import dev.zacsweers.metro.binding import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Single import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel @@ -152,7 +158,7 @@ class OmnipodDashPumpPlugin( DashStringNonPreferenceKey.entries, aapsLogger, rh, preferences, commandQueue, notificationManager ), - Pump, OmnipodDash, OwnDatabasePlugin { + Pump, OmnipodDash, OwnDatabasePlugin, PluginConstraints { @Volatile var bolusCanceled = false @Volatile var bolusDeliveryInProgress = false @@ -161,6 +167,7 @@ class OmnipodDashPumpPlugin( private var statusChecker: Runnable private var nextPodWarningCheck: Long = 0 @Volatile var stopConnecting: CountDownLatch? = null + private val timeChangeHandler = OmnipodTimeChange() private var scope: CoroutineScope? = null companion object { @@ -177,6 +184,7 @@ class OmnipodDashPumpPlugin( statusChecker = Runnable { refreshStatusOnUnacknowledgedCommands() updatePodWarnings() + scope?.launch { checkTimeChange() } aapsLogger.info(LTag.PUMP, "statusChecker") try { @@ -512,6 +520,7 @@ class OmnipodDashPumpPlugin( handler?.postDelayed(statusChecker, STATUS_CHECK_INTERVAL_MS) val newScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) scope = newScope + newScope.launch { checkTimeChange() } merge( preferences.observe(OmnipodBooleanPreferenceKey.ExpirationReminder).drop(1).map {}, preferences.observe(OmnipodIntPreferenceKey.ExpirationReminderHours).drop(1).map {}, @@ -637,7 +646,7 @@ class OmnipodDashPumpPlugin( override val baseBasalRate: PumpRate get() { val date = System.currentTimeMillis() - val ret = podStateManager.basalProgram?.rateAt(date) ?: 0.0 + val ret = podStateManager.basalProgram?.rateAt(date, podStateManager.timeZoneOffset) ?: 0.0 aapsLogger.info(LTag.PUMP, "baseBasalRate: $ret at $date}") return PumpRate( if (podStateManager.alarmType != null) { @@ -993,6 +1002,12 @@ class OmnipodDashPumpPlugin( pumpType = PumpType.OMNIPOD_DASH, pumpSerial = serialNumber() ) + if (tbrType == PumpSync.TemporaryBasalType.PUMP_SUSPEND) { + podStateManager.updateBasalExpected(historyEntry.createdAt) + podStateManager.tempBasal = OmnipodDashPodStateManager.TempBasal( + historyEntry.createdAt, absoluteRate, durationInMinutes.toShort() + ) + } aapsLogger.debug(LTag.PUMP, "pumpSyncTempBasal: $ret") return ret } @@ -1092,7 +1107,14 @@ class OmnipodDashPumpPlugin( pumpEnactResultProvider().success(false).enacted(false) .comment("Omnipod Dash driver does not support TDD") - override fun canHandleDST(): Boolean = false + override fun canHandleDST(): Boolean = !isInitialized() || podStateManager.timeZoneOffset != null + + override fun isLoopInvocationAllowed(value: Constraint): Constraint { + if (isInitialized() && (timeCorrectionNeeded() || timeChangeHandler.isInProgress())) { + value.set(false, rh.gs(CommonR.string.omnipod_common_loop_waiting_for_time_update), this) + } + return value + } override fun executeCustomCommand(customCommand: CustomCommand): PumpEnactResult { return when (customCommand) { is CommandSilenceAlerts -> @@ -1105,7 +1127,7 @@ class OmnipodDashPumpPlugin( deactivatePod() is CommandHandleTimeChange -> - runBlocking { handleTimeChange() } + runBlocking { handleTimeChange(customCommand.requestedByUser) } is CommandUpdateAlertConfiguration -> updateAlertConfiguration() @@ -1203,8 +1225,20 @@ class OmnipodDashPumpPlugin( return ret } - private suspend fun handleTimeChange(): PumpEnactResult { + private suspend fun handleTimeChange(requestedByUser: Boolean): PumpEnactResult { + if (!requestedByUser) { + getPodStatus().await() + if (!timeCorrectionNeeded() || !canCorrectTime()) { + aapsLogger.info(LTag.PUMP, "Deferring automatic pod time update") + return pumpEnactResultProvider().success(true).enacted(false) + } + } return pumpSync.expectedPumpState().profile?.let { + // Persisted before suspending, so a crash mid-correction can still resume it after restart + // even though the pod now looks suspended. Any active temp basal is lost here, the same way + // the Medtrum driver accepts one may be cancelled by its own time update: the loop sets a + // new one next cycle, this driver does not reconstruct the old one. + podStateManager.timeChangeInProgress = true setNewBasalProfile(it, OmnipodCommandType.SET_TIME) } ?: pumpEnactResultProvider().success(false).enacted(false).comment("No profile active") } @@ -1333,7 +1367,68 @@ class OmnipodDashPumpPlugin( } override suspend fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { - aapsLogger.info(LTag.PUMP, "Ignoring time change because automatic time handling is not implemented. timeChangeType=${timeChangeType.name}") + aapsLogger.info(LTag.PUMP, "Checking pod time after ${timeChangeType.name}") + checkTimeChange() + } + + private fun timeCorrectionNeeded(): Boolean = OmnipodTimeChange.needsCorrection( + podStateManager.timeZoneOffset, PodTimeZone.now().offset, podStateManager.timeChangeInProgress + ) + + private fun canCorrectTime(): Boolean = OmnipodTimeChange.canProgram( + isInitialized(), + podStateManager.isSuspended, + bolusDeliveryInProgress || podStateManager.deliveryStatus?.bolusDeliveringActive() == true || + podStateManager.lastBolus?.deliveryComplete == false, + podStateManager.activeCommand != null, + podStateManager.timeChangeInProgress + ) + + @VisibleForTesting + internal suspend fun checkTimeChange() { + if (!timeCorrectionNeeded()) { + // Also covers a manual command having fixed it outside this polling loop. + timeChangeHandler.resetFailureAlert() + return + } + if (!canCorrectTime() || omnipodManager.isActivationRunning || + commandQueue.isCustomCommandInQueue(CommandHandleTimeChange::class) || + commandQueue.isCustomCommandInQueue(CommandSuspendDelivery::class) || + commandQueue.isCustomCommandInQueue(CommandDeactivatePod::class) || + !timeChangeHandler.tryStart(System.nanoTime() / 1000000) + ) return + try { + val result = commandQueue.customCommand(CommandHandleTimeChange(false)) + if (!result.success) { + notifyTimeChangeFailure(result.comment) + } else if (!timeCorrectionNeeded()) { + timeChangeHandler.resetFailureAlert() + notificationManager.dismiss(NotificationId.PUMP_TIMEZONE_UPDATE_FAILED) + notificationManager.post( + NotificationId.TIME_OR_TIMEZONE_CHANGE, + TextRef.AndroidRes(CommonR.string.omnipod_common_confirmation_time_on_pod_updated), + validMinutes = 60 + ) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + notifyTimeChangeFailure(e.message) + } finally { + timeChangeHandler.finish(System.nanoTime() / 1000000) + } + } + + private fun notifyTimeChangeFailure(reason: String?) { + aapsLogger.error(LTag.PUMP, "Automatic Dash time update failed: $reason") + // Only the first of a run of retries sounds an alarm; repeated retries every minute would + // otherwise alarm continuously while the pod is unreachable. + notificationManager.post( + NotificationId.PUMP_TIMEZONE_UPDATE_FAILED, + TextRef.AndroidRes(CommonR.string.omnipod_common_automatic_time_update_failed), + level = NotificationLevel.IMPORTANT, + sound = if (timeChangeHandler.shouldSoundOnFailure()) AlarmSound.BOLUS_ERROR else null + ) } private fun executeProgrammingCommand( @@ -1382,7 +1477,8 @@ class OmnipodDashPumpPlugin( aapsLogger.debug(LTag.PUMPCOMM, "handling command confirmation: $confirmation ${historyEntry.commandType}") when (historyEntry.commandType) { OmnipodCommandType.CANCEL_TEMPORARY_BASAL -> { - if (confirmation.success) { + // Cancelling a temp basal does not resume delivery; keep the reported zero basal while suspended. + if (confirmation.success && !podStateManager.isSuspended) { val ret = pumpSync.syncStopTemporaryBasalWithPumpId( historyEntry.createdAt, historyEntry.pumpId(), @@ -1405,6 +1501,7 @@ class OmnipodDashPumpPlugin( // We can't invalidate this command, // and this is why it is pumpSync-ed at this point if (confirmation.success) { + confirmBasalProgramTime(command) pumpSync.syncStopTemporaryBasalWithPumpId( historyEntry.createdAt, historyEntry.pumpId(), @@ -1428,6 +1525,7 @@ class OmnipodDashPumpPlugin( OmnipodCommandType.SET_BASAL_PROFILE, OmnipodCommandType.SET_TIME -> { if (confirmation.success) { + confirmBasalProgramTime(command) podStateManager.basalProgram = command.basalProgram if (podStateManager.basalProgram == null) { aapsLogger.warn(LTag.PUMP, "Saving null basal profile") @@ -1442,6 +1540,8 @@ class OmnipodDashPumpPlugin( PumpType.OMNIPOD_DASH, serialNumber() ) + // The confirmed basal program resumes delivery, so clear the zero basal kept during suspension. + podStateManager.tempBasal = null notificationManager.dismiss(NotificationId.OMNIPOD_POD_SUSPENDED) notificationManager.dismiss(NotificationId.FAILED_UPDATE_PROFILE) notificationManager.dismiss(NotificationId.OMNIPOD_TBR_ALERTS) @@ -1481,7 +1581,6 @@ class OmnipodDashPumpPlugin( PumpType.OMNIPOD_DASH, serialNumber() ) - } else { podStateManager.tempBasal = null } } @@ -1557,6 +1656,11 @@ class OmnipodDashPumpPlugin( } } + private fun confirmBasalProgramTime(command: OmnipodDashPodStateManager.ActiveCommand) { + command.basalTimeZone?.let { podStateManager.confirmTimeZone(it) } ?: podStateManager.updateTimeZone() + podStateManager.timeChangeInProgress = false + } + private fun verifyPumpState(): Completable = rxCompletable(Dispatchers.IO) { val expectedState = pumpSync.expectedPumpState() aapsLogger.debug(LTag.PUMP, "verifyPumpState, AAPS: ${expectedState.temporaryBasal} Pump: ${podStateManager.deliveryStatus}") diff --git a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 5425bed32a76..f15cecaa3318 100644 --- a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -40,6 +40,7 @@ import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManager +import app.aaps.pump.omnipod.common.util.PodTimeZone import dev.zacsweers.metro.AppScope import dev.zacsweers.metro.ContributesBinding import dev.zacsweers.metro.Inject @@ -221,6 +222,8 @@ class OmnipodDashManagerImpl( private fun observeSendProgramBasalCommand(basalProgram: BasalProgram, hasBasalBeepEnabled: Boolean): Observable { return Observable.defer { val currentTime = Date() + val timeZone = PodTimeZone.now(currentTime.time) + podStateManager.recordBasalProgramTimeZone(timeZone) logger.debug(LTag.PUMPCOMM, "Programming basal. currentTime={}, basalProgram={}", currentTime, basalProgram) bleManager.sendCommand( ProgramBasalCommand.Builder() @@ -232,9 +235,10 @@ class OmnipodDashManagerImpl( .setCurrentTime(currentTime) .build(), DefaultStatusResponse::class - ) - }.doOnComplete { - podStateManager.updateTimeZone() + ).doOnComplete { + // Activation has no active command; other programs record the zone on confirmation. + if (podStateManager.activeCommand == null) podStateManager.confirmTimeZone(timeZone) + } } } diff --git a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/DashOverviewViewModel.kt b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/DashOverviewViewModel.kt index 47496bddd2bd..85f3a34f25bd 100644 --- a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/DashOverviewViewModel.kt +++ b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/DashOverviewViewModel.kt @@ -40,7 +40,6 @@ import app.aaps.pump.omnipod.common.EventOmnipodDashPumpValuesChanged import app.aaps.pump.omnipod.common.OMNIPOD_DURATION_LABELS import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType -import app.aaps.pump.omnipod.common.bledriver.pod.definition.PdmFaultCategory import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManager import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange @@ -270,7 +269,7 @@ class DashOverviewViewModel( // Base basal rate val basalText = if (podStateManager.basalProgram != null && !podStateManager.isSuspended) { ch.basalRateString( - rate = PumpRate(omnipodDashPumpPlugin.model().determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(System.currentTimeMillis()))), + rate = PumpRate(omnipodDashPumpPlugin.model().determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(System.currentTimeMillis(), podStateManager.timeZoneOffset))), isAbsolute = true ) } else PLACEHOLDER @@ -312,19 +311,7 @@ class DashOverviewViewModel( // the Ref code (see AlarmType.pdmFaultCategory). podStateManager.alarmType?.pdmFaultCategory?.let { category -> podStateManager.pdmRef?.let { ref -> - val (headerRes, textRes) = when (category) { - PdmFaultCategory.RESERVOIR_EMPTY -> CommonR.string.omnipod_common_pdm_notification_header_reservoir_empty to - CommonR.string.omnipod_common_pdm_notification_text_reservoir_empty - PdmFaultCategory.AUTO_OFF -> CommonR.string.omnipod_common_pdm_notification_header_auto_off to - CommonR.string.omnipod_common_pdm_notification_text_auto_off - PdmFaultCategory.POD_EXPIRED -> CommonR.string.omnipod_common_pdm_notification_header_pod_expired to - CommonR.string.omnipod_common_pdm_notification_text_pod_expired - PdmFaultCategory.OCCLUDED -> CommonR.string.omnipod_common_pdm_notification_header_occluded to - CommonR.string.omnipod_common_pdm_notification_text_occluded - PdmFaultCategory.POD_ERROR -> CommonR.string.omnipod_common_pdm_notification_header_pod_error to - CommonR.string.omnipod_common_pdm_notification_text_pod_error - } - val value = rh.gs(headerRes) + "\n" + rh.gs(textRes) + "\n\n" + rh.gs(CommonR.string.omnipod_common_pdm_ref, ref) + val value = category.notificationText(rh, ref) add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_pdm_notification_label), value = value)) } } diff --git a/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/PodFaultText.kt b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/PodFaultText.kt new file mode 100644 index 000000000000..bc81b1997aaf --- /dev/null +++ b/pump/omnipod/dash/src/main/kotlin/app/aaps/pump/omnipod/dash/ui/compose/PodFaultText.kt @@ -0,0 +1,18 @@ +package app.aaps.pump.omnipod.dash.ui.compose + +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PdmFaultCategory +import app.aaps.pump.omnipod.dash.R +import app.aaps.pump.omnipod.common.R as CommonR + +/** Dash PDM wording for the fault notification. */ +fun PdmFaultCategory.notificationText(rh: ResourceHelper, ref: String): String { + val templateRes = when (this) { + PdmFaultCategory.RESERVOIR_EMPTY -> R.string.omnipod_dash_pdm_notification_reservoir_empty + PdmFaultCategory.AUTO_OFF -> R.string.omnipod_dash_pdm_notification_auto_off + PdmFaultCategory.POD_EXPIRED -> R.string.omnipod_dash_pdm_notification_pod_expired + PdmFaultCategory.OCCLUDED -> R.string.omnipod_dash_pdm_notification_occluded + PdmFaultCategory.POD_ERROR -> R.string.omnipod_dash_pdm_notification_pod_error + } + return rh.gs(templateRes) + "\n\n" + rh.gs(CommonR.string.omnipod_common_pdm_ref, ref) +} diff --git a/pump/omnipod/dash/src/main/res/values/strings.xml b/pump/omnipod/dash/src/main/res/values/strings.xml index c57623ac3393..d3940fd79389 100644 --- a/pump/omnipod/dash/src/main/res/values/strings.xml +++ b/pump/omnipod/dash/src/main/res/values/strings.xml @@ -2,7 +2,7 @@ Omnipod Dash - Pump integration for Omnipod Dash (the new, Bluetooth-enabled model with a blue needle cap). + Pump integration for Omnipod Dash (Bluetooth-enabled model with a blue needle cap). Bluetooth Address @@ -10,6 +10,16 @@ Connection quality Delivery Status + + + Empty Reservoir\nInsulin delivery stopped.\nChange Pod now. + Auto-Off\nInsulin delivery stopped.\nYour PDM and Pod have not communicated in the last 4 hours. To resume insulin delivery, change Pod now. + Pod Expired\nInsulin delivery stopped.\nChange Pod now. + Occlusion Detected\nInsulin delivery stopped.\nChange Pod now.\nCheck your BG + Pod error\nInsulin delivery stopped.\nChange Pod now. + Fill a new Pod with enough insulin for 3 days.\n\nListen for two beeps from the Pod during the filling process. These indicate that the minimum amount of 80U has been inserted. Be sure to completely empty the fill syringe, even after hearing the two beeps.\n\nAfter filling the Pod, please press Next.\n\nNote: do not remove the Pod\'s needle cap at this time. diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitJoinTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitJoinTest.kt index 7d1e2f1c4e1d..13d15cc29929 100644 --- a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitJoinTest.kt +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitJoinTest.kt @@ -1,6 +1,7 @@ package app.aaps.pump.omnipod.common.bledriver.comm.message import app.aaps.core.utils.toHex +import app.aaps.pump.omnipod.common.bledriver.comm.packet.BlePacketLayout import app.aaps.pump.omnipod.common.bledriver.comm.packet.PayloadJoiner import app.aaps.pump.omnipod.common.bledriver.comm.packet.PayloadSplitter import com.google.common.truth.Truth.assertThat @@ -17,9 +18,9 @@ class PayloadSplitJoinTest { random.nextBytes(payload) val splitter = PayloadSplitter(payload) val packets = splitter.splitInPackets() - val joiner = PayloadJoiner(packets[0].toByteArray()) + val joiner = PayloadJoiner(packets[0].toByteArray(BlePacketLayout.DASH)) for (p in packets.subList(1, packets.size)) { - joiner.accumulate(p.toByteArray()) + joiner.accumulate(p.toByteArray(BlePacketLayout.DASH)) } val got = joiner.finalize() assertThat(got.toHex()).isEqualTo(payload.toHex()) diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitterTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitterTest.kt index 0983fe018489..83b383b00161 100644 --- a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitterTest.kt +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/common/bledriver/comm/message/PayloadSplitterTest.kt @@ -1,6 +1,7 @@ package app.aaps.pump.omnipod.common.bledriver.comm.message import app.aaps.core.utils.toHex +import app.aaps.pump.omnipod.common.bledriver.comm.packet.BlePacketLayout import app.aaps.pump.omnipod.common.bledriver.comm.packet.PayloadSplitter import com.google.common.truth.Truth.assertThat import com.google.crypto.tink.subtle.Hex @@ -17,8 +18,8 @@ class PayloadSplitterTest { val packets = splitter.splitInPackets() assertThat(packets).hasSize(2) - assertThat(packets[0].toByteArray().toHex()).isEqualTo(f1) - val p2 = packets[1].toByteArray() + assertThat(packets[0].toByteArray(BlePacketLayout.DASH).toHex()).isEqualTo(f1) + val p2 = packets[1].toByteArray(BlePacketLayout.DASH) assertThat(p2.size).isAtLeast(10) assertThat(p2.copyOfRange(0, 10).toHex()).isEqualTo(f2.subSequence(0, 20)) } diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashAlarmTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashAlarmTest.kt new file mode 100644 index 000000000000..7b0d106e9565 --- /dev/null +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashAlarmTest.kt @@ -0,0 +1,143 @@ +package app.aaps.pump.omnipod.dash + +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.core.interfaces.notifications.AlarmSound +import app.aaps.core.interfaces.notifications.NotificationId +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.OmnipodDashBleManagerImpl +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.Nonce +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.device.BleDeviceManager +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.session.BleConnection +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.session.BleConnectionFactory +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessagePacket +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendSuccess +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageType +import app.aaps.pump.omnipod.common.bledriver.comm.session.Connected +import app.aaps.pump.omnipod.common.bledriver.comm.session.Session +import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionKeys +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManagerImpl +import app.aaps.pump.omnipod.dash.driver.OmnipodDashManagerImpl +import app.aaps.pump.omnipod.dash.history.DashHistory +import app.aaps.shared.tests.AAPSLoggerTest +import app.aaps.shared.tests.rx.TestAapsSchedulers +import com.google.common.truth.Truth.assertThat +import io.reactivex.rxjava3.core.Completable +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import app.aaps.pump.omnipod.common.R as CommonR + +class OmnipodDashAlarmTest { + + @Test + fun `a received Dash fault updates pod state and posts an audible notification`() = runTest { + val logger = AAPSLoggerTest() + val preferences: Preferences = mock() + val podState = OmnipodDashPodStateManagerImpl(logger, mock(), preferences).apply { + activationProgress = ActivationProgress.COMPLETED + uniqueId = 2L + bluetoothAddress = "00:11:22:33:44:55" + ltk = ByteArray(16) + } + val ids = Ids.forController(Id.fromInt(1), Id.fromInt(2)) + val msgIO: MessageIO = mock() + val enDecrypt: EnDecrypt = mock() + // Decrypted Dash reply from the report, with a test pod ID in the envelope. + val replyHex = "302e303d00200000000214180216020d0000000e003e10000403ff0004000008000000000000" + val reply = MessagePacket( + type = MessageType.ENCRYPTED, + source = ids.podId, + destination = ids.myId, + payload = ByteArray(replyHex.length / 2) { replyHex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }, + sequenceNumber = 2 + ) + whenever(msgIO.receiveMessage()).thenReturn(reply) + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + whenever(enDecrypt.decrypt(reply)).thenReturn(reply) + whenever(enDecrypt.encrypt(any())).thenAnswer { it.getArgument(0) } + val session = Session(logger, msgIO, ids, SessionKeys(ByteArray(16), Nonce(ByteArray(8), 0), 1), enDecrypt) + val connection: BleConnection = mock() + whenever(connection.connectionState()).thenReturn(Connected) + whenever(connection.session).thenReturn(session) + val connectionFactory: BleConnectionFactory = mock() + whenever(connectionFactory.createConnection(any())).thenReturn(connection) + val deviceManager: BleDeviceManager = mock() + whenever(deviceManager.isBluetoothAvailable()).thenReturn(true) + whenever(deviceManager.ensureBondedIfRequired(any())).thenReturn(true) + val bleManager = OmnipodDashBleManagerImpl(logger, podState, mock(), connectionFactory, deviceManager) + bleManager.connect().test().assertComplete().assertNoErrors() + val schedulers = TestAapsSchedulers() + val manager = OmnipodDashManagerImpl(logger, podState, bleManager, schedulers) + val history: DashHistory = mock() + whenever(history.updateFromState(podState)).thenReturn(Completable.complete()) + val pumpSync: PumpSync = mock() + whenever(pumpSync.expectedPumpState()).thenReturn(PumpSync.PumpState(null, null, null, null, "2")) + val rh: ResourceHelper = mock() + whenever( + rh.gs( + eq(CommonR.string.omnipod_common_pod_status_pod_fault_description), + eq(AlarmType.ALARM_SAWCOP_RESET.code), + eq(AlarmType.ALARM_SAWCOP_RESET.toString()) + ) + ).thenReturn("Pod fault") + whenever(rh.gs(eq(CommonR.string.omnipod_common_pdm_ref), any())).thenReturn("Ref: test") + val notifications: NotificationManager = mock() + val plugin = OmnipodDashPumpPlugin( + aapsLogger = logger, + rh = rh, + preferences = preferences, + commandQueue = mock(), + omnipodManager = manager, + podStateManager = podState, + history = history, + pumpSync = pumpSync, + rxBus = mock(), + aapsSchedulers = schedulers, + uiInteraction = mock(), + notificationManager = notifications, + pumpEnactResultProvider = { mock() }, + bolusProgressData = mock(), + dashHistoryDatabase = mock(), + protectionCheck = mock(), + blePreCheck = mock() + ) + + plugin.getPumpStatus("Refresh") + + assertThat(podState.podStatus).isEqualTo(PodStatus.ALARM) + assertThat(podState.deliveryStatus).isEqualTo(DeliveryStatus.SUSPENDED) + assertThat(podState.alarmType).isEqualTo(AlarmType.ALARM_SAWCOP_RESET) + assertThat(podState.alarmSynced).isTrue() + verify(notifications).post( + id = eq(NotificationId.OMNIPOD_POD_FAULT), + text = eq("Pod fault\nRef: test"), + level = eq(NotificationId.OMNIPOD_POD_FAULT.defaultLevel), + validMinutes = eq(0), + sound = eq(AlarmSound.BOLUS_ERROR), + actions = eq(emptyList()), + validityCheck = anyOrNull() + ) + verify(pumpSync).insertAnnouncement( + error = eq("Pod fault\nRef: test"), + pumpId = any(), + pumpType = eq(PumpType.OMNIPOD_DASH), + pumpSerial = eq("2") + ) + } +} diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashCommandConfirmationTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashCommandConfirmationTest.kt index 851211b11122..3214f7a25bd2 100644 --- a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashCommandConfirmationTest.kt +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashCommandConfirmationTest.kt @@ -23,6 +23,7 @@ import app.aaps.pump.omnipod.common.definition.OmnipodCommandType import app.aaps.pump.omnipod.common.history.data.HistoryRecord import app.aaps.pump.omnipod.common.history.data.InitialResult import app.aaps.pump.omnipod.common.queue.command.CommandDisableSuspendAlerts +import app.aaps.pump.omnipod.common.util.PodTimeZone import app.aaps.pump.omnipod.dash.driver.OmnipodDashManager import app.aaps.pump.omnipod.dash.history.DashHistory import app.aaps.pump.omnipod.dash.history.database.DashHistoryDatabase @@ -97,6 +98,7 @@ class OmnipodDashCommandConfirmationTest { verifyBlocking(pumpSync) { syncStopTemporaryBasalWithPumpId(eq(CREATED_AT), eq(HISTORY_ID), eq(PumpType.OMNIPOD_DASH), any(), any()) } verifyBlocking(commandQueue, timeout(2_000)) { customCommand(any()) } verify(podStateManager).basalProgram = basalProgram + verify(podStateManager).tempBasal = null verify(notificationManager).dismiss(NotificationId.OMNIPOD_POD_SUSPENDED) verify(notificationManager).dismiss(NotificationId.OMNIPOD_TIME_OUT_OF_SYNC) } @@ -111,6 +113,40 @@ class OmnipodDashCommandConfirmationTest { verify(rxBus, never()).send(any()) } + @Test + fun `late time confirmation uses the sent offset and clears the in-progress flag`() = runBlocking { + givenHistoryEntry(OmnipodCommandType.SET_TIME) + val sentZone = PodTimeZone("Europe/Amsterdam", 7200000, CREATED_AT) + whenever(podStateManager.timeChangeInProgress).thenReturn(true) + val original = confirmation(success = true) + + sut.handleCommandConfirmation(original.copy(command = original.command.copy(basalTimeZone = sentZone))) + + verify(podStateManager).confirmTimeZone(sentZone) + verify(podStateManager, never()).updateTimeZone() + verify(podStateManager).timeChangeInProgress = false + } + + @Test + fun `confirmed suspend retains the internal zero basal`() = runBlocking { + givenHistoryEntry(OmnipodCommandType.SUSPEND_DELIVERY) + + sut.handleCommandConfirmation(confirmation(success = true)) + + verify(podStateManager, never()).tempBasal = null + } + + @Test + fun `cancel during suspension retains the internal zero basal`() = runBlocking { + givenHistoryEntry(OmnipodCommandType.CANCEL_TEMPORARY_BASAL) + whenever(podStateManager.isSuspended).thenReturn(true) + + sut.handleCommandConfirmation(confirmation(success = true)) + + verify(podStateManager, never()).tempBasal = null + verifyBlocking(pumpSync, never()) { syncStopTemporaryBasalWithPumpId(any(), any(), any(), any(), any()) } + } + @Test fun `a failed time change changes nothing`() = runBlocking { givenHistoryEntry(OmnipodCommandType.SET_TIME) diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPluginStateTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPluginStateTest.kt index 86024931ea91..82de360abe92 100644 --- a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPluginStateTest.kt +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashPumpPluginStateTest.kt @@ -118,8 +118,7 @@ class OmnipodDashPumpPluginStateTest { */ @Test fun `an alarming pod reports a zero base rate even with a program loaded`() { - val program = mock() - whenever(program.rateAt(any())).thenReturn(1.25) + val program = BasalProgram(listOf(BasalProgram.Segment(0, 48, 125))) whenever(podStateManager.basalProgram).thenReturn(program) whenever(podStateManager.alarmType).thenReturn(mock()) @@ -128,10 +127,10 @@ class OmnipodDashPumpPluginStateTest { @Test fun `a healthy pod reports the rate its program gives for now`() { - val program = mock() - whenever(program.rateAt(any())).thenReturn(1.25) + val program = BasalProgram(listOf(BasalProgram.Segment(0, 48, 125))) whenever(podStateManager.basalProgram).thenReturn(program) whenever(podStateManager.alarmType).thenReturn(null) + whenever(podStateManager.timeZoneOffset).thenReturn(null) assertThat(sut.baseBasalRate.cU).isEqualTo(1.25) } @@ -290,11 +289,20 @@ class OmnipodDashPumpPluginStateTest { } @Test - fun `the pump reports itself as an Insulet pump that cannot handle DST`() { + fun `the pump supports automatic time handling without an active pod`() { assertThat(sut.manufacturer()).isEqualTo(ManufacturerType.Insulet) - assertThat(sut.canHandleDST()).isFalse() + assertThat(sut.canHandleDST()).isTrue() assertThat(sut.isFakingTempsByExtendedBoluses).isFalse() } + @Test + fun `an active pod needs a known offset before disabling the old DST guard`() { + whenever(podStateManager.isPodRunning).thenReturn(true) + whenever(podStateManager.timeZoneOffset).thenReturn(null) + assertThat(sut.canHandleDST()).isFalse() + whenever(podStateManager.timeZoneOffset).thenReturn(3600000) + assertThat(sut.canHandleDST()).isTrue() + } + // endregion } diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashTimeChangeTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashTimeChangeTest.kt new file mode 100644 index 000000000000..7c2585a762fd --- /dev/null +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/OmnipodDashTimeChangeTest.kt @@ -0,0 +1,254 @@ +package app.aaps.pump.omnipod.dash + +import app.aaps.core.interfaces.constraints.Constraint +import app.aaps.core.data.pump.defs.TimeChangeType +import app.aaps.core.interfaces.profile.Profile +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.pump.PumpProfile +import app.aaps.core.interfaces.pump.PumpRate +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.pump.omnipod.common.bledriver.event.PodEvent +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.state.CommandConfirmed +import app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManager +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.common.history.data.HistoryRecord +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange +import app.aaps.pump.omnipod.common.util.PodTimeZone +import app.aaps.pump.omnipod.dash.driver.OmnipodDashManager +import app.aaps.pump.omnipod.dash.history.DashHistory +import app.aaps.shared.tests.TestBaseWithProfile +import com.google.common.truth.Truth.assertThat +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Maybe +import io.reactivex.rxjava3.core.Observable +import io.reactivex.rxjava3.core.Single +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class OmnipodDashTimeChangeTest : TestBaseWithProfile() { + + private val logger = mock() + private val state = mock() + private val manager = mock() + private val history = mock() + private val sync = mock() + private val queue = mock() + private lateinit var plugin: OmnipodDashPumpPlugin + private var delivery = DeliveryStatus.BASAL_ACTIVE + private var active: OmnipodDashPodStateManager.ActiveCommand? = null + private var temp: OmnipodDashPodStateManager.TempBasal? = null + private var inProgress = false + private var zone = PodTimeZone.now().copy(offset = PodTimeZone.now().offset - 3600000) + private var expectedTemp: PumpSync.PumpState.TemporaryBasal? = null + private var basal: BasalProgram? = null + private var confirmSuccess = true + private val records = mutableMapOf() + + private fun loopAllowed(): Boolean { + var allowed = true + val constraint = mock>() + doAnswer { allowed = it.getArgument(0); constraint }.whenever(constraint).set(any(), anyOrNull(), any()) + plugin.isLoopInvocationAllowed(constraint) + return allowed + } + + @BeforeEach + fun setup() = runBlocking { + plugin = OmnipodDashPumpPlugin( + logger, rh, preferences, queue, manager, state, history, sync, rxBus, + aapsSchedulers, mock(), notificationManager, pumpEnactResultProvider, mock(), mock(), mock(), mock() + ) + whenever(state.isPodRunning).thenReturn(true) + whenever(state.isActivationCompleted).thenReturn(true) + whenever(state.deliveryStatus).thenAnswer { delivery } + whenever(state.isSuspended).thenAnswer { delivery.suspended() } + whenever(state.tempBasalActive).thenAnswer { delivery.tempBasalActive() } + whenever(state.tempBasal).thenAnswer { temp } + doAnswer { temp = it.getArgument(0); Unit }.whenever(state).tempBasal = anyOrNull() + whenever(state.timeZoneOffset).thenAnswer { zone.offset } + whenever(state.timeChangeInProgress).thenAnswer { inProgress } + doAnswer { inProgress = it.getArgument(0); Unit }.whenever(state).timeChangeInProgress = any() + doAnswer { zone = it.getArgument(0); Unit }.whenever(state).confirmTimeZone(any()) + whenever(state.activeCommand).thenAnswer { active } + whenever(state.basalProgram).thenAnswer { basal } + doAnswer { basal = it.getArgument(0); Unit }.whenever(state).basalProgram = anyOrNull() + whenever(state.observeNoActiveCommand()).thenReturn(Completable.defer { + if (active == null) Completable.complete() else Completable.error(IllegalStateException("Unconfirmed")) + }) + whenever(state.createActiveCommand(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenAnswer { + val id = it.getArgument(0) + val basal = it.getArgument(1) + val newTemp = it.getArgument(2) + Single.fromCallable { + OmnipodDashPodStateManager.ActiveCommand(1, 0, historyId = id, sendError = null, + basalProgram = basal, tempBasal = newTemp, requestedBolus = null).also { command -> active = command } + } + } + whenever(state.updateActiveCommand()).thenReturn(Maybe.defer { + val command = active + active = null + if (command == null) Maybe.empty() else Maybe.just(CommandConfirmed(command, confirmSuccess)) + }) + whenever(history.updateFromState(any())).thenReturn(Completable.complete()) + whenever(history.createRecord(any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenAnswer { + val commandType = it.getArgument(0) + Single.fromCallable { + val id = records.size.toLong() + 1 + val now = System.currentTimeMillis() + records[id] = HistoryRecord(id, now, now, commandType, InitialResult.SENT, null, null, null, null) + id + } + } + whenever(history.getById(any())).thenAnswer { records.getValue(it.getArgument(0)) } + val profile = mock() + whenever(profile.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 1.0))) + whenever(sync.expectedPumpState()).thenAnswer { PumpSync.PumpState(expectedTemp, null, null, profile, "12345") } + whenever(sync.syncTemporaryBasalWithPumpId(any(), any(), any(), any(), anyOrNull(), any(), any(), any())).thenAnswer { + expectedTemp = PumpSync.PumpState.TemporaryBasal( + it.getArgument(0), it.getArgument(2), it.getArgument(1).cU, true, + it.getArgument(4), 1, it.getArgument(5) + ) + true + } + whenever(sync.syncStopTemporaryBasalWithPumpId(any(), any(), any(), any(), any())).thenAnswer { expectedTemp = null; true } + whenever(manager.getStatus(any())).thenReturn(Observable.empty()) + whenever(manager.suspendDelivery(any())).thenReturn(Observable.defer { + delivery = DeliveryStatus.SUSPENDED + Observable.just(PodEvent.CommandSent(mock())) + }) + whenever(manager.setBasalProgram(any(), any())).thenReturn(Observable.defer { + active?.basalTimeZone = PodTimeZone.now() + delivery = DeliveryStatus.BASAL_ACTIVE + Observable.empty() + }) + whenever(manager.setTempBasal(any(), any(), any())).thenReturn(Observable.defer { + delivery = DeliveryStatus.TEMP_BASAL_ACTIVE + Observable.just(PodEvent.CommandSent(mock())) + }) + } + + @ParameterizedTest + @ValueSource(ints = [3600000, -3600000]) + fun `both DST directions unblock loop only after confirmed time correction`(difference: Int) = runBlocking { + zone = PodTimeZone.now().let { it.copy(offset = it.offset - difference) } + assertThat(loopAllowed()).isFalse() + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isTrue() + assertThat(zone.offset).isEqualTo(PodTimeZone.now().offset) + assertThat(inProgress).isFalse() + assertThat(loopAllowed()).isTrue() + verify(manager).setBasalProgram(any(), any()) + } + + @ParameterizedTest + @ValueSource(doubles = [0.0, 0.7, 1.5, 1.0]) + fun `a DST correction suspends and loses any active temp basal, like Medtrum accepts`(rate: Double) = runBlocking { + val start = System.currentTimeMillis() - 60000 + temp = OmnipodDashPodStateManager.TempBasal(start, rate, 30) + expectedTemp = PumpSync.PumpState.TemporaryBasal(start, 30 * 60000L, rate, true, PumpSync.TemporaryBasalType.NORMAL, 1, 1) + delivery = DeliveryStatus.TEMP_BASAL_ACTIVE + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isTrue() + assertThat(temp).isNull() + verify(manager, never()).setTempBasal(any(), any(), any()) + assertThat(inProgress).isFalse() + } + + @Test + fun `reported suspend counts the old rate then keeps the same zero inside and outside`() = runBlocking { + var zeroAtResume: OmnipodDashPodStateManager.TempBasal? = null + var reportedAtResume: PumpSync.PumpState.TemporaryBasal? = null + whenever(manager.setBasalProgram(any(), any())).thenReturn(Observable.defer { + zeroAtResume = temp + reportedAtResume = expectedTemp + delivery = DeliveryStatus.BASAL_ACTIVE + Observable.empty() + }) + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isTrue() + val reported = requireNotNull(reportedAtResume) + val zero = OmnipodDashPodStateManager.TempBasal(reported.timestamp, 0.0, (reported.duration / 60000).toShort()) + assertThat(zeroAtResume).isEqualTo(zero) + assertThat(reported.type).isEqualTo(PumpSync.TemporaryBasalType.PUMP_SUSPEND) + val order = inOrder(state) + order.verify(state).updateBasalExpected(reported.timestamp) + order.verify(state).tempBasal = zero + assertThat(temp).isNull() + assertThat(expectedTemp).isNull() + } + + @Test + fun `a nonzero suspend rate also updates the expected basal at the reported start`() = runBlocking { + whenever(state.updateActiveCommand()).thenReturn(Maybe.empty()) + + plugin.setTempBasalAbsolute(1.0, 30, true, PumpSync.TemporaryBasalType.PUMP_SUSPEND) + + val reported = requireNotNull(expectedTemp) + verify(state).updateBasalExpected(reported.timestamp) + assertThat(temp).isEqualTo(OmnipodDashPodStateManager.TempBasal(reported.timestamp, 1.0, 30)) + } + + @Test + fun `a denied time update keeps the loop blocked for a retry`() = runBlocking { + confirmSuccess = false + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isTrue() + assertThat(inProgress).isTrue() + assertThat(loopAllowed()).isFalse() + } + + @Test + fun `an active bolus or a user suspension prevents automatic reprogramming`() = runBlocking { + delivery = DeliveryStatus.BOLUS_AND_BASAL_ACTIVE + plugin.executeCustomCommand(CommandHandleTimeChange(false)) + delivery = DeliveryStatus.SUSPENDED + plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + verify(manager, never()).suspendDelivery(any()) + verify(manager, never()).setBasalProgram(any(), any()) + } + + @Test + fun `DST callback queues correction once and a missed callback is found by polling`() = runBlocking { + whenever(queue.customCommand(any())).thenAnswer { + plugin.executeCustomCommand(it.getArgument(0)) + } + + plugin.timezoneOrDSTChanged(TimeChangeType.DSTStarted) + plugin.checkTimeChange() + + verify(queue, times(1)).customCommand(any()) + zone = zone.copy(offset = zone.offset - 3600000) + plugin = OmnipodDashPumpPlugin( + aapsLogger, rh, preferences, queue, manager, state, history, sync, rxBus, + aapsSchedulers, mock(), notificationManager, pumpEnactResultProvider, mock(), mock(), mock(), mock() + ) + plugin.checkTimeChange() + verify(queue, times(2)).customCommand(any()) + } +} diff --git a/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/ui/compose/PodFaultTextTest.kt b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/ui/compose/PodFaultTextTest.kt new file mode 100644 index 000000000000..41dbc3d2082b --- /dev/null +++ b/pump/omnipod/dash/src/test/kotlin/app/aaps/pump/omnipod/dash/ui/compose/PodFaultTextTest.kt @@ -0,0 +1,34 @@ +package app.aaps.pump.omnipod.dash.ui.compose + +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PdmFaultCategory +import app.aaps.pump.omnipod.dash.R +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import app.aaps.pump.omnipod.common.R as CommonR + +internal class PodFaultTextTest { + + @Test + fun eachFaultCategoryShowsItsMessageAndReference() { + val rh = mock() + val ref = "ref" + val resources = mapOf( + PdmFaultCategory.RESERVOIR_EMPTY to R.string.omnipod_dash_pdm_notification_reservoir_empty, + PdmFaultCategory.AUTO_OFF to R.string.omnipod_dash_pdm_notification_auto_off, + PdmFaultCategory.POD_EXPIRED to R.string.omnipod_dash_pdm_notification_pod_expired, + PdmFaultCategory.OCCLUDED to R.string.omnipod_dash_pdm_notification_occluded, + PdmFaultCategory.POD_ERROR to R.string.omnipod_dash_pdm_notification_pod_error + ) + resources.values.forEach { resource -> + whenever(rh.gs(resource)).thenReturn("Fault $resource") + } + whenever(rh.gs(CommonR.string.omnipod_common_pdm_ref, ref)).thenReturn("Ref: $ref") + + resources.forEach { (category, resource) -> + assertThat(category.notificationText(rh, ref)).isEqualTo("Fault $resource\n\nRef: $ref") + } + } +} diff --git a/pump/omnipod/eros/src/main/java/app/aaps/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatus.java b/pump/omnipod/eros/src/main/java/app/aaps/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatus.java index 2c099d7b5f4c..12da7f4c0390 100644 --- a/pump/omnipod/eros/src/main/java/app/aaps/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatus.java +++ b/pump/omnipod/eros/src/main/java/app/aaps/pump/omnipod/eros/driver/communication/message/response/podinfo/PodInfoDetailedStatus.java @@ -57,8 +57,8 @@ public PodInfoDetailedStatus(byte[] encodedData) { faultEventTime = Duration.standardMinutes(minutesSinceActivation); } - double reservoirValue = ((encodedData[11] & 0x03) << 8) + - ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[12]) * OmnipodConstants.POD_PULSE_SIZE; + double reservoirValue = (((encodedData[11] & 0x03) << 8) + + ByteUtil.INSTANCE.convertUnsignedByteToInt(encodedData[12])) * OmnipodConstants.POD_PULSE_SIZE; if (reservoirValue > OmnipodConstants.MAX_RESERVOIR_READING) { reservoirLevel = null; } else { diff --git a/pump/omnipod/omnipod5/build.gradle.kts b/pump/omnipod/omnipod5/build.gradle.kts new file mode 100644 index 000000000000..b127d3d76bf8 --- /dev/null +++ b/pump/omnipod/omnipod5/build.gradle.kts @@ -0,0 +1,40 @@ +plugins { + alias(libs.plugins.android.library) + alias(libs.plugins.ksp) + alias(libs.plugins.compose.compiler) + alias(libs.plugins.metro) + id("android-module-dependencies") + id("test-module-dependencies") + id("jacoco-module-dependencies") +} + +android { + namespace = "app.aaps.pump.omnipod.omnipod5" +} + +ksp { + arg("room.incremental", "true") + arg("room.schemaLocation", "$projectDir/schemas") +} + +dependencies { + implementation(project(":core:data")) + implementation(project(":core:interfaces")) + implementation(project(":core:keys")) + implementation(project(":core:utils")) + implementation(project(":core:ui")) + implementation(project(":pump:common")) + implementation(project(":pump:omnipod:common")) + + api(libs.androidx.room.runtime) + implementation(libs.androidx.room.rxjava3) + implementation(libs.kotlinx.coroutines.rx3) + + implementation(libs.androidx.compose.ui.tooling.preview) + debugImplementation(libs.androidx.compose.ui.tooling) + + implementation(libs.androidx.webkit) + + testImplementation(project(":shared:tests")) + ksp(libs.androidx.room.compiler) +} diff --git a/pump/omnipod/omnipod5/consumer-rules.pro b/pump/omnipod/omnipod5/consumer-rules.pro new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/pump/omnipod/omnipod5/proguard-rules.pro b/pump/omnipod/omnipod5/proguard-rules.pro new file mode 100644 index 000000000000..f1b424510da5 --- /dev/null +++ b/pump/omnipod/omnipod5/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/pump/omnipod/omnipod5/src/androidTest/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/AndroidKeystoreAesCipherTest.kt b/pump/omnipod/omnipod5/src/androidTest/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/AndroidKeystoreAesCipherTest.kt new file mode 100644 index 000000000000..78e563c81319 --- /dev/null +++ b/pump/omnipod/omnipod5/src/androidTest/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/AndroidKeystoreAesCipherTest.kt @@ -0,0 +1,86 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.security + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.google.common.truth.Truth.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import java.security.SecureRandom + +/** + * Real instrumented test for [AndroidKeystoreAesCipher] - the one piece of cryptography + * built this session that genuinely could not be verified in the development sandbox, + * since `AndroidKeyStore` is a real Android OS provider that only exists on an actual + * device or emulator. Run this via Android Studio's test runner (or + * `./gradlew :pump:omnipod:omnipod5:connectedFullDebugAndroidTest`) against a real device or + * emulator to close that gap for real, rather than relying on code review alone for a class + * that handles actual key material. + */ +@RunWith(AndroidJUnit4::class) +class AndroidKeystoreAesCipherTest { + + private val random = SecureRandom() + + @Test + fun encryptDecryptRoundTrip_variousSizes() { + val cipher = AndroidKeystoreAesCipher() + + repeat(20) { i -> + val plaintext = ByteArray(1 + i * 7).also { random.nextBytes(it) } + val encrypted = cipher.encrypt(plaintext) + val decrypted = cipher.decrypt(encrypted) + assertThat(decrypted).isEqualTo(plaintext) + } + } + + @Test + fun emptyPlaintext_roundTrips() { + val cipher = AndroidKeystoreAesCipher() + val encrypted = cipher.encrypt(ByteArray(0)) + val decrypted = cipher.decrypt(encrypted) + assertThat(decrypted).isEqualTo(ByteArray(0)) + } + + @Test + fun sameEncryptedValue_decryptsDifferentlyEachTime_dueToRandomIv() { + val cipher = AndroidKeystoreAesCipher() + val plaintext = "same plaintext both times".toByteArray() + + val encrypted1 = cipher.encrypt(plaintext) + val encrypted2 = cipher.encrypt(plaintext) + + assertThat(encrypted1).isNotEqualTo(encrypted2) + assertThat(cipher.decrypt(encrypted1)).isEqualTo(plaintext) + assertThat(cipher.decrypt(encrypted2)).isEqualTo(plaintext) + } + + @Test + fun keyPersistsAcrossSeparateCipherInstances() { + val cipherBeforeRestart = AndroidKeystoreAesCipher() + val plaintext = "must survive a simulated restart".toByteArray() + val encrypted = cipherBeforeRestart.encrypt(plaintext) + + val cipherAfterRestart = AndroidKeystoreAesCipher() + val decrypted = cipherAfterRestart.decrypt(encrypted) + + assertThat(decrypted).isEqualTo(plaintext) + } + + @Test(expected = Exception::class) + fun tamperedCiphertext_failsToDecrypt() { + val cipher = AndroidKeystoreAesCipher() + val plaintext = "sensitive credential material".toByteArray() + val encrypted = cipher.encrypt(plaintext) + + val raw = java.util.Base64.getDecoder().decode(encrypted) + raw[raw.size - 1] = (raw[raw.size - 1] + 1).toByte() + val tampered = java.util.Base64.getEncoder().encodeToString(raw) + + cipher.decrypt(tampered) + } + + @Test(expected = Exception::class) + fun malformedBase64_failsToDecryptRatherThanCrashingUnpredictably() { + val cipher = AndroidKeystoreAesCipher() + cipher.decrypt("not valid base64 at all !!!") + } +} diff --git a/pump/omnipod/omnipod5/src/main/AndroidManifest.xml b/pump/omnipod/omnipod5/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..fd3e29e82367 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + + diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/O5PumpPlugin.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/O5PumpPlugin.kt new file mode 100644 index 000000000000..31231a9dfaf2 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/O5PumpPlugin.kt @@ -0,0 +1,1952 @@ +package app.aaps.pump.omnipod.omnipod5 +import app.aaps.pump.omnipod.common.R + +import android.os.Handler +import android.os.Looper +import androidx.annotation.StringRes +import androidx.annotation.VisibleForTesting +import app.aaps.core.data.model.BS +import app.aaps.core.data.plugin.PluginType +import app.aaps.core.data.pump.defs.ManufacturerType +import app.aaps.core.data.pump.defs.PumpDescription +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.core.data.pump.defs.TimeChangeType +import app.aaps.core.data.time.T +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.constraints.Constraint +import app.aaps.core.interfaces.constraints.PluginConstraints +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.notifications.AlarmSound +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.di.PumpDriver +import app.aaps.core.interfaces.plugin.OwnDatabasePlugin +import app.aaps.core.interfaces.plugin.PluginBase +import app.aaps.core.interfaces.plugin.PluginDescription +import app.aaps.core.interfaces.profile.Profile +import app.aaps.core.interfaces.pump.BlePreCheck +import app.aaps.core.interfaces.pump.BolusProgressData +import app.aaps.core.interfaces.pump.DetailedBolusInfo +import app.aaps.core.interfaces.pump.Pump +import app.aaps.core.interfaces.pump.PumpEnactResult +import app.aaps.core.interfaces.pump.PumpInsulin +import app.aaps.core.interfaces.pump.PumpPluginBase +import app.aaps.core.interfaces.pump.PumpProfile +import app.aaps.core.interfaces.pump.PumpRate +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.pump.defs.fillFor +import app.aaps.core.interfaces.protection.ProtectionCheck +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.queue.CustomCommand +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.collectResilient +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.keys.interfaces.withCompose +import app.aaps.core.ui.compose.ComposeScreenContent +import app.aaps.core.ui.compose.icons.IcPluginOmnipod +import app.aaps.core.ui.compose.metroViewModel +import app.aaps.core.ui.compose.preference.PreferenceSubScreenDef +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5BleManager +import app.aaps.pump.omnipod.common.bledriver.pod.command.DeactivateCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.GetStatusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramAlertsCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBeepsCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBolusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramTempBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.SilenceAlertsCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.StopDeliveryCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.SuspendDeliveryCommand +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertConfiguration +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertTrigger +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepRepetitionType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepType +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.definition.O5_FIXED_NONCE +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ProgramReminder +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.basalDrift +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.basalDelivered +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.withPodAcceptance +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.buildO5ExpirationAlerts +import app.aaps.pump.omnipod.omnipod5.history.O5History +import app.aaps.pump.omnipod.omnipod5.history.database.O5HistoryDatabase +import app.aaps.pump.omnipod.common.history.data.BasalValuesRecord +import app.aaps.pump.omnipod.common.history.data.BolusRecord +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BolusType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.event.PodEvent +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.TempBasalRecord +import app.aaps.pump.omnipod.common.keys.DashBooleanPreferenceKey +import app.aaps.pump.omnipod.common.keys.OmnipodBooleanPreferenceKey +import app.aaps.pump.omnipod.common.keys.OmnipodIntPreferenceKey +import app.aaps.pump.omnipod.common.queue.command.CommandDeactivatePod +import app.aaps.pump.omnipod.common.queue.command.CommandDeliverBasalCorrection +import app.aaps.pump.omnipod.common.queue.command.CommandDisableSuspendAlerts +import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange +import app.aaps.pump.omnipod.omnipod5.queue.command.CommandPairNewPod +import app.aaps.pump.omnipod.common.queue.command.CommandPlayTestBeep +import app.aaps.pump.omnipod.common.queue.command.CommandResumeDelivery +import app.aaps.pump.omnipod.common.queue.command.CommandSilenceAlerts +import app.aaps.pump.omnipod.common.queue.command.CommandSuspendDelivery +import app.aaps.pump.omnipod.common.queue.command.CommandUpdateAlertConfiguration +import app.aaps.pump.omnipod.omnipod5.keys.O5IntentKey +import app.aaps.pump.omnipod.omnipod5.ui.O5CertificateStoreScreen +import app.aaps.pump.omnipod.omnipod5.ui.compose.OmnipodO5ComposeContent +import app.aaps.pump.omnipod.common.util.mapProfileToBasalProgram +import app.aaps.pump.omnipod.common.util.OmnipodTimeChange +import app.aaps.pump.omnipod.common.util.PodTimeZone +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Single +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.merge +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.rx3.rxCompletable +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.util.Date +import java.util.concurrent.CountDownLatch +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesIntoMap +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.IntKey +import dev.zacsweers.metro.SingleIn +import dev.zacsweers.metro.binding +import kotlin.concurrent.thread +import kotlin.math.ceil +import kotlin.math.roundToLong +import kotlin.time.TimeMark +import kotlin.time.TimeSource +import app.aaps.pump.omnipod.omnipod5.R as O5R + +private fun (() -> PumpEnactResult).get(): PumpEnactResult = invoke() + +/** + * `Pump`-interface implementation for Omnipod 5. Connects the already-built + * pairing/BLE/command/persistence layers + * (see [O5BleManager], [O5PodStateManager]) to AAPS's dosing/control surface. + * + * Runs O5 as a manual pod under AAPS's control, identical capabilities to Omnipod Dash - + * the pod's own onboard automated-delivery mode is never engaged (mirrors + * [PumpType.OMNIPOD_DASH]'s capability fields). + * + * Every dose-affecting command (bolus, temp basal, basal program) records a + * [O5PodStateManager.pendingDoseCommand] marker *before* sending, and clears it only once + * the outcome is confirmed. If the BLE response never arrives, the marker survives (it's + * part of the persisted pod state) and [reconcilePendingDose] - run at the end of every + * [getPumpStatus] call - resolves it on the next successful status read. Regular status + * reads are driven by the loop cycle and `KeepAliveWorker` (like Dash), so the pod stays + * disconnected between cycles. Two timers run on top of that: + * - [statusChecker] only queues an extra read when a + * [O5PodStateManager.pendingDoseCommand] is still outstanding (see + * [refreshStatusOnUnacknowledgedCommands]), and stops itself once the marker is cleared. + * - [housekeepingChecker] runs every minute while the plugin runs, but uses stored state + * only and never connects to the pod. It tells AAPS that no insulin is going in while no + * pod is running ([createFakeTBRWhenNoActivePod]) and posts the periodic pod warnings + * ([updatePodWarnings]), like the Dash status tick does. + * This is what makes an uncertain delivery outcome + * recoverable instead of silently lost; see [O5PodStateManager]'s class doc for why this + * doesn't need a Dash-style persisted command ledger to do so. + */ +@ContributesIntoMap(AppScope::class, binding = binding()) +@PumpDriver +@IntKey(1085) +@SingleIn(AppScope::class) +class O5PumpPlugin @Inject constructor( + aapsLogger: AAPSLogger, + override val rh: ResourceHelper, + preferences: Preferences, + commandQueue: CommandQueue, + private val bleManager: O5BleManager, + private val podStateManager: O5PodStateManager, + private val history: O5History, + private val pumpSync: PumpSync, + notificationManager: NotificationManager, + private val pumpEnactResultProvider: () -> PumpEnactResult, + private val bolusProgressData: BolusProgressData, + private val protectionCheck: ProtectionCheck, + private val blePreCheck: BlePreCheck, + private val config: Config, + private val o5HistoryDatabase: O5HistoryDatabase +) : PumpPluginBase( + pluginDescription = PluginDescription() + .mainType(PluginType.PUMP) + .composeContent { _ -> + OmnipodO5ComposeContent( + pluginName = rh.gs(R.string.omnipod_5_name), + protectionCheck = protectionCheck, + blePreCheck = blePreCheck, + rh = rh + ) + } + .icon(IcPluginOmnipod) + .pluginName(TextRef.AndroidRes(R.string.omnipod_5_name)) + .description(TextRef.AndroidRes(R.string.omnipod_5_pump_description)), + ownPreferences = OmnipodBooleanPreferenceKey.entries + OmnipodIntPreferenceKey.entries + + DashBooleanPreferenceKey.entries + O5IntentKey.ConfigEnabledEntries(config), + aapsLogger, rh, preferences, commandQueue, notificationManager +), Pump, OwnDatabasePlugin, PluginConstraints { + + @Volatile private var bolusCanceled = false + @Volatile private var bolusDeliveryInProgress = false + @Volatile private var stopConnecting: CountDownLatch? = null + private val doseMutex = Mutex() + private val timeChangeHandler = OmnipodTimeChange() + + @VisibleForTesting + internal var bolusTimeSource: TimeSource = TimeSource.Monotonic + + @VisibleForTesting + internal var bolusSleep: (Long) -> Unit = { Thread.sleep(it) } + + private var statusChecker: Runnable + private var housekeepingChecker: Runnable + private var nextPodWarningCheck: Long = 0 + + private var handler: Handler? = null + @VisibleForTesting + internal var scope: CoroutineScope? = null + + companion object { + + private const val BOLUS_RETRY_INTERVAL_MS = 2000L + private const val BOLUS_RETRIES = 5 + private const val BOLUS_CONFIRMATION_MARGIN_MS = 3000L + private const val STATUS_CHECK_INTERVAL_MS = 60L * 1000 + private const val POD_WARNING_INTERVAL_MS = 15L * 60 * 1000 + private const val RESERVOIR_OVER_50_UNITS_DEFAULT = 75.0 + + /** Serial reported before any pod is paired, and used for the zero "no delivery" temp + * basal when AAPS has no pump registered yet. */ + internal const val UNPAIRED_SERIAL = "O5-unpaired" + + private const val FIXED_NONCE = O5_FIXED_NONCE + + /** Bolus pulse interval in eighths of a second (2 seconds). */ + private const val BOLUS_DELAY_BETWEEN_PULSES_EIGHTH_SECONDS: Byte = 16 + + private val pumpDescription = PumpDescription().fillFor(PumpType.OMNIPOD_5) + } + + init { + statusChecker = Runnable { + refreshStatusOnUnacknowledgedCommands() + if (podStateManager.pendingDoseCommand != null) { + handler?.postDelayed(statusChecker, STATUS_CHECK_INTERVAL_MS) + } + } + housekeepingChecker = Runnable { + updatePodWarnings() + scope?.launch { + checkTimeChange() + try { + createFakeTBRWhenNoActivePod() + } catch (e: Exception) { + aapsLogger.warn(LTag.PUMP, "O5 error in createFakeTBRWhenNoActivePod: $e") + } + } + handler?.postDelayed(housekeepingChecker, STATUS_CHECK_INTERVAL_MS) + } + } + + /** + * (Re)start the 60s [statusChecker] tick. Called whenever a dose-affecting command records a + * [O5PodStateManager.pendingDoseCommand], so an unconfirmed dose is reconciled promptly. The + * tick self-stops once the pending marker is cleared, so it does not run while the pod is idle. + */ + private fun armStatusChecker() { + handler?.removeCallbacks(statusChecker) + handler?.postDelayed(statusChecker, STATUS_CHECK_INTERVAL_MS) + } + + /** + * Mirrors `OmnipodDashPumpPlugin.refreshStatusOnUnacknowledgedCommands`. The periodic tick no + * longer forces a BLE connect on its own - regular status polling is driven by the loop cycle + * and `KeepAliveWorker` (same as Dash), which keeps the pod disconnected between cycles instead + * of reconnecting every tick. We only reach out here when a dose-affecting command was left + * unconfirmed ([O5PodStateManager.pendingDoseCommand] survives), so a single status read is + * queued to reconcile it promptly rather than waiting for the next loop-driven read. The queue + * routes that read through [getPumpStatus], which runs [reconcilePendingDose] at the end. + */ + private fun refreshStatusOnUnacknowledgedCommands() { + if (podStateManager.activationProgress == ActivationProgress.COMPLETED && + podStateManager.pendingDoseCommand != null && + commandQueue.size() == 0 && + commandQueue.performing() == null + ) { + pluginScope.launch { commandQueue.readStatus(rh.gs(R.string.omnipod_5_unconfirmed_command)) } + } + } + + /** + * Tells AAPS that no insulin is going in while no pod is running (none paired, activation not + * finished, faulted or deactivated). Without this AAPS keeps counting profile basal as + * delivered and IOB includes insulin that never went in. Mirrors + * `OmnipodDashPumpPlugin.createFakeTBRWhenNoActivePod`. + * + * Uses the serial AAPS has registered as the active pump, so the record is accepted instead of + * being rejected as data from a different pump - the old pod's serial after a deactivation or + * discard, or [UNPAIRED_SERIAL] when nothing is registered. The new-pod wizard's + * `connectNewPump()` ends this temp basal when the next pod starts delivering. + * + * Internal (rather than private) to allow unit testing within this module. + */ + internal suspend fun createFakeTBRWhenNoActivePod() { + if (podStateManager.isPodRunning) return + val expectedState = pumpSync.expectedPumpState() + recordNoDelivery(expectedState, expectedState.serialNumber.ifEmpty { UNPAIRED_SERIAL }) + } + + /** + * Records a zero-rate [PumpSync.TemporaryBasalType.PUMP_SUSPEND] temp basal for the whole pod + * lifetime, unless one is already running. A zero temp basal of another type (for example a + * 30 minute one from the loop) is replaced, because it would end while the pod still delivers + * nothing. + */ + private suspend fun recordNoDelivery(expectedState: PumpSync.PumpState, pumpSerial: String) { + val tbr = expectedState.temporaryBasal + if (tbr != null && tbr.rate == 0.0 && tbr.type == PumpSync.TemporaryBasalType.PUMP_SUSPEND) return + aapsLogger.info(LTag.PUMP, "O5 recording zero delivery temp basal, serial=$pumpSerial") + syncZeroTempBasal(pumpSerial) + } + + private suspend fun syncZeroTempBasal(pumpSerial: String) { + val now = System.currentTimeMillis() + pumpSync.syncTemporaryBasalWithPumpId( + timestamp = now, + rate = PumpRate(0.0), + duration = T.mins(PodConstants.MAX_POD_LIFETIME.toMinutes()).msecs(), + isAbsolute = true, + type = PumpSync.TemporaryBasalType.PUMP_SUSPEND, + pumpId = now, // not used for anything, only has to be unique + pumpType = PumpType.OMNIPOD_5, + pumpSerial = pumpSerial + ) + podStateManager.activeTempBasalStartTime = now + podStateManager.activeTempBasalRate = 0.0 + podStateManager.activeTempBasalDurationMinutes = PodConstants.MAX_POD_LIFETIME.toMinutes().toShort() + } + + /** + * When the pod has stopped delivering for good (fault or deactivation), tells AAPS that no + * insulin is going in. Runs on every status read, not only once per alarm like + * [checkPodFault], so a lost write or an app restart still ends up with the zero temp basal. + * Mirrors `OmnipodDashPumpPlugin.checkPodKaput`. + * + * Internal (rather than private) to allow unit testing within this module. + */ + internal suspend fun checkPodKaput() { + if (podStateManager.isPodKaput) { + recordNoDelivery(pumpSync.expectedPumpState(), serialNumber()) + } + checkPodFault() + } + + /** + * Posts the periodic pod warnings, at most once every 15 minutes: no running pod, delivery + * suspended, pod time zone differs from the phone. Uses stored state only. Port of + * `OmnipodDashPumpPlugin.updatePodWarnings`. + * + * Internal (rather than private) to allow unit testing within this module. + */ + internal fun updatePodWarnings() { + val now = System.currentTimeMillis() + if (now <= nextPodWarningCheck) return + if (!podStateManager.isPodRunning) { + notificationManager.post( + NotificationId.OMNIPOD_POD_NOT_ATTACHED, + TextRef.AndroidRes(R.string.omnipod_common_pod_status_no_active_pod) + ) + } else { + notificationManager.dismiss(NotificationId.OMNIPOD_POD_NOT_ATTACHED) + if (podStateManager.isSuspended) { + notificationManager.post( + NotificationId.OMNIPOD_POD_SUSPENDED, + rh.gs(R.string.omnipod_common_alert_delivery_suspended), + sound = if (preferences.get(DashBooleanPreferenceKey.SoundDeliverySuspendedNotification)) AlarmSound.BOLUS_ERROR else null + ) + } else { + notificationManager.dismiss(NotificationId.OMNIPOD_POD_SUSPENDED) + if (!podStateManager.sameTimeZone) { + notificationManager.post( + NotificationId.OMNIPOD_TIME_OUT_OF_SYNC, + TextRef.AndroidRes(R.string.timezone_on_pod_is_different_from_the_timezone), + level = NotificationLevel.NORMAL + ) + } + } + } + nextPodWarningCheck = now + POD_WARNING_INTERVAL_MS + } + + override suspend fun onStart() { + super.onStart() + handler = Handler(Looper.getMainLooper()) + if (podStateManager.pendingDoseCommand != null) { + handler?.postDelayed(statusChecker, STATUS_CHECK_INTERVAL_MS) + } + handler?.postDelayed(housekeepingChecker, STATUS_CHECK_INTERVAL_MS) + val newScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + scope = newScope + newScope.launch { checkTimeChange() } + merge( + preferences.observe(OmnipodBooleanPreferenceKey.ExpirationReminder).drop(1).map {}, + preferences.observe(OmnipodIntPreferenceKey.ExpirationReminderHours).drop(1).map {}, + preferences.observe(OmnipodBooleanPreferenceKey.ExpirationAlarm).drop(1).map {}, + preferences.observe(OmnipodIntPreferenceKey.ExpirationAlarmHours).drop(1).map {}, + preferences.observe(OmnipodBooleanPreferenceKey.LowReservoirAlert).drop(1).map {}, + preferences.observe(OmnipodIntPreferenceKey.LowReservoirAlertUnits).drop(1).map {}, + ).collectResilient(newScope, aapsLogger, LTag.PUMP) { commandQueue.customCommand(CommandUpdateAlertConfiguration()) } + } + + override suspend fun onStop() { + super.onStop() + handler?.removeCallbacks(statusChecker) + handler?.removeCallbacks(housekeepingChecker) + handler = null + scope?.cancel() + scope = null + } + + + /** Ready only while an activated pod is actually running. [ActivationProgress] never moves + * backwards on a fault (the wizard needs it for deactivation), so the pod status is checked + * too - like Dash's `isPodRunning`. */ + override fun isInitialized(): Boolean = + podStateManager.activationProgress == ActivationProgress.COMPLETED && podStateManager.isPodRunning + override fun isSuspended(): Boolean = podStateManager.deliverySuspended + + // The progress alone does not cover pairing: it is still NOT_STARTED until the first step is done, + // and the queue then ran and disconnected in the middle of the pairing (Dash #5219). + override fun isBusy(): Boolean = + bleManager.isActivationRunning || + (podStateManager.activationProgress != ActivationProgress.NOT_STARTED && + podStateManager.activationProgress.isBefore(ActivationProgress.COMPLETED)) + + override fun isConnected(): Boolean = + podStateManager.ltk == null || + podStateManager.bluetoothConnectionState == O5PodStateManager.BluetoothConnectionState.CONNECTED + + override fun isConnecting(): Boolean = stopConnecting != null + + override fun isHandshakeInProgress(): Boolean = + stopConnecting != null && + podStateManager.bluetoothConnectionState == O5PodStateManager.BluetoothConnectionState.CONNECTED + + override fun finishHandshaking() {} + + override fun connect(reason: String) { + aapsLogger.info(LTag.PUMP, "O5 connect reason=$reason") + podStateManager.bluetoothConnectionState = O5PodStateManager.BluetoothConnectionState.CONNECTING + synchronized(this) { + stopConnecting?.let { + aapsLogger.warn(LTag.PUMP, "O5 already connecting: $it") + return + } + stopConnecting = CountDownLatch(1) + } + thread(start = true, name = "O5ConnectionThread") { + try { + stopConnecting?.let { latch -> + bleManager.connect(latch).ignoreElements().blockingAwait() + } + } catch (e: Exception) { + aapsLogger.info(LTag.PUMPCOMM, "O5 connect error=$e") + } finally { + synchronized(this) { stopConnecting = null } + } + } + } + + override fun disconnect(reason: String) { + aapsLogger.info(LTag.PUMP, "O5 disconnect reason=$reason") + if (bleManager.isActivationRunning) { + // The activation uses the BLE link outside the queue. Closing it here breaks the pairing (Dash #5219). + aapsLogger.info(LTag.PUMP, "O5 disconnect ignored, pod activation is running") + return + } + stopConnecting?.countDown() + bleManager.disconnect(false) + } + + override fun stopConnecting() { + aapsLogger.info(LTag.PUMP, "O5 stopConnecting") + stopConnecting?.countDown() + bleManager.disconnect(true) + } + + + override suspend fun getPumpStatus(reason: String) { + aapsLogger.debug(LTag.PUMP, "O5 getPumpStatus reason=$reason") + if (podStateManager.ltk == null) { + return + } + try { + doseMutex.withLock { + try { + fetchStatus().blockingAwait() + reconcilePendingDoseLocked() + } finally { + // Alarm responses update pod state before the command reports an error. + checkPodKaput() + } + updateAlertConfiguration() + } + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error in O5 getPumpStatus", e) + } + syncPumpFlows() + } + + /** + * Posts a user-facing [NotificationId.OMNIPOD_POD_FAULT] alert (with sound) plus a + * [PumpSync.insertAnnouncement] entry the first time [O5PodStateManager.alarmType] + * is seen non-null, mirroring Dash's `OmnipodDashPumpPlugin.checkPodKaput()` handling - + * without this, a faulted O5 pod only shows CRITICAL status on + * the Omnipod overview screen with no system notification/sound, so a fault could go + * unnoticed if the user isn't actively looking at that screen. + * [O5PodStateManager.alarmSynced] makes this idempotent across repeated status polls of the same fault. + * If the fault code cannot be read, the notification still warns the user, but the + * announcement stays pending until a later status read provides the fault details. + * Activation timeout can be recorded directly from the pod status. + * + * Called by [checkPodKaput], like Dash's stopped-pod handling. The + * notification is skipped (but the announcement/sync flag are not) if a pod + * deactivation is already queued, since the user is already acting on the fault. + * + * Internal (rather than private) to allow unit testing within this module, without + * needing to drive [getPumpStatus]'s full status-poll chain. + */ + internal suspend fun checkPodFault() { + if (podStateManager.alarmSynced) return + if (!podStateManager.isPodKaput && podStateManager.alarmType == null) return + + if (podStateManager.alarmType == null) { + try { + fetchAlarmStatus().blockingAwait() + } catch (e: Exception) { + aapsLogger.warn(LTag.PUMP, "O5 could not read the alarm status page; fault announcement remains pending: ${e.message}") + } + } + + val description = podFaultDescription() + ?: podStateManager.podStatus?.toString() + ?: return + + if (!commandQueue.isCustomCommandInQueue(CommandDeactivatePod::class)) { + notificationManager.post( + NotificationId.OMNIPOD_POD_FAULT, + description, + sound = AlarmSound.BOLUS_ERROR + ) + } + if (podStateManager.alarmType == null && !podStateManager.isPodActivationTimeExceeded) return + pumpSync.insertAnnouncement( + error = description, + pumpId = System.currentTimeMillis(), + pumpType = PumpType.OMNIPOD_5, + pumpSerial = serialNumber() + ) + podStateManager.alarmSynced = true + } + + private fun podFaultDescription(): String? = + podStateManager.alarmType?.let { alarm -> + listOfNotNull( + rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, alarm.code, alarm.toString()), + podStateManager.pdmRef?.let { rh.gs(R.string.omnipod_common_pdm_ref, it) } + ).joinToString("\n") + } ?: if (podStateManager.isPodActivationTimeExceeded) { + rh.gs(R.string.omnipod_common_error_pod_fault_activation_time_exceeded) + } else { + null + } + + /** Keeps a failed command failed even if saving its fault announcement also fails. */ + private fun reportPodFault(): String? { + try { + runBlocking { checkPodFault() } + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "O5 could not save the pod fault announcement; it remains pending", e) + } + return podFaultDescription() + } + + private fun handleCommandFailure(@StringRes fallbackMessage: Int): PumpEnactResult { + val faultDescription = reportPodFault() + return pumpEnactResultProvider.get().success(false).enacted(false) + .comment(faultDescription ?: rh.gs(fallbackMessage)) + } + + /** + * Reads status page 2, the pod's fault detail, to learn *why* it faulted. Mirrors the Dash + * driver, which requests this page explicitly - the pod never volunteers it. + */ + private fun fetchAlarmStatus(): Completable = Completable.defer { + val cmd = GetStatusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setStatusResponseType(ResponseType.StatusResponseType.ALARM_STATUS) + .build() + bleManager.sendCommand(cmd, AlarmStatusResponse::class).ignoreElements() + } + + private fun ensureConnected(): Completable = Completable.defer { + bleManager.connect().ignoreElements() + } + + private fun fetchStatus(): Completable = ensureConnected().andThen(Completable.defer { + val cmd = GetStatusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements() + }) + .andThen(Completable.defer { fetchActivationTimeIfNeeded() }) + .andThen(Completable.defer { fetchTriggeredAlertsIfNeeded() }) + + /** + * Status pages 5/1 carry diagnostic data only relevant once something's actually + * wrong or alerting - fetched conditionally, on top of the default status poll + * above, rather than on every 15s poll. State is populated as a side effect of + * [O5BleManager.sendCommand] via `O5BleManagerImpl.onResponse`, + * same as every other response type, so nothing further is done with the result + * here - see [O5PodStateManager.podActivatedAt]/[O5PodStateManager.triggeredAlertTimes]. + */ + private fun fetchActivationTimeIfNeeded(): Completable { + if (podStateManager.alarmType == null || podStateManager.podActivatedAt != null) return Completable.complete() + val cmd = GetStatusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setStatusResponseType(ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_5) + .build() + return bleManager.sendCommand(cmd, PodInfoActivationTimeResponse::class).ignoreElements() + } + + private fun fetchTriggeredAlertsIfNeeded(): Completable { + if (podStateManager.activeAlerts?.isNotEmpty() != true) return Completable.complete() + val cmd = GetStatusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setStatusResponseType(ResponseType.StatusResponseType.STATUS_RESPONSE_PAGE_1) + .build() + return bleManager.sendCommand(cmd, PodInfoTriggeredAlertsResponse::class).ignoreElements() + } + + /** + * Resolves a [O5PodStateManager.pendingDoseCommand] left over from a dose-affecting + * call whose BLE response never arrived - see this class's doc comment. Called after + * every successful status read, so an uncertain outcome is recovered automatically + * rather than only on the next user-triggered action. + * + * Decides in the same order OmnipodKit's `PodCommsSession.recoverUnacknowledgedCommand` + * does: + * 1. **Authoritative** - the pod reports the sequence number of the last programming + * command it accepted ([O5PodStateManager.sequenceNumberOfLastProgrammingCommand]). + * If it equals the number this dose was sent with, the pod definitely got it. + * 2. **Heuristic fallback** - otherwise, a *positive* sign of the delivery actually + * running counts as confirmation ([confirmedByDeliveryStatus]). + * 3. A different sequence can reject an unaccepted command only if no bolus stop + * has since replaced it. Otherwise the outcome stays unknown and blocks dosing. + * + * Step 3 is why the sequence number matters. With only the delivery-status heuristic, an + * uncertain bolus that the pod never received looks identical to one that completed - both + * report "not currently bolusing" - and the old code resolved that ambiguity by assuming + * delivery, crediting `requestedUnits - bolusPulsesRemaining` as insulin that was never + * given. That inflates IOB and suppresses later dosing. + */ + internal suspend fun reconcilePendingDose() = doseMutex.withLock { + reconcilePendingDoseLocked() + } + + private suspend fun reconcilePendingDoseLocked() { + var pending = podStateManager.pendingDoseCommand ?: return + val status = podStateManager.deliveryStatus ?: return + if (status == DeliveryStatus.UNKNOWN) return + val podSequence = podStateManager.sequenceNumberOfLastProgrammingCommand + val sentSequence = pending.sequenceNumber + val acceptedByPod = pending.confirmedByStatus || pending.bolusCancelRequested != true && podSequence != null && sentSequence != null && + (podSequence.toInt() and 0x0f) == (sentSequence.toInt() and 0x0f) + + val confirmedByStatus = confirmedByDeliveryStatus(pending) + if (!acceptedByPod && !confirmedByStatus) { + val canReject = pending.type != O5PodStateManager.PendingDoseType.BOLUS || pending.bolusCancelRequested == false + if (sentSequence != null && podSequence != null && canReject) { + aapsLogger.info( + LTag.PUMP, + "O5 pending ${pending.type} was not received by the pod " + + "(sent sequence $sentSequence, pod's last programming sequence $podSequence) - recording no delivery" + ) + if (pending.type == O5PodStateManager.PendingDoseType.BOLUS && pending.bolusRecordExpected) { + pumpSync.syncBolusWithPumpId( + timestamp = pending.startedAt, + amount = PumpInsulin(0.0), + type = pending.bolusType ?: BS.Type.NORMAL, + pumpId = pending.historyId ?: pending.startedAt, + pumpType = PumpType.OMNIPOD_5, + pumpSerial = serialNumber() + ) + } + pending.historyId?.let { + history.markSendingFailure(it).andThen(history.markFailure(it)).blockingAwait() + } + podStateManager.pendingDoseCommand = null + return + } + return + } + if (!pending.confirmedByStatus) { + pending = pending.copy(confirmedByStatus = true) + podStateManager.pendingDoseCommand = pending + } + + when (pending.type) { + O5PodStateManager.PendingDoseType.BOLUS -> + if (!status.bolusDeliveringActive() && (status.basalActive() || status.tempBasalActive() || status.suspended())) { + val deliveredPulses = pending.deliveredBolusPulses(podSequence, status, podStateManager.bolusPulsesRemaining) ?: return + val deliveredUnits = deliveredPulses * PodConstants.POD_PULSE_BOLUS_UNITS + finalizeBolus(pending, deliveredUnits) + } + + O5PodStateManager.PendingDoseType.TEMP_BASAL_START -> confirmTempBasal(pending) + + O5PodStateManager.PendingDoseType.TEMP_BASAL_CANCEL -> + if (podStateManager.deliveryStatus?.tempBasalActive() != true) { + syncTempBasalCancelled(pending.startedAt, pending.historyId ?: pending.startedAt) + markDoseSuccess(pending) + podStateManager.pendingDoseCommand = null + } + + O5PodStateManager.PendingDoseType.BASAL_PROGRAM -> + if (status.basalActive()) { + val program = pending.requestedBasalProgram ?: return + podStateManager.basalProgram = program + onBasalProgramConfirmed(pending.startedAt, pending.historyId ?: pending.startedAt, pending.basalTimeZone) + markDoseSuccess(pending) + podStateManager.pendingDoseCommand = null + } + } + } + + private fun markDoseSuccess(pending: O5PodStateManager.PendingDoseCommand) { + pending.historyId?.let { history.markSent(it).andThen(history.markSuccess(it)).blockingAwait() } + } + + private suspend fun confirmTempBasal(pending: O5PodStateManager.PendingDoseCommand) { + val rate = pending.requestedRate ?: return + val duration = pending.requestedDurationMinutes ?: return + val running = pending.startedAt + duration * 60_000L > System.currentTimeMillis() && + podStateManager.deliveryStatus?.tempBasalActive() == true + pumpSync.syncTemporaryBasalWithPumpId( + timestamp = pending.startedAt, + rate = PumpRate(rate), + duration = T.mins(duration.toLong()).msecs(), + isAbsolute = true, + type = pending.tempBasalType ?: PumpSync.TemporaryBasalType.NORMAL, + pumpId = pending.historyId ?: pending.startedAt, + pumpType = PumpType.OMNIPOD_5, + pumpSerial = serialNumber() + ) + podStateManager.activeTempBasalStartTime = pending.startedAt.takeIf { running } + podStateManager.activeTempBasalRate = rate.takeIf { running } + podStateManager.activeTempBasalDurationMinutes = duration.takeIf { running } + markDoseSuccess(pending) + notificationManager.dismiss(NotificationId.OMNIPOD_TBR_ALERTS) + podStateManager.pendingDoseCommand = null + } + + /** Tells AAPS that the temp basal (or the zero "suspended" temp basal) running at + * [timestamp] has ended. */ + private suspend fun syncTempBasalStopped(timestamp: Long, endPumpId: Long) { + val stopped = pumpSync.syncStopTemporaryBasalWithPumpId( + timestamp = timestamp, + endPumpId = endPumpId, + pumpType = PumpType.OMNIPOD_5, + pumpSerial = serialNumber() + ) + aapsLogger.info(LTag.PUMP, "O5 syncStopTemporaryBasalWithPumpId ret=$stopped endPumpId=$endPumpId") + } + + /** + * After a confirmed temp basal cancel. If the pod is suspended, scheduled basal does not + * come back, so the zero "suspended" temp basal in AAPS must stay and nothing is stopped. + */ + private suspend fun syncTempBasalCancelled(timestamp: Long, endPumpId: Long) { + if (podStateManager.deliveryStatus?.suspended() == true) { + aapsLogger.info(LTag.PUMP, "O5 temp basal cancelled while delivery is suspended - keeping the zero temp basal") + return + } + podStateManager.activeTempBasalStartTime = null + podStateManager.activeTempBasalRate = null + podStateManager.activeTempBasalDurationMinutes = null + syncTempBasalStopped(timestamp, endPumpId) + } + + /** + * A basal program always suspends delivery first, so any temp basal on the pod is gone and + * scheduled basal runs again. Records that in AAPS and in the pod state, and stores the pod + * clock's time zone, because the same command sets the pod clock. Mirrors Dash's + * `SET_BASAL_PROFILE` / `RESUME_DELIVERY` confirmation handling. + */ + private suspend fun onBasalProgramConfirmed(timestamp: Long, endPumpId: Long, timeZone: PodTimeZone?) { + podStateManager.deliverySuspended = false + podStateManager.activeTempBasalStartTime = null + podStateManager.activeTempBasalRate = null + podStateManager.activeTempBasalDurationMinutes = null + timeZone?.let { podStateManager.confirmTimeZone(it) } ?: podStateManager.updateTimeZone() + podStateManager.timeChangeInProgress = false + syncTempBasalStopped(timestamp, endPumpId) + notificationManager.dismiss(NotificationId.OMNIPOD_POD_SUSPENDED) + notificationManager.dismiss(NotificationId.FAILED_UPDATE_PROFILE) + notificationManager.dismiss(NotificationId.OMNIPOD_TBR_ALERTS) + notificationManager.dismiss(NotificationId.OMNIPOD_TIME_OUT_OF_SYNC) + } + + /** + * Clears the way for a new dose-affecting command, returning false if it must not be sent. + * + * A [O5PodStateManager.pendingDoseCommand] means an earlier dose may or may not have + * reached the pod. Issuing another one on top of that risks stacking a second dose onto a + * first that did land, so this first tries to settle the question the same way OmnipodKit's + * `PodCommsSession.tryToResolvePendingCommand` does - read status, reconcile, and proceed + * only if the pending marker actually cleared. + * + * Note this resolves rather than merely refuses: in the ordinary case where the pod is + * reachable again, the status read settles the outcome and the new command goes ahead + * normally. Refusal is reserved for a pod that still cannot be reached or whose status + * leaves the earlier dose undecided. + * + * Deliberately *not* applied to pod deactivation. Blocking a user from taking a pod off + * because the driver is unsure about a temp basal is the wrong trade, and deactivation + * never sets a pending marker of its own. + */ + private suspend fun pendingDoseResolved(): Boolean { + if (podStateManager.pendingDoseCommand == null) return true + return try { + fetchStatus().blockingAwait() + reconcilePendingDoseLocked() + val resolved = podStateManager.pendingDoseCommand == null + if (!resolved) { + aapsLogger.warn(LTag.PUMP, "O5 refusing new dose command: an earlier dose is still unresolved after a status read") + } + resolved + } catch (e: Exception) { + aapsLogger.warn(LTag.PUMP, "O5 refusing new dose command: could not read status to resolve the pending dose: ${e.message}") + reportPodFault() + false + } + } + + private fun unresolvedDoseResult(): PumpEnactResult = + pumpEnactResultProvider.get().success(false).enacted(false) + .comment(podFaultDescription() ?: rh.gs(R.string.omnipod_5_error_unresolved_dose_pending)) + + /** + * Whether the pod's delivery status positively shows [pending] took effect - the fallback + * for when the sequence number cannot decide it (mirrors OmnipodKit's + * `checkCommandAgainstStatus`). + * + * Deliberately only ever answers true on a *positive* observation. "Not currently + * bolusing" is not evidence a bolus happened, so [O5PodStateManager.PendingDoseType.BOLUS] + * uses a running bolus as confirmation. Scheduled basal alone cannot prove a new + * basal program, since the old program may still be running. + */ + private fun confirmedByDeliveryStatus(pending: O5PodStateManager.PendingDoseCommand): Boolean { + val status = podStateManager.deliveryStatus ?: return false + return when (pending.type) { + O5PodStateManager.PendingDoseType.BOLUS -> status.bolusDeliveringActive() + O5PodStateManager.PendingDoseType.TEMP_BASAL_START -> status.tempBasalActive() + O5PodStateManager.PendingDoseType.TEMP_BASAL_CANCEL -> !status.tempBasalActive() + O5PodStateManager.PendingDoseType.BASAL_PROGRAM -> false + } + } + + private fun pendingDoseAccepted(): Boolean { + val pending = podStateManager.pendingDoseCommand ?: return false + val sequence = pending.sequenceNumber + val podSequence = podStateManager.sequenceNumberOfLastProgrammingCommand + return pending.confirmedByStatus || confirmedByDeliveryStatus(pending) || + sequence != null && podSequence != null && (sequence.toInt() and 0x0f) == (podSequence.toInt() and 0x0f) + } + + private fun requirePodId(): Int = + podStateManager.podId?.toInt() ?: throw IllegalStateException("O5 pod not paired") + + + override suspend fun setNewBasalProfile(profile: PumpProfile): PumpEnactResult = + setNewBasalProfile(profile, OmnipodCommandType.SET_BASAL_PROFILE) + + private suspend fun setNewBasalProfile( + profile: PumpProfile, + historyType: OmnipodCommandType = OmnipodCommandType.SET_BASAL_PROFILE + ): PumpEnactResult = doseMutex.withLock { setNewBasalProfileLocked(profile, historyType) } + + private suspend fun setNewBasalProfileLocked( + profile: PumpProfile, + historyType: OmnipodCommandType + ): PumpEnactResult { + if (podStateManager.ltk == null) { + // Pod not paired yet - deferred, not an actual write, same as Dash. enacted=false => no PROFILE_SET_OK. + return pumpEnactResultProvider.get().success(true).enacted(false) + } + if (!pendingDoseResolved()) return unresolvedDoseResult() + val basalProgram = mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5) + val historyId = history.createRecord( + commandType = historyType, + initialResult = InitialResult.NOT_SENT, + basalProfileRecord = BasalValuesRecord(profile.getBasalValues().toList()) + ).blockingGet() + return try { + if (podStateManager.deliveryStatus?.suspended() != true) { + val basalBeeps = preferences.get(OmnipodBooleanPreferenceKey.BasalBeepsEnabled) + val cmd = SuspendDeliveryCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setBeepType(if (basalBeeps) BeepType.LONG_SINGLE_BEEP else BeepType.SILENT) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + podStateManager.deliverySuspended = true + podStateManager.suspendAlertsEnabled = true + syncZeroTempBasal(serialNumber()) + } + + val currentTime = Date() + podStateManager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BASAL_PROGRAM, + startedAt = System.currentTimeMillis(), + sequenceNumber = podStateManager.msgSequenceNumber.toShort(), + historyId = historyId, + requestedBasalProgram = basalProgram, + basalTimeZone = PodTimeZone.now(currentTime.time) + ) + armStatusChecker() + val basalBeeps = preferences.get(OmnipodBooleanPreferenceKey.BasalBeepsEnabled) + val cmd = ProgramBasalCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setBasalProgram(basalProgram) + .setProgramReminder(ProgramReminder(atStart = basalBeeps, atEnd = false, atInterval = 0)) + .setCurrentTime(currentTime) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + val accepted = pendingDoseAccepted() + reconcilePendingDoseLocked() + if (!accepted || podStateManager.pendingDoseCommand != null) return unresolvedDoseResult() + // PROFILE_SET_OK is posted centrally (CommandQueue) on success && enacted. + disableSuspendAlerts() + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + history.markSendingFailure(historyId).andThen(history.markFailure(historyId)).blockingAwait() + aapsLogger.error(LTag.PUMP, "Error in O5 setNewBasalProfile", e) + notifyUncertain(NotificationId.FAILED_UPDATE_PROFILE, rh.gs(R.string.omnipod_5_error_setting_basal_profile_might_have_failed)) + handleCommandFailure(R.string.omnipod_5_error_setting_basal_profile_might_have_failed) + } + } + + override fun isThisProfileSet(profile: PumpProfile): Boolean { + if (podStateManager.ltk == null) return true + if (podStateManager.deliverySuspended) return false + return mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5) == podStateManager.basalProgram + } + + /** The confirmed basal program as hourly rates, including the pod's 0.05 U/h rounding. */ + override fun deliveredBasal(): List? = + if (!podStateManager.isActivationCompleted) null + else podStateManager.basalProgram?.hourlyRates()?.mapIndexed { hour, rate -> Profile.ProfileValue(T.hours(hour.toLong()).secs().toInt(), rate) } + + override fun clearAllTables() = o5HistoryDatabase.clearAllTables() + + + private val _lastDataTime = MutableStateFlow(0L) + override val lastDataTime: StateFlow = _lastDataTime + + private val _lastBolusTime = MutableStateFlow(null) + override val lastBolusTime: StateFlow = _lastBolusTime + + private val _lastBolusAmount = MutableStateFlow(null) + override val lastBolusAmount: StateFlow = _lastBolusAmount + + override val baseBasalRate: PumpRate + get() { + val rate = if (podStateManager.alarmType != null) 0.0 + else podStateManager.basalProgram?.rateAt(System.currentTimeMillis(), podStateManager.timeZoneOffset) ?: 0.0 + return PumpRate(rate) + } + + private val _reservoirLevel = MutableStateFlow(PumpInsulin(0.0)) + override val reservoirLevel: StateFlow = _reservoirLevel + + override val batteryLevel: StateFlow = MutableStateFlow(null) + + private fun syncPumpFlows() { + _lastDataTime.value = podStateManager.lastStatusResponseReceived ?: 0L + _lastBolusTime.value = podStateManager.lastBolusStartTime + _lastBolusAmount.value = podStateManager.lastBolusRequestedUnits?.let { PumpInsulin(it) } + _reservoirLevel.value = PumpInsulin( + podStateManager.reservoirPulsesRemaining?.let { it * PodConstants.POD_PULSE_BOLUS_UNITS } + ?: RESERVOIR_OVER_50_UNITS_DEFAULT + ) + } + + + override suspend fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = + doseMutex.withLock { deliverTreatmentLocked(detailedBolusInfo) } + + private suspend fun deliverTreatmentLocked(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { + require(detailedBolusInfo.carbs == 0.0) { detailedBolusInfo.toString() } + require(detailedBolusInfo.insulin > 0) { detailedBolusInfo.toString() } + + if (!pendingDoseResolved()) { + return pumpEnactResultProvider.get().success(false).enacted(false).bolusDelivered(0.0) + .comment(rh.gs(R.string.omnipod_5_error_unresolved_dose_pending)) + } + try { + bolusDeliveryInProgress = true + syncPumpFlows() + val requestedUnits = detailedBolusInfo.insulin + if (requestedUnits > reservoirLevel.value.cU) { + return pumpEnactResultProvider.get().success(false).enacted(false).bolusDelivered(0.0) + .comment(rh.gs(R.string.omnipod_5_error_not_enough_insulin)) + } + if (podStateManager.deliveryStatus?.bolusDeliveringActive() == true) { + return pumpEnactResultProvider.get().success(false).enacted(false).bolusDelivered(0.0) + .comment(rh.gs(R.string.omnipod_5_error_bolus_already_in_progress)) + } + + val bolusBeepsKey = if (detailedBolusInfo.bolusType == BS.Type.SMB) OmnipodBooleanPreferenceKey.SmbBeepsEnabled + else OmnipodBooleanPreferenceKey.BolusBeepsEnabled + val bolusBeeps = preferences.get(bolusBeepsKey) + val startedAt = System.currentTimeMillis() + val historyId = history.createRecord( + commandType = OmnipodCommandType.SET_BOLUS, + date = startedAt, + initialResult = InitialResult.NOT_SENT, + bolusRecord = BolusRecord( + requestedUnits, + BolusType.fromBolusInfoBolusType(detailedBolusInfo.bolusType) + ) + ).blockingGet() + + val pendingDose = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = requestedUnits, + bolusType = detailedBolusInfo.bolusType, + startedAt = startedAt, + sequenceNumber = podStateManager.msgSequenceNumber.toShort(), + historyId = historyId + ) + podStateManager.pendingDoseCommand = pendingDose + + val cmd = ProgramBolusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setNumberOfUnits(requestedUnits) + .setDelayBetweenPulsesInEighthSeconds(BOLUS_DELAY_BETWEEN_PULSES_EIGHTH_SECONDS) + .setProgramReminder(ProgramReminder(atStart = bolusBeeps, atEnd = bolusBeeps, atInterval = 0)) + .setO5BolusInfo(mealUnits = 0.0, correctionUnits = requestedUnits) + .build() + + var commandMayHaveBeenSent = false + var commandSentAt: TimeMark? = null + val ret = try { + bleManager.sendCommand(cmd, DefaultStatusResponse::class) + .doOnNext { rememberBolusAcceptance(startedAt, it) } + .filter { it.isCommandSent() } + .doOnNext { + commandSentAt = bolusTimeSource.markNow() + commandMayHaveBeenSent = true + markBolusRecordExpected(startedAt) + } + .concatMapCompletable { + rxCompletable(Dispatchers.IO) { + pumpSync.syncBolusWithPumpId( + timestamp = startedAt, + amount = PumpInsulin(requestedUnits), + type = detailedBolusInfo.bolusType, + pumpId = pendingDose.historyId ?: startedAt, + pumpType = PumpType.OMNIPOD_5, + pumpSerial = serialNumber() + ) + } + } + .blockingAwait() + armStatusChecker() + val completion = waitForBolusDeliveryToComplete( + requestedUnits, + requireNotNull(commandSentAt) { "Missing bolus command send time" } + ).blockingGet() + val deliveredUnits = completion.deliveredUnits + val accepted = podStateManager.pendingDoseCommand?.confirmedByStatus == true + if (deliveredUnits != null && accepted) { + finalizeBolus(podStateManager.pendingDoseCommand ?: pendingDose, deliveredUnits) + pumpEnactResultProvider.get().success(true).enacted(true).bolusDelivered(deliveredUnits) + } else { + pumpEnactResultProvider.get().success(true).enacted(true).bolusDelivered(requestedUnits) + .comment(rh.gs(R.string.omnipod_5_error_bolus_delivery_status_uncertain)) + } + } catch (throwable: Throwable) { + aapsLogger.error(LTag.PUMP, "O5 deliverTreatment error: $throwable") + if (!commandMayHaveBeenSent && podStateManager.pendingDoseCommand?.confirmedByStatus != true) { + podStateManager.pendingDoseCommand = null + pendingDose.historyId?.let { + history.markSendingFailure(it).andThen(history.markFailure(it)).blockingAwait() + } + } else { + if (bolusCanceled) { + try { + cancelBolus().blockingAwait() + checkPodKaput() + } catch (e: Exception) { + aapsLogger.warn(LTag.PUMP, "O5 bolus stop outcome is unknown: ${e.message}") + } + } + armStatusChecker() + } + val faultDescription = reportPodFault() + pumpEnactResultProvider.get().success(bolusCanceled).enacted(false) + .comment(faultDescription ?: rh.gs(R.string.omnipod_5_error_bolus_delivery_status_uncertain)) + } + + if (detailedBolusInfo.bolusType == BS.Type.SMB && podStateManager.pendingDoseCommand != null) { + notifyUncertain(NotificationId.OMNIPOD_UNCERTAIN_SMB, rh.gs(R.string.omnipod_5_error_uncertain_smb, requestedUnits)) + } else if (podStateManager.pendingDoseCommand != null && podFaultDescription() == null) { + notifyUncertain(NotificationId.OMNIPOD_POD_FAULT, rh.gs(R.string.omnipod_5_error_bolus_delivery_status_uncertain)) + } + return ret + } finally { + bolusCanceled = false + bolusDeliveryInProgress = false + } + } + + private data class BolusCompletion(val deliveredUnits: Double?) + + private fun waitForBolusDeliveryToComplete( + requestedUnits: Double, + commandSentAt: TimeMark + ): Single = Single.defer { + val totalPulses = (requestedUnits / PodConstants.POD_PULSE_BOLUS_UNITS).roundToLong() + val pulseIntervalMs = BOLUS_DELAY_BETWEEN_PULSES_EIGHTH_SECONDS.toLong() * 1000 / 8 + val deliveryDurationMs = totalPulses * pulseIntervalMs + val confirmationTimeMs = deliveryDurationMs + BOLUS_CONFIRMATION_MARGIN_MS + + // This is an estimate from the send time, not live feedback from the pod. + while (!bolusCanceled) { + val elapsedMs = commandSentAt.elapsedNow().inWholeMilliseconds + val estimatedPulses = (elapsedMs / pulseIntervalMs).coerceIn(0L, totalPulses) + val delivered = PumpInsulin(estimatedPulses * PodConstants.POD_PULSE_BOLUS_UNITS) + + if (elapsedMs < deliveryDurationMs) { + bolusProgressData.updateProgress(delivered = delivered) + } else { + bolusProgressData.updateProgress( + percent = 99, + status = TextRef.AndroidRes(O5R.string.omnipod_5_checking_delivery_status), + delivered = delivered + ) + } + + val remainingMs = confirmationTimeMs - elapsedMs + if (remainingMs <= 0L) break + bolusSleep(minOf(1000L, remainingMs)) + } + + repeat(BOLUS_RETRIES) { + val cmd = if (bolusCanceled) cancelBolus() else fetchStatus() + try { + cmd.andThen(rxCompletable(Dispatchers.IO) { checkPodKaput() }).blockingAwait() + } catch (e: Exception) { + aapsLogger.debug(LTag.PUMP, "waitForBolusDeliveryToComplete errorGettingStatus=$e") + reportPodFault() + bolusSleep(BOLUS_RETRY_INTERVAL_MS) + return@repeat + } + val bolusActive = podStateManager.deliveryStatus?.bolusDeliveringActive() == true + if (bolusActive) { + val remainingPulses = podStateManager.bolusPulsesRemaining + if (remainingPulses == null) { + bolusSleep(BOLUS_RETRY_INTERVAL_MS) + return@repeat + } + val remainingUnits = remainingPulses.toInt() * PodConstants.POD_PULSE_BOLUS_UNITS + val delivered = requestedUnits - remainingUnits + val percent = (delivered / requestedUnits) * 100 + bolusProgressData.updateProgress(percent.toInt().coerceIn(0, 99)) + val sleepSeconds = if (bolusCanceled) BOLUS_RETRY_INTERVAL_MS / 1000 + else ceil(remainingUnits / PodConstants.POD_PULSE_BOLUS_UNITS).toLong() * 2 + 3 + bolusSleep(sleepSeconds * 1000) + } else { + val deliveredPulses = podStateManager.pendingDoseCommand?.deliveredBolusPulses( + podStateManager.sequenceNumberOfLastProgrammingCommand, + podStateManager.deliveryStatus, + podStateManager.bolusPulsesRemaining + ) + if (deliveredPulses != null) { + return@defer Single.just(BolusCompletion(deliveredPulses * PodConstants.POD_PULSE_BOLUS_UNITS)) + } + } + } + Single.just(BolusCompletion(null)) + } + + private fun markBolusRecordExpected(startedAt: Long) { + val pending = podStateManager.pendingDoseCommand ?: return + if (pending.type == O5PodStateManager.PendingDoseType.BOLUS && pending.startedAt == startedAt) { + podStateManager.pendingDoseCommand = pending.copy(bolusRecordExpected = true) + } + } + + private fun rememberBolusAcceptance(startedAt: Long, event: PodEvent) { + val response = (event as? PodEvent.ResponseReceived)?.response as? DefaultStatusResponse ?: return + val pending = podStateManager.pendingDoseCommand ?: return + if (pending.startedAt != startedAt) return + val confirmed = pending.withPodAcceptance(response.sequenceNumberOfLastProgrammingCommand, response.deliveryStatus) + if (confirmed != pending) { + podStateManager.pendingDoseCommand = confirmed + } + } + + private suspend fun finalizeBolus(pending: O5PodStateManager.PendingDoseCommand, deliveredUnits: Double) { + val finalUnits = deliveredUnits.coerceIn(0.0, pending.requestedUnits ?: deliveredUnits) + pending.historyId?.let { + history.markSent(it) + .andThen(history.setTotalAmountDelivered(it, finalUnits)) + .andThen(history.markSuccess(it)) + .blockingAwait() + } + if (!pending.isBasalCorrection) { + pumpSync.syncBolusWithPumpId( + timestamp = pending.startedAt, + amount = PumpInsulin(finalUnits), + type = pending.bolusType ?: BS.Type.NORMAL, + pumpId = pending.historyId ?: pending.startedAt, + pumpType = PumpType.OMNIPOD_5, + pumpSerial = serialNumber() + ) + } + if (pending.bolusCancelSequenceNumber?.let { + (it.toInt() and 0x0f) == podStateManager.sequenceNumberOfLastProgrammingCommand?.toInt()?.and(0x0f) + } == true + ) { + pending.bolusCancelHistoryId?.let { + history.markSent(it).andThen(history.markSuccess(it)).blockingAwait() + } + } + val deliveredPulses = if (pending.isBasalCorrection) { + null + } else { + Math.round(finalUnits / PodConstants.POD_PULSE_BOLUS_UNITS).toShort() + } + podStateManager.completeBolus( + startedAt = pending.startedAt, + requestedUnits = pending.requestedUnits ?: finalUnits, + deliveredUnits = finalUnits, + deliveredPulses = deliveredPulses + ) + } + + private fun cancelBolus(): Completable = ensureConnected().andThen(Completable.defer { + val bolusBeeps = preferences.get(OmnipodBooleanPreferenceKey.BolusBeepsEnabled) + val historyId = podStateManager.pendingDoseCommand?.bolusCancelHistoryId ?: history.createRecord( + commandType = OmnipodCommandType.CANCEL_BOLUS, + initialResult = InitialResult.NOT_SENT + ).blockingGet() + val cmd = StopDeliveryCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setDeliveryType(StopDeliveryCommand.DeliveryType.BOLUS) + .setBeepType(if (bolusBeeps) BeepType.LONG_SINGLE_BEEP else BeepType.SILENT) + .build() + podStateManager.pendingDoseCommand?.let { pending -> + podStateManager.pendingDoseCommand = pending.copy( + bolusCancelRequested = true, + bolusCancelSequenceNumber = podStateManager.msgSequenceNumber.toShort(), + bolusCancelHistoryId = historyId + ) + } + bleManager.sendCommand(cmd, DefaultStatusResponse::class) + .doOnNext { event -> + val response = (event as? PodEvent.ResponseReceived)?.response as? DefaultStatusResponse + if (response != null && (response.sequenceNumberOfLastProgrammingCommand.toInt() and 0x0f) == + podStateManager.pendingDoseCommand?.bolusCancelSequenceNumber?.toInt()?.and(0x0f) + ) { + history.markSent(historyId).andThen(history.markSuccess(historyId)).blockingAwait() + } + } + .ignoreElements() + .doOnError { + history.markSendingFailure(historyId).andThen(history.markFailure(historyId)).blockingAwait() + } + }) + + override fun stopBolusDelivering() { + aapsLogger.info(LTag.PUMP, "O5 stopBolusDelivering called") + if (bolusDeliveryInProgress) { + bolusCanceled = true + } + } + + + override suspend fun setTempBasalAbsolute( + absoluteRate: Double, + durationInMinutes: Int, + enforceNew: Boolean, + tbrType: PumpSync.TemporaryBasalType + ): PumpEnactResult = doseMutex.withLock { + setTempBasalAbsoluteLocked(absoluteRate, durationInMinutes, enforceNew, tbrType) + } + + private suspend fun setTempBasalAbsoluteLocked( + absoluteRate: Double, + durationInMinutes: Int, + enforceNew: Boolean, + tbrType: PumpSync.TemporaryBasalType + ): PumpEnactResult { + aapsLogger.info(LTag.PUMP, "O5 setTempBasalAbsolute: rate=$absoluteRate U/h duration=$durationInMinutes min enforce=$enforceNew type=$tbrType") + if (!pendingDoseResolved()) return unresolvedDoseResult() + var historyId: Long? = null + return try { + if (podStateManager.deliveryStatus?.tempBasalActive() == true) { + cancelActiveTempBasal() + } + val tempBasalBeeps = preferences.get(OmnipodBooleanPreferenceKey.TbrBeepsEnabled) + val startedAt = System.currentTimeMillis() + historyId = history.createRecord( + commandType = OmnipodCommandType.SET_TEMPORARY_BASAL, + date = startedAt, + initialResult = InitialResult.NOT_SENT, + tempBasalRecord = TempBasalRecord(durationInMinutes, absoluteRate) + ).blockingGet() + podStateManager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_START, + requestedRate = absoluteRate, + requestedDurationMinutes = durationInMinutes.toShort(), + startedAt = startedAt, + sequenceNumber = podStateManager.msgSequenceNumber.toShort(), + historyId = historyId, + tempBasalType = tbrType + ) + armStatusChecker() + val cmd = ProgramTempBasalCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setProgramReminder(ProgramReminder(atStart = tempBasalBeeps, atEnd = tempBasalBeeps, atInterval = 0)) + .setRateInUnitsPerHour(absoluteRate) + .setDurationInMinutes(durationInMinutes.toShort()) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + + val accepted = pendingDoseAccepted() + reconcilePendingDoseLocked() + if (!accepted || podStateManager.pendingDoseCommand != null) return unresolvedDoseResult() + queueBasalCorrectionIfNeeded() + pumpEnactResultProvider.get().success(true).enacted(true).isPercent(false).absolute(absoluteRate).duration(durationInMinutes) + } catch (e: Exception) { + historyId?.let { history.markSendingFailure(it).andThen(history.markFailure(it)).blockingAwait() } + aapsLogger.error(LTag.PUMP, "Error in O5 setTempBasalAbsolute", e) + notifyUncertain(NotificationId.OMNIPOD_TBR_ALERTS, rh.gs(R.string.omnipod_5_error_setting_temp_basal_might_have_failed)) + handleCommandFailure(R.string.omnipod_5_error_setting_temp_basal_might_have_failed) + } + } + + override suspend fun setTempBasalPercent(percent: Int, durationInMinutes: Int, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = + error("Pump doesn't support percent basal rate") + + override suspend fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = + doseMutex.withLock { + cancelTempBasalLocked(enforceNew) + } + + private suspend fun cancelTempBasalLocked(enforceNew: Boolean): PumpEnactResult { + if (!pendingDoseResolved()) return unresolvedDoseResult() + if (podStateManager.deliveryStatus?.tempBasalActive() != true && pumpSync.expectedPumpState().temporaryBasal == null) { + return pumpEnactResultProvider.get().success(true).enacted(false) + } + return try { + cancelActiveTempBasal() + queueBasalCorrectionIfNeeded() + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error in O5 cancelTempBasal", e) + notifyUncertain(NotificationId.OMNIPOD_TBR_ALERTS, rh.gs(R.string.omnipod_5_error_cancel_temp_basal_result_is_uncertain)) + handleCommandFailure(R.string.omnipod_5_error_cancel_temp_basal_result_is_uncertain) + } + } + + private suspend fun cancelActiveTempBasal() { + val startedAt = System.currentTimeMillis() + val historyId = history.createRecord( + commandType = OmnipodCommandType.CANCEL_TEMPORARY_BASAL, + date = startedAt, + initialResult = InitialResult.NOT_SENT + ).blockingGet() + podStateManager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_CANCEL, + startedAt = startedAt, + sequenceNumber = podStateManager.msgSequenceNumber.toShort(), + historyId = historyId + ) + armStatusChecker() + val tempBasalBeeps = preferences.get(OmnipodBooleanPreferenceKey.TbrBeepsEnabled) + val cmd = StopDeliveryCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setDeliveryType(StopDeliveryCommand.DeliveryType.TEMP_BASAL) + .setBeepType(if (tempBasalBeeps) BeepType.LONG_SINGLE_BEEP else BeepType.SILENT) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + history.markSent(historyId).andThen(history.markSuccess(historyId)).blockingAwait() + syncTempBasalCancelled(startedAt, historyId) + notificationManager.dismiss(NotificationId.OMNIPOD_TBR_ALERTS) + podStateManager.pendingDoseCommand = null + } + + override suspend fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = + pumpEnactResultProvider.get().success(false).enacted(false) + .comment(rh.gs(R.string.omnipod_5_error_extended_bolus_not_supported)) + + override suspend fun cancelExtendedBolus(): PumpEnactResult = + pumpEnactResultProvider.get().success(false).enacted(false) + .comment(rh.gs(R.string.omnipod_5_error_extended_bolus_not_supported)) + + override val pumpDescription: PumpDescription = Companion.pumpDescription + override fun manufacturer(): ManufacturerType = ManufacturerType.Insulet + override fun model(): PumpType = pumpDescription.pumpType + override fun serialNumber(): String = podStateManager.podId?.toString() ?: UNPAIRED_SERIAL + override val isFakingTempsByExtendedBoluses: Boolean = false + + override suspend fun loadTDDs(): PumpEnactResult = + pumpEnactResultProvider.get().success(false).enacted(false) + .comment(rh.gs(R.string.omnipod_5_error_tdd_not_supported)) + + override fun canHandleDST(): Boolean = !isInitialized() || podStateManager.timeZoneOffset != null + + override fun isLoopInvocationAllowed(value: Constraint): Constraint { + if (isInitialized() && (timeCorrectionNeeded() || timeChangeHandler.isInProgress())) { + value.set(false, rh.gs(R.string.omnipod_common_loop_waiting_for_time_update), this) + } + return value + } + + override fun executeCustomCommand(customCommand: CustomCommand): PumpEnactResult = + when (customCommand) { + is CommandPairNewPod -> pairNewPod() + is CommandDeactivatePod -> deactivatePod() + is CommandSilenceAlerts -> silenceAlerts() + is CommandResumeDelivery -> runBlocking { resumeOrHandleTimeChange() } + is CommandSuspendDelivery -> suspendDelivery() + is CommandPlayTestBeep -> playTestBeep() + is CommandHandleTimeChange -> runBlocking { handleTimeChange(customCommand.requestedByUser) } + is CommandUpdateAlertConfiguration -> updateAlertConfiguration() + is CommandDisableSuspendAlerts -> disableSuspendAlerts() + is CommandDeliverBasalCorrection -> deliverBasalCorrection() + else -> { + aapsLogger.warn(LTag.PUMP, "Unsupported custom command: " + customCommand.javaClass.name) + pumpEnactResultProvider.get().success(false).enacted(false).comment( + rh.gs(R.string.omnipod_common_error_unsupported_custom_command, customCommand.javaClass.name) + ) + } + } + + private fun pairNewPod(): PumpEnactResult = + try { + bleManager.pairNewPod().ignoreElements().blockingAwait() + history.recordSuccess(OmnipodCommandType.INITIALIZE_POD) + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error pairing new O5 pod", e) + history.recordFailure(OmnipodCommandType.INITIALIZE_POD) + handleCommandFailure(R.string.omnipod_common_error_failed_to_initialize_pod) + } + + private fun deactivatePod(): PumpEnactResult = + try { + val cmd = DeactivateCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + val podSerial = serialNumber() + reportPodFault() + bleManager.removeBond() + podStateManager.reset() + history.recordSuccess(OmnipodCommandType.DEACTIVATE_POD) + notificationManager.dismiss(NotificationId.OMNIPOD_POD_FAULT) + try { + runBlocking { recordNoDelivery(pumpSync.expectedPumpState(), podSerial) } + } catch (e: Exception) { + aapsLogger.warn(LTag.PUMP, "O5 could not record zero delivery after deactivation: $e") + } + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error deactivating O5 pod", e) + handleCommandFailure(R.string.omnipod_common_error_failed_to_deactivate_pod) + } + + private fun silenceAlerts(): PumpEnactResult = + podStateManager.activeAlerts?.let { alerts -> + try { + val cmd = SilenceAlertsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setAlertTypes(alerts) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + history.recordSuccess(OmnipodCommandType.ACKNOWLEDGE_ALERTS) + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error silencing O5 alerts", e) + handleCommandFailure(R.string.omnipod_common_error_failed_to_silence_alerts) + } + } ?: pumpEnactResultProvider.get().success(false).enacted(false).comment(rh.gs(R.string.omnipod_5_error_no_active_alerts)) + + private fun suspendDelivery(): PumpEnactResult = + try { + podStateManager.timeChangeInProgress = false + val basalBeeps = preferences.get(OmnipodBooleanPreferenceKey.BasalBeepsEnabled) + val cmd = SuspendDeliveryCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setBeepType(if (basalBeeps) BeepType.LONG_SINGLE_BEEP else BeepType.SILENT) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + podStateManager.deliverySuspended = true + podStateManager.suspendAlertsEnabled = true + history.recordSuccess(OmnipodCommandType.SUSPEND_DELIVERY) + runBlocking { syncZeroTempBasal(serialNumber()) } + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error suspending O5 delivery", e) + handleCommandFailure(R.string.omnipod_common_error_failed_to_suspend_delivery) + } + + private fun playTestBeep(): PumpEnactResult = + try { + val silentReminder = ProgramReminder(atStart = false, atEnd = false, atInterval = 0) + val cmd = ProgramBeepsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setImmediateBeepType(BeepType.LONG_SINGLE_BEEP) + .setBasalReminder(silentReminder) + .setTempBasalReminder(silentReminder) + .setBolusReminder(silentReminder) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + history.recordSuccess(OmnipodCommandType.PLAY_TEST_BEEP) + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error playing O5 test beep", e) + handleCommandFailure(R.string.omnipod_common_error_failed_to_play_test_beep) + } + + /** Resuming sends the current basal program, which also sets the pod's local time. */ + private suspend fun resumeOrHandleTimeChange(): PumpEnactResult = + pumpSync.expectedPumpState().profile?.let { setNewBasalProfile(it, OmnipodCommandType.RESUME_DELIVERY) } + ?: pumpEnactResultProvider.get().success(false).enacted(false).comment(rh.gs(R.string.omnipod_5_error_no_active_profile)) + + private suspend fun handleTimeChange(requestedByUser: Boolean): PumpEnactResult = doseMutex.withLock { + if (!requestedByUser) { + fetchStatus().blockingAwait() + reconcilePendingDoseLocked() + if (!timeCorrectionNeeded() || !canCorrectTime()) { + aapsLogger.info(LTag.PUMP, "Deferring automatic O5 time update") + return@withLock pumpEnactResultProvider.get().success(true).enacted(false) + } + } + pumpSync.expectedPumpState().profile?.let { + // Persisted before suspending, so a crash mid-correction can still resume it after restart + // even though the pod now looks suspended. Any active temp basal is lost here, the same way + // the Medtrum driver accepts one may be cancelled by its own time update: the loop sets a + // new one next cycle, this driver does not reconstruct the old one. + podStateManager.timeChangeInProgress = true + setNewBasalProfileLocked(it, OmnipodCommandType.SET_TIME) + } ?: pumpEnactResultProvider.get().success(false).enacted(false).comment(rh.gs(R.string.omnipod_5_error_no_active_profile)) + } + + override suspend fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { + aapsLogger.info(LTag.PUMP, "Checking O5 pod time after ${timeChangeType.name}") + checkTimeChange() + } + + private fun timeCorrectionNeeded(): Boolean = OmnipodTimeChange.needsCorrection( + podStateManager.timeZoneOffset, PodTimeZone.now().offset, podStateManager.timeChangeInProgress + ) + + private fun canCorrectTime(): Boolean = OmnipodTimeChange.canProgram( + isInitialized(), + podStateManager.deliverySuspended, + bolusDeliveryInProgress || podStateManager.deliveryStatus?.bolusDeliveringActive() == true, + podStateManager.pendingDoseCommand != null, + podStateManager.timeChangeInProgress + ) + + @VisibleForTesting + internal suspend fun checkTimeChange() { + if (!timeCorrectionNeeded()) { + // Also covers a manual command having fixed it outside this polling loop. + timeChangeHandler.resetFailureAlert() + return + } + if (!canCorrectTime() || bleManager.isActivationRunning || + commandQueue.isCustomCommandInQueue(CommandHandleTimeChange::class) || + commandQueue.isCustomCommandInQueue(CommandSuspendDelivery::class) || + commandQueue.isCustomCommandInQueue(CommandDeactivatePod::class) || + !timeChangeHandler.tryStart(System.nanoTime() / 1000000) + ) return + try { + val result = commandQueue.customCommand(CommandHandleTimeChange(false)) + if (!result.success) { + notifyTimeChangeFailure(result.comment) + } else if (!timeCorrectionNeeded()) { + timeChangeHandler.resetFailureAlert() + notificationManager.dismiss(NotificationId.PUMP_TIMEZONE_UPDATE_FAILED) + notificationManager.post( + NotificationId.TIME_OR_TIMEZONE_CHANGE, + TextRef.AndroidRes(R.string.omnipod_common_confirmation_time_on_pod_updated), + validMinutes = 60 + ) + } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + notifyTimeChangeFailure(e.message) + } finally { + timeChangeHandler.finish(System.nanoTime() / 1000000) + } + } + + private fun notifyTimeChangeFailure(reason: String?) { + aapsLogger.error(LTag.PUMP, "Automatic O5 time update failed: $reason") + // Only the first of a run of retries sounds an alarm; repeated retries every minute would + // otherwise alarm continuously while the pod is unreachable. + notificationManager.post( + NotificationId.PUMP_TIMEZONE_UPDATE_FAILED, + TextRef.AndroidRes(R.string.omnipod_common_automatic_time_update_failed), + level = NotificationLevel.IMPORTANT, + sound = if (timeChangeHandler.shouldSoundOnFailure()) AlarmSound.BOLUS_ERROR else null + ) + } + + private fun notifyUncertain(id: NotificationId, message: String) { + if (podStateManager.pendingDoseCommand != null) { + notificationManager.post(id, message, sound = AlarmSound.BOLUS_ERROR) + } + } + + + /** Re-pushes expiration/low-reservoir alert config to the pod when preferences have + * changed since the last successful push - safe to call often (see [getPumpStatus]'s + * call site), since it's a no-op whenever nothing has changed. Mirrors Dash's + * updateAlertConfiguration(), minus its isPodRunning/expiry-negative guards (O5's + * activationProgress check below covers the same intent). */ + private fun updateAlertConfiguration(): PumpEnactResult { + val expirationReminderEnabled = preferences.get(OmnipodBooleanPreferenceKey.ExpirationReminder) + val expirationReminderHours = preferences.get(OmnipodIntPreferenceKey.ExpirationReminderHours) + val expirationAlarmEnabled = preferences.get(OmnipodBooleanPreferenceKey.ExpirationAlarm) + val expirationAlarmHours = preferences.get(OmnipodIntPreferenceKey.ExpirationAlarmHours) + val lowReservoirAlertEnabled = preferences.get(OmnipodBooleanPreferenceKey.LowReservoirAlert) + val lowReservoirAlertUnits = preferences.get(OmnipodIntPreferenceKey.LowReservoirAlertUnits) + val current = O5PodStateManager.SyncedAlertSettings( + expirationReminderEnabled, expirationReminderHours, + expirationAlarmEnabled, expirationAlarmHours, + lowReservoirAlertEnabled, lowReservoirAlertUnits + ) + + if (podStateManager.syncedAlertSettings == current) { + return pumpEnactResultProvider.get().success(true).enacted(false) + } + if (podStateManager.activationProgress != ActivationProgress.COMPLETED) { + return pumpEnactResultProvider.get().success(true).enacted(false) + } + + return try { + val alerts = buildO5ExpirationAlerts(podStateManager, preferences, aapsLogger) + AlertConfiguration( + AlertType.LOW_RESERVOIR, + enabled = lowReservoirAlertEnabled, + durationInMinutes = 0, + autoOff = false, + AlertTrigger.ReservoirVolumeTrigger((lowReservoirAlertUnits * 10).toShort()), + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX + ) + val cmd = ProgramAlertsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setAlertConfigurations(alerts) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + podStateManager.syncedAlertSettings = current + history.recordSuccess(OmnipodCommandType.CONFIGURE_ALERTS) + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error updating O5 alert configuration", e) + handleCommandFailure(R.string.omnipod_5_error_failed_to_update_alert_configuration) + } + } + + /** Silences the pod's SUSPEND_ENDED alert once delivery has resumed - see + * [podStateManager]'s suspendAlertsEnabled doc comment. */ + private fun disableSuspendAlerts(): PumpEnactResult { + if (!podStateManager.suspendAlertsEnabled) { + return pumpEnactResultProvider.get().success(true).enacted(false) + } + return try { + val cmd = ProgramAlertsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setAlertConfigurations( + listOf( + AlertConfiguration( + AlertType.SUSPEND_ENDED, enabled = false, durationInMinutes = 0, autoOff = false, + AlertTrigger.TimerTrigger(0), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.EVERY_MINUTE_AND_EVERY_15_MIN + ) + ) + ) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().blockingAwait() + podStateManager.suspendAlertsEnabled = false + history.recordSuccess(OmnipodCommandType.CONFIGURE_ALERTS) + pumpEnactResultProvider.get().success(true).enacted(true) + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "Error disabling O5 suspend alerts", e) + handleCommandFailure(R.string.omnipod_5_error_failed_to_update_alert_configuration) + } + } + + + /** + * Uses the Dash correction thresholds, cooldown and drift reset. + * A zero temp basal blocks correction, except within 5 minutes of a bolus (same as Dash). + * Check only after a temp basal change is finished, not between cancel and replacement. + * While a dose is pending, its bolus pulses may not be counted yet, so basal looks too high. + * Drift is not read or reset then. + */ + private fun needsBasalCorrection(): Boolean { + val correctionThreshold = -PodConstants.POD_PULSE_BOLUS_UNITS / 2 + + if (podStateManager.activationProgress != ActivationProgress.COMPLETED) return false + if (podStateManager.deliverySuspended || podStateManager.alarmType != null) return false + if (podStateManager.pendingDoseCommand != null) return false + + podStateManager.lastBasalCorrectionTime?.let { + if (System.currentTimeMillis() - it < 2 * 60 * 1000L) return false + } + + val drift = podStateManager.basalDrift + + if (drift >= PodConstants.POD_PULSE_BOLUS_UNITS * 2 || drift <= -PodConstants.POD_PULSE_BOLUS_UNITS * 2) { + aapsLogger.warn(LTag.PUMP, "Resetting O5 basal drift: drift=${"%.3f".format(drift)}U") + podStateManager.basalExpected = podStateManager.basalDelivered + return false + } + + if (drift > correctionThreshold) return false + + if (podStateManager.activeTempBasalRate == 0.0) { + val timeSinceLastBolus = podStateManager.lastBolusStartTime?.let { System.currentTimeMillis() - it } + if (timeSinceLastBolus == null || timeSinceLastBolus >= 5 * 60 * 1000L) return false + } + + return true + } + + /** + * Queues the correction after the current command, like Dash. The queued command + * checks the drift again before it sends anything. + */ + private fun queueBasalCorrectionIfNeeded() { + if (!commandQueue.isCustomCommandInQueue(CommandDeliverBasalCorrection::class) && needsBasalCorrection()) { + // Queue-worker deadlock guard - don't unwrap the .launch. See CommandQueue kdoc. + pluginScope.launch { commandQueue.customCommand(CommandDeliverBasalCorrection()) } + } + } + + /** Delivers a single POD_PULSE_BOLUS_UNITS (0.05U) correction bolus to true up basal + * drift - see [needsBasalCorrection]. Reuses [waitForBolusDeliveryToComplete] for the + * same progress-polling/confirmation logic a regular bolus uses. */ + private fun deliverBasalCorrection(): PumpEnactResult = runBlocking { + doseMutex.withLock { deliverBasalCorrectionLocked() } + } + + private fun deliverBasalCorrectionLocked(): PumpEnactResult { + if (podStateManager.pendingDoseCommand != null) { + aapsLogger.info(LTag.PUMP, "O5 basal correction skipped: an earlier dose is still unresolved") + return pumpEnactResultProvider.get().success(false).enacted(false) + } + if (!needsBasalCorrection()) { + aapsLogger.info(LTag.PUMP, "O5 basal correction no longer appropriate") + return pumpEnactResultProvider.get().success(true).enacted(false) + } + podStateManager.lastBasalCorrectionTime = System.currentTimeMillis() + + val requestedInsulinAmount = PodConstants.POD_PULSE_BOLUS_UNITS + syncPumpFlows() + if (requestedInsulinAmount > reservoirLevel.value.cU) { + aapsLogger.info(LTag.PUMP, "O5 basal correction skipped: not enough insulin in reservoir") + return pumpEnactResultProvider.get().success(false).enacted(false) + } + if (podStateManager.deliveryStatus?.bolusDeliveringActive() == true) { + aapsLogger.info(LTag.PUMP, "O5 basal correction skipped: bolus already in progress") + return pumpEnactResultProvider.get().success(false).enacted(false) + } + + var commandMayHaveBeenSent = false + var historyId: Long? = null + return try { + bolusDeliveryInProgress = true + podStateManager.basalCorrectionInProgress = true + aapsLogger.info(LTag.PUMP, "Delivering O5 basal correction") + + val startedAt = System.currentTimeMillis() + historyId = history.createRecord( + commandType = OmnipodCommandType.SET_BOLUS, + date = startedAt, + initialResult = InitialResult.NOT_SENT, + bolusRecord = BolusRecord(requestedInsulinAmount, BolusType.BASAL_CORRECTION) + ).blockingGet() + val pendingDose = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = requestedInsulinAmount, + bolusType = BS.Type.NORMAL, + startedAt = startedAt, + isBasalCorrection = true, + sequenceNumber = podStateManager.msgSequenceNumber.toShort(), + historyId = historyId + ) + podStateManager.pendingDoseCommand = pendingDose + + val cmd = ProgramBolusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(podStateManager.msgSequenceNumber.toShort()) + .setNonce(FIXED_NONCE) + .setNumberOfUnits(requestedInsulinAmount) + .setDelayBetweenPulsesInEighthSeconds(BOLUS_DELAY_BETWEEN_PULSES_EIGHTH_SECONDS) + .setProgramReminder(ProgramReminder(atStart = false, atEnd = false, atInterval = 0)) + .setO5BolusInfo(mealUnits = 0.0, correctionUnits = requestedInsulinAmount) + .build() + var commandSentAt: TimeMark? = null + bleManager.sendCommand(cmd, DefaultStatusResponse::class) + .doOnNext { rememberBolusAcceptance(startedAt, it) } + .filter { it.isCommandSent() } + .doOnNext { + commandSentAt = bolusTimeSource.markNow() + commandMayHaveBeenSent = true + markBolusRecordExpected(startedAt) + } + .ignoreElements() + .blockingAwait() + armStatusChecker() + val completion = waitForBolusDeliveryToComplete( + requestedInsulinAmount, + requireNotNull(commandSentAt) { "Missing bolus command send time" } + ).blockingGet() + val deliveredUnits = completion.deliveredUnits + if (deliveredUnits != null && podStateManager.pendingDoseCommand?.confirmedByStatus == true) { + runBlocking { finalizeBolus(podStateManager.pendingDoseCommand ?: pendingDose, deliveredUnits) } + aapsLogger.info(LTag.PUMP, "O5 basal correction delivered: $deliveredUnits U") + pumpEnactResultProvider.get().success(true).enacted(true).bolusDelivered(deliveredUnits) + } else { + pumpEnactResultProvider.get().success(true).enacted(true).bolusDelivered(requestedInsulinAmount) + .comment(rh.gs(R.string.omnipod_5_error_bolus_delivery_status_uncertain)) + } + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "O5 basal correction delivery failed", e) + if (!commandMayHaveBeenSent && podStateManager.pendingDoseCommand?.confirmedByStatus != true) { + podStateManager.pendingDoseCommand = null + historyId?.let { history.markSendingFailure(it).andThen(history.markFailure(it)).blockingAwait() } + } else { + armStatusChecker() + } + handleCommandFailure(R.string.omnipod_5_error_bolus_delivery_status_uncertain) + } finally { + bolusDeliveryInProgress = false + podStateManager.basalCorrectionInProgress = false + } + } + + override fun getPreferenceScreenContent() = PreferenceSubScreenDef( + key = "omnipod_5_settings", + titleResId = R.string.omnipod_5_name, + items = listOfNotNull( + PreferenceSubScreenDef( + key = "omnipod_5_beeps", + titleResId = R.string.omnipod_common_preferences_category_confirmation_beeps, + items = listOf( + OmnipodBooleanPreferenceKey.BolusBeepsEnabled, + OmnipodBooleanPreferenceKey.BasalBeepsEnabled, + OmnipodBooleanPreferenceKey.SmbBeepsEnabled, + OmnipodBooleanPreferenceKey.TbrBeepsEnabled + ) + ), + PreferenceSubScreenDef( + key = "omnipod_5_alerts", + titleResId = R.string.omnipod_common_preferences_category_alerts, + items = listOf( + OmnipodBooleanPreferenceKey.ExpirationReminder, + OmnipodIntPreferenceKey.ExpirationReminderHours, + OmnipodBooleanPreferenceKey.ExpirationAlarm, + OmnipodIntPreferenceKey.ExpirationAlarmHours, + OmnipodBooleanPreferenceKey.LowReservoirAlert, + OmnipodIntPreferenceKey.LowReservoirAlertUnits + ) + ), + PreferenceSubScreenDef( + key = "omnipod_5_notifications", + titleResId = R.string.omnipod_common_preferences_category_notifications, + items = listOf( + OmnipodBooleanPreferenceKey.SoundUncertainTbrNotification, + OmnipodBooleanPreferenceKey.SoundUncertainSmbNotification, + OmnipodBooleanPreferenceKey.SoundUncertainBolusNotification, + DashBooleanPreferenceKey.SoundDeliverySuspendedNotification + ) + ), + if (config.isEngineeringMode()) { + O5IntentKey.CertificateStore.withCompose( + ComposeScreenContent { onBack -> + O5CertificateStoreScreen( + rh = rh, + onBack = onBack, + ) + } + ) + } else { + null + } + ), + icon = pluginDescription.icon + ) + +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManager.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManager.kt new file mode 100644 index 000000000000..976536438128 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManager.kt @@ -0,0 +1,23 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm + +import app.aaps.pump.omnipod.common.bledriver.comm.OmnipodBleManager +import io.reactivex.rxjava3.core.Completable + +/** + * Omnipod 5 BLE manager with support for the O5-only AID setup command batch. + */ +interface O5BleManager : OmnipodBleManager { + + /** + * True while the activation wizard runs a step (pairing, prime, cannula insertion). The wizard + * talks to the pod outside the command queue, so the queue must not use or close the BLE link + * during this time (see Dash #5219). Only the wizard sets it, and it must clear it in a `finally`. + */ + var isActivationRunning: Boolean + + /** Sends the O5-only AID setup command batch (see [app.aaps.pump.omnipod.common + * .bledriver.pod.command.aid.O5AidSetupCommands]) over the already-established + * session. Must be called after [pairNewPod] completes and before any other + * activation command - see that object's class doc for why. */ + fun sendAidSetupCommands(): Completable +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManagerImpl.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManagerImpl.kt new file mode 100644 index 000000000000..02b4bc807164 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManagerImpl.kt @@ -0,0 +1,215 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.utils.toHex +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.SharedBleManager +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.FailedToConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.device.BleDeviceManager +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.session.BleConnection +import app.aaps.pump.omnipod.common.bledriver.comm.session.ConnectionWaitCondition +import app.aaps.pump.omnipod.common.bledriver.event.PodEvent +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.Response +import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.O5BleConnectionFactory +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5CertificateStore +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5LTKExchanger +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.command.aid.O5AidSetupCommands +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.security.SecureO5RegistrationStorage +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.PodTypeAwarePodScanner +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Observable +import io.reactivex.rxjava3.core.ObservableEmitter +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 + +@ContributesBinding(AppScope::class, binding = binding()) +@SingleIn(AppScope::class) +class O5BleManagerImpl @Inject constructor( + aapsLogger: AAPSLogger, + private val podState: O5PodStateManager, + private val config: Config, + private val context: Context, + private val bleConnectionFactory: O5BleConnectionFactory, + bleDeviceManager: BleDeviceManager, + secureO5RegistrationStorage: SecureO5RegistrationStorage, + private val p256KeyGenerator: P256KeyGenerator +) : SharedBleManager(aapsLogger, bleDeviceManager), O5BleManager { + + init { + secureO5RegistrationStorage.loadAndInstallAll() + } + + private val bluetoothAdapter: BluetoothAdapter? + get() = (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter + + override val bluetoothAddress: String? + get() = podState.bluetoothAddress + override val ltk: ByteArray? + get() = podState.ltk + override val ids: Ids + get() { + val controllerId = podState.controllerId + ?: throw FailedToConnectException("Missing controllerId, activate the O5 pod first") + val podId = podState.podId + ?: throw FailedToConnectException("Missing podId, activate the O5 pod first") + return Ids.forController(Id.fromLong(controllerId), Id.fromLong(podId)) + } + @Volatile override var isActivationRunning: Boolean = false + override val releaseBusyBeforeCompletion = true + override val connectionName = "O5 pod" + + override fun createConnection(podAddress: String): BleConnection = + bleConnectionFactory.createConnection(podAddress) + + override fun increaseEapAkaSequenceNumber(): ByteArray = podState.increaseEapAkaSequenceNumber() + + override fun updateEapAkaSequenceNumber(sequenceNumber: Long) { + podState.eapAkaSequenceNumber = sequenceNumber + } + + override fun commitEapAkaSequenceNumber() { + podState.commitEapAkaSequenceNumber() + } + + override fun recordSuccessfulConnection() { + podState.successfulConnections++ + } + + override fun onCommandSent() { + podState.increaseMessageSequenceNumber() + } + + override fun onResponseRead() { + podState.increaseMessageSequenceNumber() + } + + override fun onResponse(response: Response) { + when (response) { + is VersionResponse -> podState.updateFromVersionResponse(response) + is DefaultStatusResponse -> podState.updateFromDefaultStatusResponse(response) + is AlarmStatusResponse -> podState.updateFromAlarmStatusResponse(response) + is SetUniqueIdResponse -> podState.updateFromSetUniqueIdResponse(response) + is PodInfoActivationTimeResponse -> podState.updateFromActivationTimeResponse(response) + is PodInfoTriggeredAlertsResponse -> podState.updateFromTriggeredAlertsResponse(response) + else -> Unit + } + } + + override fun pairNewPod(): Observable = Observable.create { emitter -> + acquireBusy() + try { + if (podState.ltk == null && podState.bluetoothAddress != null) { + aapsLogger.info(LTag.PUMPBTCOMM, "Forgetting saved O5 address ${podState.bluetoothAddress} of an unpaired pod") + podState.bluetoothAddress = null + } + var lastError: Exception? = null + for (attempt in 0..1) { + try { + pairNewPodAttempt(emitter) + emitter.onComplete() + return@create + } catch (ex: Exception) { + lastError = ex + disconnect(true) + if (attempt == 0 && podState.podId != null && !podState.isPodKaput) Thread.sleep(3_000) else break + } + } + throw requireNotNull(lastError) + } catch (ex: Exception) { + aapsLogger.error(LTag.PUMPBTCOMM, "O5 pod activation failed", ex) + disconnect(true) + emitter.tryOnError(ex) + } finally { + releaseBusy() + } + } + + private fun pairNewPodAttempt(emitter: ObservableEmitter) { + if (podState.ltk != null) { + emitter.onNext(PodEvent.AlreadyPaired) + val address = podState.bluetoothAddress + ?: throw FailedToConnectException("Missing bluetoothAddress, activate the pod first") + emitter.onNext(PodEvent.BluetoothConnecting) + val conn = createConnection(address) + connection = conn + conn.connect(ConnectionWaitCondition(timeoutMs = BleConnection.DEFAULT_CONNECT_TIMEOUT_MS)) + emitter.onNext(PodEvent.BluetoothConnected(address)) + emitter.onNext(PodEvent.EstablishingSession) + establishSession(podState.msgSequenceNumber) + emitter.onNext(PodEvent.Connected) + return + } + + val controllerId = podState.controllerId + ?.takeIf(O5RegistrationData::contains) + ?: O5RegistrationData.pickControllerId + if (controllerId == 0L) { + throw PairingException("No O5 registration data available") + } + val certStore = O5CertificateStore(aapsLogger, p256KeyGenerator, controllerId) + val address = podState.bluetoothAddress ?: run { + val adapter = bluetoothAdapter ?: throw ConnectException("Bluetooth not available") + emitter.onNext(PodEvent.Scanning) + PodTypeAwarePodScanner(aapsLogger, adapter).scanForPod(PodType.OMNIPOD_5).address + .also { podState.bluetoothAddress = it } + } + val podIdLong = podState.podId + ?.takeIf { podState.controllerId == controllerId } + ?: podState.nextPodId + ?.takeIf { O5IdRotation.controllerIdForPodId(it) == O5IdRotation.controllerIdForPodId(controllerId) } + ?: O5IdRotation.firstPodId(controllerId) + podState.controllerId = controllerId + podState.podId = podIdLong + podState.nextPodId = null + + emitter.onNext(PodEvent.BluetoothConnecting) + val conn = bleConnectionFactory.createConnection(address, controllerId) + connection = conn + conn.connect(ConnectionWaitCondition(timeoutMs = BleConnection.DEFAULT_CONNECT_TIMEOUT_MS)) + emitter.onNext(PodEvent.BluetoothConnected(address)) + emitter.onNext(PodEvent.Pairing) + val messageIO = conn.msgIO ?: throw ConnectException("Connection lost") + val myId = Id.fromLong(certStore.controllerId) + val podId = Id.fromLong(podIdLong) + val pairResult = O5LTKExchanger(aapsLogger, messageIO, certStore, myId, podId).o5NegotiateLTK() + emitter.onNext(PodEvent.Paired(podId)) + podState.updateFromPairing(certStore.controllerId, podId.toLong(), pairResult) + if (config.DEBUG) aapsLogger.info(LTag.PUMPCOMM, "Got O5 LTK: ${pairResult.ltk.toHex()}") + emitter.onNext(PodEvent.EstablishingSession) + establishSession(pairResult.msgSeq) + emitter.onNext(PodEvent.Connected) + } + + override fun sendAidSetupCommands(): Completable = Completable.fromAction { + acquireBusy() + try { + O5AidSetupCommands.send(assertSessionEstablished()) + } catch (ex: Exception) { + disconnect(false) + throw ex + } finally { + releaseBusy() + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5IdRotation.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5IdRotation.kt new file mode 100644 index 000000000000..0c46666eca30 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5IdRotation.kt @@ -0,0 +1,21 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm + +object O5IdRotation { + + private const val CONTROLLER_ID_BIT_MASK: Long = 0b11L + + fun controllerIdForPodId(podId: Long): Long = + podId and (CONTROLLER_ID_BIT_MASK.inv()) + + fun firstPodId(controllerId: Long): Long = + controllerIdForPodId(controllerId) + 1 + + fun nextPodId(lastPodId: Long): Long { + val low2Bits = lastPodId and CONTROLLER_ID_BIT_MASK + return if (low2Bits == CONTROLLER_ID_BIT_MASK) { + controllerIdForPodId(lastPodId) + 1 + } else { + lastPodId + 1 + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5PairingCoordinator.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5PairingCoordinator.kt new file mode 100644 index 000000000000..1b5689d32e5f --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5PairingCoordinator.kt @@ -0,0 +1,111 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.session.BleConnection +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.O5BleConnectionFactory +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5CertificateStore +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5LTKExchanger +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.common.bledriver.comm.pair.PairResult +import app.aaps.pump.omnipod.common.bledriver.comm.session.ConnectionWaitCondition +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.PodTypeAwarePodScanner +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** + * The O5 pairing entry point: scans for a pairable Omnipod 5 pod, connects to it, runs + * [O5LTKExchanger]'s pairing message sequence, then establishes the post-pairing encrypted + * session - parallel to [OmnipodDashBleManagerImpl.pairNewPod] rather than a modification + * of it. + * + * Requires real registration data to already be installed in [O5RegistrationData] (see + * that class's doc comment) - without it, [pairNewPod] fails immediately with a + * [PairingException] rather than attempting a pairing that could never succeed. + */ +@SingleIn(AppScope::class) +class O5PairingCoordinator @Inject constructor( + private val aapsLogger: AAPSLogger, + private val config: Config, + private val context: Context, + private val podState: O5PodStateManager, + private val bleConnectionFactory: O5BleConnectionFactory, + private val p256KeyGenerator: P256KeyGenerator +) { + + private val bluetoothAdapter: BluetoothAdapter? + get() = (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter + + /** + * Pairs a new Omnipod 5 pod and establishes the initial encrypted session with it. + * Returns the negotiated [PairResult] on success. + * + * @throws PairingException if no O5 registration data is available, or if pairing fails. + * @throws ConnectException if the BLE connection is lost partway through. + */ + fun pairNewPod(): PairResult { + aapsLogger.info(LTag.PUMPBTCOMM, "Starting new O5 pod activation") + + val adapter = bluetoothAdapter ?: throw ConnectException("Bluetooth not available") + + val controllerId = O5RegistrationData.pickControllerId + if (controllerId == 0L) { + throw PairingException( + "No O5 registration data available - cannot pair an Omnipod 5 pod without " + + "real Insulet-issued controller credentials (see O5RegistrationData)" + ) + } + val certStore = O5CertificateStore(aapsLogger, p256KeyGenerator, controllerId) + + val scanner = PodTypeAwarePodScanner(aapsLogger, adapter) + val discovered = scanner.scanForPod(PodType.OMNIPOD_5) + podState.bluetoothAddress = discovered.address + aapsLogger.info(LTag.PUMPBTCOMM, "Found O5 pod at ${discovered.address}, connecting") + + val conn = bleConnectionFactory.createConnection(discovered.address, controllerId) + conn.connect(ConnectionWaitCondition(timeoutMs = BleConnection.DEFAULT_CONNECT_TIMEOUT_MS)) + + val mIO = conn.msgIO ?: throw ConnectException("Connection lost before pairing could start") + + val myId = Id.fromLong(certStore.controllerId) + val podId = myId.increment() + + aapsLogger.info(LTag.PUMPBTCOMM, "Pairing with predicted podId=$podId, myId=$myId") + val ltkExchanger = O5LTKExchanger(aapsLogger, mIO, certStore, myId, podId) + val pairResult = ltkExchanger.o5NegotiateLTK() + + podState.updateFromPairing(certStore.controllerId, podId.toLong(), pairResult) + aapsLogger.info(LTag.PUMPBTCOMM, "O5 pairing succeeded, establishing session") + + val ids = Ids.forController(myId, podId) + val eapSqn = podState.increaseEapAkaSequenceNumber() + val resyncSqn = conn.establishSession(pairResult.ltk, pairResult.msgSeq, ids, eapSqn) + if (resyncSqn != null) { + aapsLogger.info(LTag.PUMPBTCOMM, "O5 EAP AKA resynchronization on first connect: $resyncSqn") + podState.eapAkaSequenceNumber = resyncSqn.toLong() + val secondAttemptSqn = conn.establishSession( + pairResult.ltk, pairResult.msgSeq, ids, podState.increaseEapAkaSequenceNumber() + ) + if (secondAttemptSqn != null) { + throw PairingException("Received EAP AKA resynchronization for the second time") + } + } + podState.commitEapAkaSequenceNumber() + podState.successfulConnections++ + + aapsLogger.info(LTag.PUMPBTCOMM, "O5 pod paired and session established") + return pairResult + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/O5BleConnectionFactory.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/O5BleConnectionFactory.kt new file mode 100644 index 000000000000..eab4ef19ac24 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/O5BleConnectionFactory.kt @@ -0,0 +1,50 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.session.BleConnection +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.session.BleConnectionFactory +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.session.O5Connection +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** + * Creates [O5Connection] instances, parallel to Dash's [LegacyBleConnectionFactory] + * rather than a modification of it (that factory is hardwired to Dash's + * [app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManager]). + */ +@SingleIn(AppScope::class) +class O5BleConnectionFactory @Inject constructor( + private val context: Context, + private val aapsLogger: AAPSLogger, + private val config: Config, + private val podState: O5PodStateManager, + private val p256KeyGenerator: P256KeyGenerator +) : BleConnectionFactory { + + private val bluetoothAdapter: BluetoothAdapter? + get() = (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter + + override fun createConnection(podAddress: String): BleConnection = createConnection(podAddress, null) + + /** + * O5-specific overload used during new pod activation, where the controller id is known + * from the picked credentials but not yet stored in [O5PodStateManager] (that only + * happens after pairing succeeds). The id is passed straight into the 'hello' handshake + * so it matches the source id used in the pairing messages. For reconnects to an already + * paired pod, use [createConnection] with no controller id - [O5Connection] resolves it + * from [O5PodStateManager.controllerId]. + */ + fun createConnection(podAddress: String, controllerId: Long?): BleConnection { + val adapter = bluetoothAdapter ?: throw ConnectException("Bluetooth not available") + val podDevice = adapter.getRemoteDevice(podAddress) + return O5Connection(podDevice, aapsLogger, config, context, podState, p256KeyGenerator, controllerId) + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/session/O5Connection.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/session/O5Connection.kt new file mode 100644 index 000000000000..527d64662590 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/session/O5Connection.kt @@ -0,0 +1,94 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.session + +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt +import app.aaps.pump.omnipod.common.bledriver.comm.legacy.io.CmdBleIO +import app.aaps.pump.omnipod.common.bledriver.comm.legacy.session.SharedBleConnection +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.pump.omnipod.common.bledriver.comm.session.Session +import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionKeys +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5CertificateStore +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator + +class O5Connection( + podDevice: BluetoothDevice, + aapsLogger: AAPSLogger, + config: Config, + context: Context, + private val podState: O5PodStateManager, + private val p256KeyGenerator: P256KeyGenerator, + private val pairingControllerId: Long? = null +) : SharedBleConnection(podDevice, aapsLogger, config, context) { + + override val podType = PodType.OMNIPOD_5 + + override fun recordConnectionAttempt() { + podState.connectionAttempts++ + } + + override fun updateConnectionState(state: LifecycleState) { + podState.bluetoothConnectionState = when (state) { + LifecycleState.CONNECTING -> O5PodStateManager.BluetoothConnectionState.CONNECTING + LifecycleState.CONNECTED -> O5PodStateManager.BluetoothConnectionState.CONNECTED + LifecycleState.DISCONNECTED -> O5PodStateManager.BluetoothConnectionState.DISCONNECTED + } + } + + override fun connectGatt(): BluetoothGatt? = + podDevice.connectGatt(context, false, bleCommCallbacks, BluetoothDevice.TRANSPORT_LE) + + override fun prepareGatt(gatt: BluetoothGatt) { + if (!gatt.requestMtu(REQUESTED_MTU)) { + aapsLogger.warn(LTag.PUMPBTCOMM, "O5 requestMtu($REQUESTED_MTU) call returned false - continuing with default MTU") + return + } + val completed = bleCommCallbacks.waitForMtuChange(MTU_NEGOTIATION_TIMEOUT_MS) + val mtu = bleCommCallbacks.negotiatedMtu + if (!completed) { + aapsLogger.warn(LTag.PUMPBTCOMM, "O5 MTU negotiation timed out - continuing with MTU=$mtu") + } else { + aapsLogger.debug(LTag.PUMPBTCOMM, "O5 MTU negotiated: $mtu") + } + if (mtu < MIN_REQUIRED_MTU) { + aapsLogger.warn(LTag.PUMPBTCOMM, "O5 negotiated MTU=$mtu is below the required $MIN_REQUIRED_MTU") + } + } + + override fun hello(cmdBleIO: CmdBleIO) { + val controllerId = pairingControllerId ?: podState.controllerId + if (controllerId == null) { + aapsLogger.warn(LTag.PUMPBTCOMM, "O5 hello handshake has no controllerId; using the default") + cmdBleIO.hello() + } else { + cmdBleIO.hello(controllerId.toInt()) + } + } + + override fun createSession(messageIO: MessageIO, ids: Ids, keys: SessionKeys, enDecrypt: EnDecrypt): Session { + val controllerId = requireNotNull(podState.controllerId) { + "Missing controllerId, cannot establish a signed O5 session" + } + return Session( + aapsLogger, + messageIO, + ids, + sessionKeys = keys, + enDecrypt = enDecrypt, + commandSigner = O5CertificateStore(aapsLogger, p256KeyGenerator, controllerId) + ) + } + + companion object { + const val REQUESTED_MTU = 512 + const val MIN_REQUIRED_MTU = 247 + const val MTU_NEGOTIATION_TIMEOUT_MS = 5_000L + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5CertificateStore.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5CertificateStore.kt new file mode 100644 index 000000000000..3d9fcf605987 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5CertificateStore.kt @@ -0,0 +1,324 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.utils.toHex +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.common.bledriver.comm.pair.CommandSigner +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256Codec +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import java.math.BigInteger +import java.security.Signature +import java.security.interfaces.ECPublicKey +import java.util.Base64 + +/** + * Manages the PKI material needed for Omnipod 5 pairing and pod command authentication. + * Key/certificate data comes from [O5RegistrationData] - swap the underlying registration + * to use different registration data. + * + * Ported from OmnipodKit's O5CertificateStore.swift (loopandlearn/OmnipodKit). Two + * deliberate differences from the Swift original, both explained inline below: + * 1. Certificate field extraction (public key + serial number) is ported as a faithful, + * hand-rolled byte-level parser rather than switched to a full ASN.1 library, so every + * line here could be verified against real, JDK-generated X.509 certificates without + * depending on an external library this environment couldn't compile-check. + * 2. DER signature encoding/decoding is similarly hand-rolled rather than delegated to a + * library, for the same verifiability reason. + * + * @throws PairingException if no registration data is available for [controllerId], or if + * the registration's stored public key doesn't match the one derived from its private key + * (which would indicate corrupted or tampered registration data). + */ +class O5CertificateStore( + private val aapsLogger: AAPSLogger, + private val p256KeyGenerator: P256KeyGenerator, + controllerId: Long +) : CommandSigner { + + val registration: O5RegistrationData = + O5RegistrationData.get(controllerId) + ?: throw PairingException("No O5 registration data found for controller id 0x%08X".format(controllerId)) + + val controllerId: Long get() = registration.controllerId + val controllerIdData: ByteArray get() = registration.controllerIdData + + private val signingPrivateKeyRaw: ByteArray = registration.privateKey + + /** The secondary P-256 signing key's raw (65-byte, uncompressed) public key. */ + val signingPublicKeyRaw: ByteArray + + init { + require(signingPrivateKeyRaw.size == P256Codec.SCALAR_LENGTH_BYTES) { + "Secondary key scalar must be exactly ${P256Codec.SCALAR_LENGTH_BYTES} bytes" + } + + signingPublicKeyRaw = p256KeyGenerator.publicFromPrivate(signingPrivateKeyRaw) + + if (!signingPublicKeyRaw.contentEquals(registration.publicKey)) { + aapsLogger.error( + LTag.PUMPBTCOMM, + "O5 signing public key does NOT match expected secondary public key for controller 0x%08X" + .format(controllerId) + ) + throw PairingException( + "O5 signing public key mismatch for controller id 0x%08X".format(controllerId) + ) + } + + val tlsCert = registration.tlsCertificate + val intermediateCA = registration.intermediateCA + val tlsSerial = tlsCert?.let { extractSerialNumber(it) } + aapsLogger.debug( + LTag.PUMPBTCOMM, + "O5CertificateStore initialized for controller 0x%08X (source=%s): tlsCert=%s bytes, intermediateCA=%s bytes, tlsSerial=%s, signingPublicKey=%d bytes" + .format( + controllerId, + O5RegistrationData.source(controllerId), + tlsCert?.size?.toString() ?: "null", + intermediateCA?.size?.toString() ?: "null", + tlsSerial?.toHex() ?: "unavailable", + signingPublicKeyRaw.size + ) + ) + if (tlsCert != null && extractP256PublicKey(tlsCert) == null) { + aapsLogger.warn( + LTag.PUMPBTCOMM, + "O5CertificateStore: could not extract P-256 public key from TLS certificate for controller 0x%08X" + .format(controllerId) + ) + } + } + + /** Sign [data] with the secondary key; returns the raw signature (r || s, 64 bytes). */ + override fun signRaw(data: ByteArray): ByteArray { + val privateKey = P256Codec.decodePrivateKey(signingPrivateKeyRaw) + val signature = Signature.getInstance(SIGNATURE_ALGORITHM) + signature.initSign(privateKey) + signature.update(data) + val raw = derSignatureToRaw(signature.sign()) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "O5 signRaw: signed ${data.size} bytes with secondary key -> ${raw.size}-byte raw signature" + ) + return raw + } + + companion object { + + private const val SIGNATURE_ALGORITHM = "SHA256withECDSA" + + + /** + * Verify an ECDSA signature against a raw (65-byte, uncompressed) public key. + * Accepts [signature] in either DER or raw (64-byte r || s) form, trying DER first, + * matching the Swift original's behavior. + */ + fun verifySignature(signature: ByteArray, data: ByteArray, publicKeyRaw: ByteArray): Boolean { + val publicKey = try { + P256Codec.decodePublicKey(publicKeyRaw) + } catch (e: Exception) { + return false + } + + verifyDer(signature, data, publicKey)?.let { return it } + + if (signature.size == 64) { + val der = try { + rawSignatureToDer(signature) + } catch (e: Exception) { + null + } + if (der != null) { + verifyDer(der, data, publicKey)?.let { return it } + } + } + + return false + } + + /** Returns null (rather than false) if [der] isn't validly-DER-encoded, so the + * caller knows to try the other signature format instead of treating it as a + * genuine verification failure. */ + private fun verifyDer(der: ByteArray, data: ByteArray, publicKey: ECPublicKey): Boolean? = + try { + val signature = Signature.getInstance(SIGNATURE_ALGORITHM) + signature.initVerify(publicKey) + signature.update(data) + signature.verify(der) + } catch (e: Exception) { + null + } + + + internal fun derSignatureToRaw(der: ByteArray): ByteArray { + require(der.isNotEmpty() && der[0] == 0x30.toByte()) { "Expected DER SEQUENCE tag" } + val (_, seqContentStart) = readDerLength(der, 1) + + val (r, afterR) = readDerInteger(der, seqContentStart) + val (s, _) = readDerInteger(der, afterR) + + return r.toFixedLengthBytes(32) + s.toFixedLengthBytes(32) + } + + internal fun rawSignatureToDer(raw: ByteArray): ByteArray { + require(raw.size == 64) { "Raw ECDSA signature must be 64 bytes (r || s), got ${raw.size}" } + val r = BigInteger(1, raw.copyOfRange(0, 32)) + val s = BigInteger(1, raw.copyOfRange(32, 64)) + val body = encodeDerInteger(r) + encodeDerInteger(s) + return byteArrayOf(0x30) + encodeDerLength(body.size) + body + } + + private fun encodeDerInteger(value: BigInteger): ByteArray { + val content = value.toByteArray() + return byteArrayOf(0x02) + encodeDerLength(content.size) + content + } + + + private val p256SpkiHeader = byteArrayOf( + 0x30, 0x59.toByte(), + 0x30, 0x13, + 0x06, 0x07, 0x2a, 0x86.toByte(), 0x48, 0xce.toByte(), 0x3d, 0x02, 0x01, + 0x06, 0x08, 0x2a, 0x86.toByte(), 0x48, 0xce.toByte(), 0x3d, 0x03, 0x01, 0x07, + 0x03, 0x42, + 0x00, + 0x04 + ) + + /** Extract the raw P-256 public key (64 bytes, x || y) from a base64-encoded DER cert. */ + fun extractP256PublicKey(certDERBase64: String): ByteArray? { + val certDER = try { + Base64.getDecoder().decode(certDERBase64) + } catch (e: IllegalArgumentException) { + return null + } + return extractP256PublicKey(certDER) + } + + /** + * Extract the raw P-256 public key (64 bytes, x || y) from DER certificate bytes. + * Searches for the known SubjectPublicKeyInfo DER header pattern for P-256 keys, + * then extracts the 64-byte raw EC point (without the leading 0x04 prefix). + */ + fun extractP256PublicKey(certDER: ByteArray): ByteArray? { + val header = p256SpkiHeader + val headerLen = header.size + val keyLen = 64 + + if (certDER.size < headerLen + keyLen) return null + + val lastPossibleStart = certDER.size - headerLen - keyLen + for (i in 0..lastPossibleStart) { + var matches = true + for (j in 0 until headerLen) { + if (certDER[i + j] != header[j]) { + matches = false + break + } + } + if (matches) { + val keyStart = i + headerLen + return certDER.copyOfRange(keyStart, keyStart + keyLen) + } + } + return null + } + + + /** + * Extract the serial number from a DER-encoded X.509 certificate. + * + * Handles both v3 certificates (with explicit version tag `a0 03 02 01 02`) + * and v1 certificates (no version tag - serial immediately after the + * TBSCertificate SEQUENCE). + */ + fun extractSerialNumber(certDER: ByteArray): ByteArray? { + val v3Pattern = byteArrayOf(0xa0.toByte(), 0x03, 0x02, 0x01, 0x02, 0x02) + val v3PatternIndex = indexOf(certDER, v3Pattern) + if (v3PatternIndex >= 0) { + val serialLenOffset = v3PatternIndex + v3Pattern.size + if (serialLenOffset >= certDER.size) return null + val serialLen = certDER[serialLenOffset].toInt() and 0xFF + val serialStart = serialLenOffset + 1 + if (serialLen <= 0 || serialStart + serialLen > certDER.size) return null + return certDER.copyOfRange(serialStart, serialStart + serialLen) + } + + if (certDER.size <= 4 || certDER[0] != 0x30.toByte()) return null + val (_, outerContentStart) = readDerLength(certDER, 1) + if (outerContentStart >= certDER.size || certDER[outerContentStart] != 0x30.toByte()) return null + val (_, tbsContentStart) = readDerLength(certDER, outerContentStart + 1) + if (tbsContentStart >= certDER.size) return null + + if (certDER[tbsContentStart] != 0x02.toByte()) return null + val lenOffset = tbsContentStart + 1 + if (lenOffset >= certDER.size) return null + val serialLen = certDER[lenOffset].toInt() and 0xFF + val serialStart = lenOffset + 1 + if (serialLen <= 0 || serialStart + serialLen > certDER.size) return null + return certDER.copyOfRange(serialStart, serialStart + serialLen) + } + + private fun indexOf(haystack: ByteArray, needle: ByteArray): Int { + if (needle.isEmpty() || haystack.size < needle.size) return -1 + outer@ for (i in 0..haystack.size - needle.size) { + for (j in needle.indices) { + if (haystack[i + j] != needle[j]) continue@outer + } + return i + } + return -1 + } + + + /** + * Parses a DER length field starting at [offset]. Returns (length, contentStartOffset). + * Handles both short-form (single byte) and long-form (0x8n + n bytes) lengths. + */ + private fun readDerLength(data: ByteArray, offset: Int): Pair { + val firstByte = data[offset].toInt() and 0xFF + return if (firstByte and 0x80 == 0) { + Pair(firstByte, offset + 1) + } else { + val numLenBytes = firstByte and 0x7f + require(numLenBytes > 0 && offset + 1 + numLenBytes <= data.size) { "Malformed DER length" } + var len = 0 + for (i in 0 until numLenBytes) { + len = (len shl 8) or (data[offset + 1 + i].toInt() and 0xFF) + } + Pair(len, offset + 1 + numLenBytes) + } + } + + private fun encodeDerLength(length: Int): ByteArray { + if (length < 0x80) return byteArrayOf(length.toByte()) + var remaining = length + val bytes = java.util.ArrayDeque() + while (remaining > 0) { + bytes.addFirst((remaining and 0xFF).toByte()) + remaining = remaining shr 8 + } + return byteArrayOf((0x80 or bytes.size).toByte()) + bytes.toByteArray() + } + + /** Reads a DER INTEGER (tag 0x02) at [offset]; returns (value, offset after integer). */ + private fun readDerInteger(data: ByteArray, offset: Int): Pair { + require(data[offset] == 0x02.toByte()) { "Expected DER INTEGER tag" } + val (len, contentStart) = readDerLength(data, offset + 1) + val bytes = data.copyOfRange(contentStart, contentStart + len) + return Pair(BigInteger(bytes), contentStart + len) + } + + private fun BigInteger.toFixedLengthBytes(length: Int): ByteArray { + val raw = this.toByteArray() + return when { + raw.size == length -> raw + raw.size == length + 1 && raw[0] == 0.toByte() -> raw.copyOfRange(1, raw.size) + raw.size < length -> ByteArray(length - raw.size) + raw + else -> throw IllegalStateException( + "Value does not fit in $length bytes (got ${raw.size})" + ) + } + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5KeyExchange.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5KeyExchange.kt new file mode 100644 index 000000000000..c9bc901f84ec --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5KeyExchange.kt @@ -0,0 +1,255 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.utils.toHex +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.MessageIOException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.pump.omnipod.common.bledriver.pod.util.RandomByteGenerator +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.security.MessageDigest + +/** + * Runs the Omnipod 5 pairing key exchange (the "SPS1"/"SPS2" handshake): generates the + * controller's ephemeral P-256 keypair and nonce, combines them with the pod's ephemeral + * public key and nonce plus the ECDH shared secret into a SHA-256-derived confirmation + * value and long-term key (LTK), and provides the nonce/transcript machinery the rest of + * the O5 pairing flow needs to build and verify SPS2/SPS2.1 messages. + * + * Ported from OmnipodKit's O5KeyExchange.swift (loopandlearn/OmnipodKit). + */ +class O5KeyExchange( + private val aapsLogger: AAPSLogger, + private val p256KeyGenerator: P256KeyGenerator, + randomByteGenerator: RandomByteGenerator, + /** The certificate-derived controller ID (4 bytes, big-endian). */ + val controllerIdData: ByteArray +) { + + enum class Direction { WRITE, READ } + + var pdmNonce: ByteArray = randomByteGenerator.nextBytes(NONCE_SIZE) + private set + val pdmPrivate: ByteArray = p256KeyGenerator.generatePrivateKey() + val pdmPublic: ByteArray = p256KeyGenerator.publicFromPrivate(pdmPrivate) + + var podPublic: ByteArray = ByteArray(PUBLIC_KEY_SIZE) + private set + var podNonce: ByteArray = ByteArray(NONCE_SIZE) + private set + + var conf: ByteArray = ByteArray(CMAC_SIZE) + private set + var ltk: ByteArray = ByteArray(CMAC_SIZE) + private set + + init { + if (pdmNonce.size != NONCE_SIZE) { + throw PairingException("pdmNonce size ${pdmNonce.size} != expected $NONCE_SIZE") + } + if (pdmPublic.size != PUBLIC_KEY_SIZE) { + throw PairingException("pdmPublic size ${pdmPublic.size} != expected $PUBLIC_KEY_SIZE") + } + aapsLogger.debug( + LTag.PUMPBTCOMM, + "O5KeyExchange init: controllerId=${controllerIdData.joinToString("") { "%02x".format(it) }}" + ) + } + + /** + * Processes the pod's SPS1 response payload (its ephemeral public key + nonce), + * then derives [conf] and [ltk] from the ECDH shared secret. + * + * @throws MessageIOException if [payload] isn't exactly PUBLIC_KEY_SIZE + NONCE_SIZE bytes. + */ + fun o5UpdatePodPublicData(payload: ByteArray) { + if (payload.size != PUBLIC_KEY_SIZE + NONCE_SIZE) { + throw MessageIOException( + "Invalid SPS1 payload size: ${payload.size}, expected ${PUBLIC_KEY_SIZE + NONCE_SIZE}" + ) + } + podPublic = payload.copyOfRange(0, PUBLIC_KEY_SIZE) + podNonce = payload.copyOfRange(PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE + NONCE_SIZE) + aapsLogger.debug(LTag.PUMPBTCOMM, "pdmPublic (${pdmPublic.size}): ${pdmPublic.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "podPublic (${podPublic.size}): ${podPublic.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "pdmNonce (${pdmNonce.size}): ${pdmNonce.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "podNonce (${podNonce.size}): ${podNonce.toHex()}") + o5GenerateKeys() + } + + private fun o5GenerateKeys() { + val sharedSecret = p256KeyGenerator.computeSharedSecret(pdmPrivate, podPublic) + + val data = ByteArrayBuilder() + .appendBigEndianU64Length(FIRMWARE_ID.size) + .append(FIRMWARE_ID) + .appendBigEndianU64Length(4) + .append(byteArrayOf(0x00, 0x00, 0x00, 0x00)) + .appendBigEndianU64Length(pdmPublic.size) + .append(pdmPublic) + .appendBigEndianU64Length(podPublic.size) + .append(podPublic) + .appendBigEndianU64Length(sharedSecret.size) + .append(sharedSecret) + .toByteArray() + + val derivedKey = MessageDigest.getInstance("SHA-256").digest(data) + if (derivedKey.size != 32) { + throw PairingException("SHA-256 output size ${derivedKey.size} != expected 32") + } + conf = derivedKey.copyOfRange(0, 16) + ltk = derivedKey.copyOfRange(16, 32) + aapsLogger.debug(LTag.PUMPBTCOMM, "Derived conf (${conf.size}): ${conf.toHex()}, ltk ${ltk.size} bytes") + } + + /** + * Builds the 13-byte AES-CCM nonce for an SPS2/SPS2.1 message in the given [direction]: + * `[directionByte] || first6(senderNonce) || first6(receiverNonce)`. + */ + fun getSPSNonce(direction: Direction): ByteArray { + if (pdmNonce.size < 6 || podNonce.size < 6) { + return ByteArray(0) + } + val pdmSlice = pdmNonce.copyOfRange(0, 6) + val podSlice = podNonce.copyOfRange(0, 6) + + val nonce = when (direction) { + Direction.WRITE -> byteArrayOf(0x01) + pdmSlice + podSlice + Direction.READ -> byteArrayOf(0x02) + podSlice + pdmSlice + } + return nonce + } + + /** Increments the controller's (write) or pod's (read) nonce by one, per [incrementNonceInPlace]. */ + fun incrementNonce(direction: Direction) { + when (direction) { + Direction.WRITE -> pdmNonce = incrementNonceInPlace(pdmNonce) + Direction.READ -> podNonce = incrementNonceInPlace(podNonce) + } + } + + /** + * Increments the first 8 bytes of [nonce], interpreted as a little-endian UInt64 + * counter (matching Swift's `withUnsafeBytes { $0.load(as: UInt64.self) }` on + * little-endian Apple hardware), wrapping on overflow. Bytes 8+ are preserved as-is. + */ + private fun incrementNonceInPlace(nonce: ByteArray): ByteArray { + val counter = ByteBuffer.wrap(nonce, 0, 8).order(ByteOrder.LITTLE_ENDIAN).long + val incremented = counter + 1 + val result = nonce.copyOf() + ByteBuffer.wrap(result, 0, 8).order(ByteOrder.LITTLE_ENDIAN).putLong(incremented) + return result + } + + /** + * Decrements the first 8 bytes of [nonce] (little-endian UInt64), wrapping on + * underflow, leaving the rest of the bytes untouched. Used only when building the + * pod's channel-binding transcript variant (see [buildPodChannelBindingTranscript]). + */ + private fun decrementNonceCopy(nonce: ByteArray): ByteArray { + val counter = ByteBuffer.wrap(nonce, 0, 8).order(ByteOrder.LITTLE_ENDIAN).long + val decremented = counter - 1 + val result = nonce.copyOf() + ByteBuffer.wrap(result, 0, 8).order(ByteOrder.LITTLE_ENDIAN).putLong(decremented) + return result + } + + /** + * Builds the 171-byte channel-binding transcript for SPS2.1 signing, from the + * controller's point of view: + * `[0x01] || FIRMWARE_ID(6) || zeros(4) || pdmPublic(64) || podPublic(64) || pdmNonce(16) || podNonce(16)` + */ + fun buildChannelBindingTranscript(): ByteArray { + val transcript = byteArrayOf(0x01) + + FIRMWARE_ID + + byteArrayOf(0x00, 0x00, 0x00, 0x00) + + pdmPublic + + podPublic + + pdmNonce + + podNonce + + check(transcript.size == TRANSCRIPT_SIZE) { + "Channel-binding transcript size mismatch: got ${transcript.size}, expected $TRANSCRIPT_SIZE" + } + return transcript + } + + /** + * Builds the pod's (peer) variant of the channel-binding transcript, for verifying the + * pod's own SPS2 signature. Must only be called AFTER: controller sent SPS2.1 (pdmNonce + * +1), received pod SPS2.1 (podNonce +1), sent SPS2 (pdmNonce +2 total), received pod + * SPS2 (podNonce +2 total) - i.e. from [O5LTKExchanger]'s `o5validatePodSps2()` step. + * + * At that point the pod's own nonce state when it built ITS transcript was one step + * behind the controller's current podNonce (the pod had only processed SPS2.1, not yet + * encrypted its SPS2 reply), so [podNonce] is decremented by one here to match. + * + * Layout: `[0x02] || zeros(4) || FIRMWARE_ID(6) || podPublic(64) || pdmPublic(64) || podNonceAdjusted(16) || pdmNonce(16)` + */ + fun buildPodChannelBindingTranscript(): ByteArray { + val podNonceAdjusted = decrementNonceCopy(podNonce) + + val transcript = byteArrayOf(0x02) + + byteArrayOf(0x00, 0x00, 0x00, 0x00) + + FIRMWARE_ID + + podPublic + + pdmPublic + + podNonceAdjusted + + pdmNonce + + check(transcript.size == TRANSCRIPT_SIZE) { + "Pod channel-binding transcript size mismatch: got ${transcript.size}, expected $TRANSCRIPT_SIZE" + } + return transcript + } + + /** A tiny append-only byte builder, just to keep [o5GenerateKeys] readable. */ + private class ByteArrayBuilder { + private val parts = mutableListOf() + + fun append(bytes: ByteArray): ByteArrayBuilder { + parts.add(bytes) + return this + } + + /** Appends [value] as an 8-byte big-endian length field (matches Swift's + * `UInt64(...).bigEndian` length-prefixing in the KDF input construction). */ + fun appendBigEndianU64Length(value: Int): ByteArrayBuilder { + val buffer = ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN) + buffer.putLong(value.toLong()) + parts.add(buffer.array()) + return this + } + + fun toByteArray(): ByteArray { + val total = parts.fold(0) { acc, part -> acc + part.size } + val result = ByteArray(total) + var offset = 0 + for (part in parts) { + part.copyInto(result, offset) + offset += part.size + } + return result + } + } + + companion object { + + const val CMAC_SIZE = 16 + const val PUBLIC_KEY_SIZE = 64 + const val NONCE_SIZE = 16 + private const val TRANSCRIPT_SIZE = 171 + + /** + * Fixed 6-byte value taken from the PDM firmware. Shared with [O5LTKExchanger] + * (not yet ported), which will reference this same constant rather than + * duplicating it. + */ + val FIRMWARE_ID: ByteArray = hexToBytes("9b0ab96a76f4") + + private fun hexToBytes(hex: String): ByteArray = + ByteArray(hex.length / 2) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5LTKExchanger.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5LTKExchanger.kt new file mode 100644 index 000000000000..4349b61c9766 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5LTKExchanger.kt @@ -0,0 +1,423 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair +import app.aaps.pump.omnipod.common.bledriver.comm.pair.PairMessage +import app.aaps.pump.omnipod.common.bledriver.comm.pair.PairResult + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.utils.toHex +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.scan.PodScanner +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessagePacket +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendSuccess +import app.aaps.pump.omnipod.common.bledriver.comm.message.StringLengthPrefixEncoding.Companion.parseKeys +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.pump.omnipod.common.bledriver.pod.util.RandomByteGenerator +import org.spongycastle.crypto.engines.AESEngine +import org.spongycastle.crypto.modes.CCMBlockCipher +import org.spongycastle.crypto.params.AEADParameters +import org.spongycastle.crypto.params.KeyParameter + +/** + * Drives the Omnipod 5 pairing message sequence over BLE: SP1+SP2, SPS0, SPS1, SPS2.1, + * SPS2, SP0GP0, P0 - using [O5KeyExchange] for the key agreement/nonces/transcripts and + * [O5CertificateStore] for certificate data and channel-binding signatures. + * + * Ported from OmnipodKit's O5LTKExchanger.swift (loopandlearn/OmnipodKit). + * + * Unlike the Swift original (which resolves `myId`/`podId` via a Dash-specific `Ids` + * helper tied to `OmnipodDashBleManagerImpl`/`OmnipodDashPodStateManager`), this takes + * [myId] and [podId] directly - O5 has its own certificate-derived controller identity + * (see [O5CertificateStore.controllerId]) rather than sharing Dash's `Ids` scheme, and + * wiring those together for a live pod is a separate integration step. + */ +class O5LTKExchanger( + private val aapsLogger: AAPSLogger, + private val msgIO: MessageIO, + private val certStore: O5CertificateStore, + private val myId: Id, + private val podId: Id +) { + + private val podAddress: Id = Id.fromLong(PodScanner.POD_ID_NOT_ACTIVATED) + private val keyExchange: O5KeyExchange = O5KeyExchange( + aapsLogger, + P256KeyGenerator(), + RandomByteGenerator(), + certStore.controllerIdData + ) + private var seq: Byte = 1 + + fun o5NegotiateLTK(): PairResult { + aapsLogger.debug(LTag.PUMPBTCOMM, "O5 pairing attempt using fixed confirmed parameters") + try { + val result = o5NegotiateLTKBody() + aapsLogger.debug(LTag.PUMPBTCOMM, "O5 pairing SUCCEEDED") + return result + } catch (e: Exception) { + aapsLogger.error(LTag.PUMPBTCOMM, "O5 pairing FAILED: $e") + throw e + } + } + + private fun o5NegotiateLTKBody(): PairResult { + val sp1sp2 = PairMessage( + sequenceNumber = seq, + source = myId, + destination = podAddress, + keys = arrayOf(SP1, SP2), + payloads = arrayOf(podId.address, o5Sp2(podId)) + ) + throwOnSendError(sp1sp2.messagePacket, SP1 + SP2) + + seq++ + val sps0 = PairMessage( + sequenceNumber = seq, + source = myId, + destination = podAddress, + keys = arrayOf(SPS0), + payloads = arrayOf(o5Sps0()) + ) + throwOnSendError(sps0.messagePacket, SPS0) + + val podSps0 = msgIO.receiveMessage() ?: throw PairingException("Could not read SPS0") + validatePodO5Sps0(podSps0) + + seq++ + val sps1 = PairMessage( + sequenceNumber = seq, + source = myId, + destination = podAddress, + keys = arrayOf(SPS1), + payloads = arrayOf(keyExchange.pdmPublic + keyExchange.pdmNonce) + ) + throwOnSendError(sps1.messagePacket, SPS1) + + val podSps1 = msgIO.receiveMessage() ?: throw PairingException("Could not read SPS1") + o5ValidatePodSps1(podSps1) + + seq++ + val sps2_1 = PairMessage( + sequenceNumber = seq, + source = myId, + destination = podAddress, + keys = arrayOf(SPS2_1), + payloads = arrayOf(o5Sps2_1()) + ) + throwOnSendError(sps2_1.messagePacket, SPS2_1) + + val podSps2_1 = msgIO.receiveMessage() ?: throw PairingException("Could not read SPS2.1") + o5ValidatePodSps2_1(podSps2_1) + + seq++ + val sps2 = PairMessage( + sequenceNumber = seq, + source = myId, + destination = podAddress, + keys = arrayOf(SPS2), + payloads = arrayOf(o5Sps2()) + ) + throwOnSendError(sps2.messagePacket, SPS2) + + val podSps2 = msgIO.receiveMessage() ?: throw PairingException("Could not read SPS2") + o5ValidatePodSps2(podSps2) + + seq++ + val sp0gp0 = PairMessage( + sequenceNumber = seq, + source = myId, + destination = podAddress, + keys = arrayOf(SP0GP0), + payloads = arrayOf(ByteArray(0)) + ) + val result = msgIO.sendMessage(sp0gp0.messagePacket) + if (result !is MessageSendSuccess) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Error sending SP0GP0: $result") + } + + msgIO.receiveMessage() + ?.let { o5ValidateP0(it) } + ?: aapsLogger.warn(LTag.PUMPBTCOMM, "Could not read P0") + + check(keyExchange.ltk.size == 16) { "Invalid LTK size: ${keyExchange.ltk.size}" } + + aapsLogger.debug( + LTag.PUMPBTCOMM, + "=== O5 Pairing Complete === address: 0x%08x, seq: %d".format(podId.toLong(), seq) + ) + return PairResult(ltk = keyExchange.ltk, msgSeq = seq) + } + + private fun throwOnSendError(msg: MessagePacket, msgType: String) { + val result = msgIO.sendMessage(msg) + if (result !is MessageSendSuccess) { + throw PairingException("Could not send or confirm $msgType: $result") + } + } + + + private fun o5Sp2(podId: Id): ByteArray { + val body = byteArrayOf(0x0e, 0x01, 0x00) + val b9: Byte = 0x00 + val withoutCrc = podId.address + byteArrayOf(b9, body.size.toByte()) + body + val crc = classicCrc16(withoutCrc) + return withoutCrc + byteArrayOf((crc ushr 8).toByte(), (crc and 0xFF).toByte()) + } + + + /** + * Generates the 5-byte SPS0 payload with CRC-16/XMODEM. + * Structure: [constant_byte, direction_byte, algorithm_byte, crc16_high, crc16_low]. + * Direction: 0x01 for PDM->Pod. Algorithm byte 0x09 specifies the encryption algorithm. + */ + private fun o5Sps0(): ByteArray { + val header = byteArrayOf(0x00, 0x01, 0x09) + val crc = crc16XMODEM(header) + return header + byteArrayOf((crc ushr 8).toByte(), (crc and 0xFF).toByte()) + } + + /** Validates the pod's 5-byte SPS0 response (pod's direction byte is 0x00, vs PDM's 0x01). */ + private fun validatePodO5Sps0(msg: MessagePacket) { + val payload = parseKeys(arrayOf(SPS0), msg.payload)[0] + if (payload.size != 5) { + throw PairingException("Invalid SPS0 payload length: ${payload.size}") + } + if (payload[0] != 0x00.toByte() || payload[1] != 0x00.toByte() || payload[2] != 0x09.toByte()) { + throw PairingException("Unexpected SPS0 header bytes") + } + val header = payload.copyOfRange(0, 3) + val expectedCrc = crc16XMODEM(header) + val receivedCrc = ((payload[3].toInt() and 0xFF) shl 8) or (payload[4].toInt() and 0xFF) + if (expectedCrc != receivedCrc) { + throw PairingException( + "SPS0 CRC mismatch: expected %04x, received %04x".format(expectedCrc, receivedCrc) + ) + } + } + + + private fun o5ValidatePodSps1(msg: MessagePacket) { + val payload = parseKeys(arrayOf(SPS1), msg.payload)[0] + keyExchange.o5UpdatePodPublicData(payload) + } + + + /** + * Builds and encrypts the SPS2.1 payload: `AES_CCM_ENC(intermediateCA_DER) || tag(8)`. + * The ECDSA channel-binding signature goes in SPS2, not here. + */ + private fun o5Sps2_1(): ByteArray { + val certDER = certStore.registration.intermediateCA + ?: throw PairingException("SPS2.1: intermediate CA certificate DER is null") + + aapsLogger.debug(LTag.PUMPBTCOMM, "=== SPS2.1 PHASE START ===") + aapsLogger.debug(LTag.PUMPBTCOMM, "SPS2.1: using cert (${certDER.size} bytes, cert-only short path)") + + val nonce = keyExchange.getSPSNonce(O5KeyExchange.Direction.WRITE) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Encrypting SPS2.1: key=${keyExchange.conf.toHex()}, nonce=${nonce.toHex()}, plaintext=${certDER.size} bytes" + ) + val encrypted = aesCcmEncrypt(keyExchange.conf, nonce, certDER) + keyExchange.incrementNonce(O5KeyExchange.Direction.WRITE) + aapsLogger.debug(LTag.PUMPBTCOMM, "SPS2.1 encrypted: ${encrypted.size} bytes (target=${certDER.size + MAC_SIZE_BYTES})") + return encrypted + } + + /** Decrypts and validates the pod's SPS2.1 response (short path: cert only). */ + private fun o5ValidatePodSps2_1(msg: MessagePacket) { + val payload = parseKeys(arrayOf(SPS2_1), msg.payload)[0] + aapsLogger.debug(LTag.PUMPBTCOMM, "Received pod SPS2.1: ${payload.size} bytes") + + val nonce = keyExchange.getSPSNonce(O5KeyExchange.Direction.READ) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Decrypting pod SPS2.1: key=${keyExchange.conf.toHex()}, nonce=${nonce.toHex()}, ciphertext=${payload.size} bytes" + ) + val podCertDER = aesCcmDecrypt(keyExchange.conf, nonce, payload) + keyExchange.incrementNonce(O5KeyExchange.Direction.READ) + aapsLogger.debug(LTag.PUMPBTCOMM, "Pod SPS2.1 decrypted: ${podCertDER.size} bytes (pod cert DER, short path)") + + if (O5CertificateStore.extractP256PublicKey(podCertDER) == null) { + aapsLogger.error(LTag.PUMPBTCOMM, "Failed to extract P-256 public key from pod SPS2.1 certificate DER") + } + aapsLogger.debug(LTag.PUMPBTCOMM, "=== SPS2.1 PHASE COMPLETE ===") + } + + + /** + * Builds and encrypts the SPS2 payload: `AES_CCM_ENC(TLS_cert_DER || ECDSA_sig(64)) || tag(8)`. + * The 64-byte signature is over the 171-byte channel-binding transcript, signed with + * the secondary key. + */ + private fun o5Sps2(): ByteArray { + val certDER = certStore.registration.tlsCertificate + ?: throw PairingException("SPS2: TLS certificate DER is null") + + aapsLogger.debug(LTag.PUMPBTCOMM, "=== SPS2 PHASE START ===") + + val transcript = keyExchange.buildChannelBindingTranscript() + aapsLogger.debug(LTag.PUMPBTCOMM, "Channel-binding transcript (${transcript.size} bytes): ${transcript.toHex()}") + + val signatureRaw = certStore.signRaw(transcript) + aapsLogger.debug(LTag.PUMPBTCOMM, "ECDSA signature (${signatureRaw.size} bytes): ${signatureRaw.toHex()}") + + val plaintext = certDER + signatureRaw + aapsLogger.debug( + LTag.PUMPBTCOMM, + "SPS2: TLS cert (${certDER.size} bytes) + sig (${signatureRaw.size}) = ${plaintext.size} plaintext" + ) + + val nonce = keyExchange.getSPSNonce(O5KeyExchange.Direction.WRITE) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Encrypting SPS2: key=${keyExchange.conf.toHex()}, nonce=${nonce.toHex()}, plaintext=${plaintext.size} bytes" + ) + val encrypted = aesCcmEncrypt(keyExchange.conf, nonce, plaintext) + keyExchange.incrementNonce(O5KeyExchange.Direction.WRITE) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "SPS2 encrypted: ${encrypted.size} bytes (target=${certDER.size + signatureRaw.size + MAC_SIZE_BYTES})" + ) + return encrypted + } + + /** Decrypts and validates the pod's SPS2 response (extended path: cert + signature). */ + private fun o5ValidatePodSps2(msg: MessagePacket) { + val payload = parseKeys(arrayOf(SPS2), msg.payload)[0] + aapsLogger.debug(LTag.PUMPBTCOMM, "Received pod SPS2: ${payload.size} bytes") + + val nonce = keyExchange.getSPSNonce(O5KeyExchange.Direction.READ) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Decrypting pod SPS2: key=${keyExchange.conf.toHex()}, nonce=${nonce.toHex()}, ciphertext=${payload.size} bytes" + ) + val decrypted = aesCcmDecrypt(keyExchange.conf, nonce, payload) + keyExchange.incrementNonce(O5KeyExchange.Direction.READ) + + if (decrypted.size <= 64) { + throw PairingException("Pod SPS2 payload too short: ${decrypted.size} bytes (need > 64)") + } + val certLen = decrypted.size - 64 + val podCertDER = decrypted.copyOfRange(0, certLen) + val podSignature = decrypted.copyOfRange(certLen, decrypted.size) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Pod SPS2 decrypted: ${decrypted.size} bytes (cert_DER=$certLen + sig=${podSignature.size})" + ) + aapsLogger.debug(LTag.PUMPBTCOMM, "Pod signature (${podSignature.size} bytes): ${podSignature.toHex()}") + + aapsLogger.debug(LTag.PUMPBTCOMM, "=== SPS2 PHASE COMPLETE ===") + } + + + private fun o5ValidateP0(msg: MessagePacket) { + val payload = parseKeys(arrayOf(P0), msg.payload)[0] + if (!payload.contentEquals(EXPECTED_P0_PAYLOAD)) { + throw PairingException( + "Received unexpected P0 payload: ${payload.joinToString("") { "%02x".format(it) }}" + ) + } + } + + + private fun aesCcmEncrypt(key: ByteArray, nonce: ByteArray, plaintext: ByteArray): ByteArray { + val cipher = CCMBlockCipher(AESEngine()) + cipher.init(true, AEADParameters(KeyParameter(key), MAC_SIZE_BITS, nonce, ByteArray(0))) + val output = ByteArray(plaintext.size + MAC_SIZE_BYTES) + cipher.processPacket(plaintext, 0, plaintext.size, output, 0) + return output + } + + private fun aesCcmDecrypt(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray): ByteArray { + val cipher = CCMBlockCipher(AESEngine()) + cipher.init(false, AEADParameters(KeyParameter(key), MAC_SIZE_BITS, nonce, ByteArray(0))) + val output = ByteArray(ciphertext.size - MAC_SIZE_BYTES) + cipher.processPacket(ciphertext, 0, ciphertext.size, output, 0) + return output + } + + companion object { + + private const val SP1 = "SP1=" + private const val SP2 = ",SP2=" + private const val SPS0 = "SPS0=" + private const val SPS1 = "SPS1=" + private const val SPS2_1 = "SPS2.1=" + private const val SPS2 = "SPS2=" + private const val SP0GP0 = "SP0,GP0" + private const val P0 = "P0=" + private val EXPECTED_P0_PAYLOAD = byteArrayOf(0xa5.toByte()) + + private const val MAC_SIZE_BYTES = 8 + private const val MAC_SIZE_BITS = MAC_SIZE_BYTES * 8 + + /** + * The CRC-16 variant (and 256-entry table) used by OmnipodKit's own Message.swift + * for the classic Omnipod message envelope in [o5Sp2]. Despite the table's + * resemblance to CRC-16/ARC's polynomial, it does NOT match CRC-16/ARC's published + * check value for "123456789" - this specific table+algorithm combination is + * whatever OmnipodKit itself uses, verified here only for faithful byte-for-byte + * reproduction of that source (see the class's test suite), not for matching any + * named textbook CRC-16 standard. This is a DIFFERENT variant from [crc16XMODEM] + * (used only for SPS0) - the two must not be confused. + */ + fun classicCrc16(data: ByteArray): Int { + var acc = 0 + for (byte in data) { + val idx = (acc xor (byte.toInt() and 0xFF)) and 0xFF + acc = (acc ushr 8) xor CLASSIC_CRC16_TABLE[idx] + } + return acc and 0xFFFF + } + + /** CRC-16/XMODEM (poly 0x1021, init 0x0000, no reflection), used only for SPS0. */ + fun crc16XMODEM(data: ByteArray): Int { + var crc = 0x0000 + for (byte in data) { + crc = crc xor ((byte.toInt() and 0xFF) shl 8) + repeat(8) { + crc = if (crc and 0x8000 != 0) (crc shl 1) xor 0x1021 else crc shl 1 + crc = crc and 0xFFFF + } + } + return crc and 0xFFFF + } + + private val CLASSIC_CRC16_TABLE: IntArray = intArrayOf( + 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011, + 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022, + 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072, + 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041, + 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2, + 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1, + 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1, + 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082, + 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192, + 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1, + 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1, + 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2, + 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151, + 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162, + 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132, + 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101, + 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312, + 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321, + 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371, + 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342, + 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1, + 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2, + 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2, + 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381, + 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291, + 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2, + 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2, + 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1, + 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252, + 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261, + 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231, + 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202 + ) + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5RegistrationData.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5RegistrationData.kt new file mode 100644 index 000000000000..6e01acbdaf11 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5RegistrationData.kt @@ -0,0 +1,245 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair + +import java.util.Base64 +import java.util.Random +import java.util.ServiceLoader +import java.util.concurrent.ConcurrentHashMap + +/** + * PKI registration material for one Omnipod 5 controller identity: a secondary P-256 + * signing keypair plus the certificate chain issued for it, all keyed by controllerId. + * + * This is deliberately just a data holder + in-memory registry - this open-source project + * doesn't ship real Insulet-issued PKI material. Real registration data can be added at + * runtime three ways, mirroring OmnipodKit's own [O5RegistrationSource] distinction: + * - [Installer] discovered via [ServiceLoader] ([O5RegistrationSource.BUILT_IN]) + * - [installPacked] / [fromJson] ([O5RegistrationSource.IMPORTED]) - for a user pasting a + * credential string or importing a keypair file through some future settings UI + * - [install] called directly by other code, e.g. after a network fetch + * ([O5RegistrationSource.DOWNLOADED]) - note OmnipodKit's own automatic-download flow is + * built on Apple's DeviceCheck/App Attest, which has no Android equivalent; this source + * value exists for API parity, not because that specific flow is portable + * + * Ported from OmnipodKit's O5RegistrationData.swift (loopandlearn/OmnipodKit). The Swift + * original's built-in loading uses a `dlsym`-based dynamic symbol lookup, which has no + * portable JVM equivalent; [ServiceLoader] is the idiomatic JVM analogue. + */ +data class O5RegistrationData( + /** The 32-bit controller id this registration applies to (kept as Long to avoid + * unsigned-overflow pitfalls; valid values fit in the low 32 bits). */ + val controllerId: Long, + val privateKeyHex: String, + val publicKeyHex: String, + val intermediateCABase64: String, + val tlsCertificateBase64: String +) { + + val privateKey: ByteArray get() = hexToBytes(privateKeyHex) + val publicKey: ByteArray get() = hexToBytes(publicKeyHex) + + val intermediateCA: ByteArray? get() = decodeBase64OrNull(intermediateCABase64) + val tlsCertificate: ByteArray? get() = decodeBase64OrNull(tlsCertificateBase64) + + /** The controllerId as its 4-byte big-endian representation. */ + val controllerIdData: ByteArray + get() { + val id = controllerId and 0xFFFFFFFFL + return byteArrayOf( + ((id shr 24) and 0xFF).toByte(), + ((id shr 16) and 0xFF).toByte(), + ((id shr 8) and 0xFF).toByte(), + (id and 0xFF).toByte() + ) + } + + /** + * The shape matches OmnipodKit's "o5keypair" file format, so persisted entries and + * imported files/strings share one representation. + */ + fun toJsonMap(): Map = mapOf( + "controllerId" to controllerId.toString(), + "privateKey" to privateKeyHex, + "publicKey" to publicKeyHex, + "intermediateCA" to intermediateCABase64, + "tlsCertificate" to tlsCertificateBase64 + ) + + /** + * Implement and register via `META-INF/services` (or call [O5RegistrationData.install] + * directly at app startup) to supply real O5 PKI data from an optional module that + * isn't part of this open-source repository. + */ + interface Installer { + fun install() + } + + /** Where a given registration entry originally came from - for diagnostics/UI display. */ + enum class O5RegistrationSource { BUILT_IN, IMPORTED, DOWNLOADED } + + companion object { + + private val registry = ConcurrentHashMap() + private val sources = ConcurrentHashMap() + private val random = Random() + + @Volatile + private var optionalDataLoaded = false + + fun install(value: O5RegistrationData, source: O5RegistrationSource) { + registry[value.controllerId] = value + sources[value.controllerId] = source + } + + fun markSource(controllerId: Long, source: O5RegistrationSource) { + sources[controllerId] = source + } + + fun source(forControllerId: Long): O5RegistrationSource? { + loadOptionalRegistrationDataOnce() + return sources[forControllerId] + } + + fun get(controllerId: Long): O5RegistrationData? { + loadOptionalRegistrationDataOnce() + return registry[controllerId] + } + + fun getRandom(): O5RegistrationData? { + loadOptionalRegistrationDataOnce() + val values = registry.values.toList() + return if (values.isEmpty()) null else values[random.nextInt(values.size)] + } + + val allValues: List + get() { + loadOptionalRegistrationDataOnce() + return registry.values.toList() + } + + val isEmpty: Boolean + get() { + loadOptionalRegistrationDataOnce() + return registry.isEmpty() + } + + fun contains(controllerId: Long): Boolean = get(controllerId) != null + + fun remove(controllerId: Long) { + registry.remove(controllerId) + sources.remove(controllerId) + } + + /** Randomly picks an available O5 controllerId, or 0 if none is available. */ + val pickControllerId: Long + get() = getRandom()?.controllerId ?: 0L + + /** + * Parses a compact delimited credential string: `"controllerId|privB64|pubB64|icaB64|tlsB64"` + * (matching OmnipodKit's own `install(packed:)` format, so a credential exported from + * one can be pasted directly into the other), converts the base64-encoded private/public + * keys to hex internally, and installs it with source [O5RegistrationSource.IMPORTED]. + * + * Returns true if the string parsed and installed successfully, false if it was + * malformed (wrong field count, unparseable controllerId) - this never throws, since + * it's meant to validate arbitrary user-pasted input. + */ + fun installPacked(packed: String): Boolean { + val parts = packed.trim().split("|") + if (parts.size != 5) return false + val controllerId = parts[0].toLongOrNull() ?: return false + + val privateKeyHex = base64ToHexOrNull(parts[1]) ?: return false + val publicKeyHex = base64ToHexOrNull(parts[2]) ?: return false + + install( + O5RegistrationData( + controllerId = controllerId, + privateKeyHex = privateKeyHex, + publicKeyHex = publicKeyHex, + intermediateCABase64 = parts[3], + tlsCertificateBase64 = parts[4] + ), + source = O5RegistrationSource.IMPORTED + ) + return true + } + + /** + * Builds the packed string form of [data], the inverse of [installPacked] - useful + * for exporting/backing up an installed credential. + */ + fun toPacked(data: O5RegistrationData): String { + val privB64 = Base64.getEncoder().encodeToString(data.privateKey) + val pubB64 = Base64.getEncoder().encodeToString(data.publicKey) + return "${data.controllerId}|$privB64|$pubB64|${data.intermediateCABase64}|${data.tlsCertificateBase64}" + } + + /** + * Parses an "o5keypair" JSON-shaped map (as produced by [O5RegistrationData.toJsonMap], + * or read from a JSON file/object elsewhere) into an [O5RegistrationData]. Returns null + * if any required field is missing or the controllerId isn't a valid number - this is + * a pure parse function; callers decide whether/how to [install] the result. + */ + fun fromJsonMap(json: Map): O5RegistrationData? { + val controllerId = json["controllerId"]?.toLongOrNull() ?: return null + val privateKeyHex = json["privateKey"] ?: return null + val publicKeyHex = json["publicKey"] ?: return null + val intermediateCABase64 = json["intermediateCA"] ?: return null + val tlsCertificateBase64 = json["tlsCertificate"] ?: return null + return O5RegistrationData( + controllerId = controllerId, + privateKeyHex = privateKeyHex, + publicKeyHex = publicKeyHex, + intermediateCABase64 = intermediateCABase64, + tlsCertificateBase64 = tlsCertificateBase64 + ) + } + + /** + * Visible for testing: forces the ServiceLoader-based optional-data lookup to run + * again on the next registry access, e.g. after registering a fake Installer. + */ + internal fun resetOptionalDataLoadedForTesting() { + optionalDataLoaded = false + } + + private fun loadOptionalRegistrationDataOnce() { + if (optionalDataLoaded) return + synchronized(this) { + if (optionalDataLoaded) return + try { + ServiceLoader.load(Installer::class.java).forEach { + it.install() + } + } catch (_: Throwable) { + } + optionalDataLoaded = true + } + } + + private fun hexToBytes(hex: String): ByteArray { + val clean = hex.trim() + require(clean.length % 2 == 0) { "Hex string must have an even length" } + return ByteArray(clean.length / 2) { i -> + clean.substring(i * 2, i * 2 + 2).toInt(16).toByte() + } + } + + private fun bytesToHex(bytes: ByteArray): String = + bytes.joinToString("") { "%02x".format(it) } + + private fun base64ToHexOrNull(base64: String): String? = + try { + bytesToHex(Base64.getDecoder().decode(base64)) + } catch (_: IllegalArgumentException) { + null + } + + private fun decodeBase64OrNull(value: String): ByteArray? = + try { + Base64.getDecoder().decode(value) + } catch (_: IllegalArgumentException) { + null + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/command/aid/O5AidSetupCommands.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/command/aid/O5AidSetupCommands.kt new file mode 100644 index 000000000000..cadc53897718 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/command/aid/O5AidSetupCommands.kt @@ -0,0 +1,95 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.command.aid + +import app.aaps.pump.omnipod.common.bledriver.comm.session.Session +import java.nio.ByteBuffer +import java.nio.charset.StandardCharsets + +/** + * O5-only "AID setup" command batch - ported from OmnipodKit's O5AidCommands.swift / + * BlePodComms.o5SendAidSetupCommands() (loopandlearn/OmnipodKit). Required right after + * pairing/session establishment and before anything else in activation - the pod's + * onboard AID firmware expects this data even though AAPS runs O5 as a manual pod with + * that firmware's own automated-delivery mode never engaged (see + * [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin]'s class doc). Skipping or getting any of + * these wrong blocks activation from completing: the reference throws immediately on any + * failure here and never proceeds to SetupPod/SetUniqueId, and [send] mirrors that by + * propagating [Session.sendAidSetupCommand]'s exceptions rather than swallowing them. + * + * Every value below except the UTC timestamp is a fixed placeholder the pod firmware + * never actually acts on for dosing (AAPS is the sole dosing decision-maker) - these + * exact fixed values, and every wire-format byte layout here, are cross-verified against + * a real captured O5 pairing's comm log (OmnipodKit's own OmniTests/O5/ + * O5CommLogFixtures.swift + O5AidCommandsTests.swift), not guessed from protocol + * documentation. + * + * The 9th AID command upstream (a pod-status query, feature `3.11`/`3.12`) is + * unconditionally skipped in OmnipodKit itself (`skipO5AID9 = true`, "isn't even + * needed") and isn't ported here for the same reason. + */ +object O5AidSetupCommands { + + fun send(session: Session) { + session.sendAidSetupCommand(utcCommand(), "ES255.2=") + session.sendAidSetupCommand(tdiCommand(), "3.2=") + session.sendAidSetupCommand(targetBgProfileCommand(), "3.1=") + session.sendAidSetupCommand(diaCommand(), "3.9=") + session.sendAidSetupCommand(egvCommand(), "3.7=") + repeat(INSULIN_HISTORY_BATCH_COUNT) { + session.sendAidSetupCommand(insulinHistoryCommand(), "ES2.1=") + } + } + + /** Feature 255.2, Extended SET - the only AID command carrying a real (non-fixed) + * value: the controller's current wall-clock time. */ + private fun utcCommand(): ByteArray { + val utcSeconds = System.currentTimeMillis() / 1000 + return "SE255.2=$utcSeconds".toByteArray(StandardCharsets.US_ASCII) + } + + /** Feature 3.2 (therapy delivery info / TDI), SET+GET - fixed 5-byte body: + * version(0x00), therapy-type(0x03), delivery-mode(0x00), bolus-speed(0x0E), + * reserved(0x00). Never varies with AAPS's actual profile. */ + private fun tdiCommand(): ByteArray { + val data = byteArrayOf(0x00, 0x03, 0x00, 0x0E, 0x00) + return "S3.2=".toByteArray(StandardCharsets.US_ASCII) + data + ",G3.2".toByteArray(StandardCharsets.US_ASCII) + } + + /** Feature 3.1 (target BG profile), SET+GET - 48 half-hour slots, each a 4-byte + * big-endian mg/dL value, all fixed at [DEFAULT_TARGET_MGDL] regardless of AAPS's + * real target profile (the pod firmware doesn't use this for dosing). */ + private fun targetBgProfileCommand(): ByteArray { + val body = ByteBuffer.allocate(2 + TARGET_SLOT_COUNT * 4) + body.putShort((TARGET_SLOT_COUNT * 4).toShort()) + repeat(TARGET_SLOT_COUNT) { body.putInt(DEFAULT_TARGET_MGDL) } + return "S3.1=".toByteArray(StandardCharsets.US_ASCII) + body.array() + ",G3.1".toByteArray(StandardCharsets.US_ASCII) + } + + /** Feature 3.9 (DIA), SET+GET - fixed ASCII value. OmnipodKit's own comment hedges on + * the exact unit semantics ("likely 8 half-hours = 4h DIA, but could be the raw + * value") - ported as the same fixed value regardless, since AAPS's own DIA setting + * is what actually governs dosing, not this pod-firmware field. */ + private fun diaCommand(): ByteArray = + "S3.9=$DEFAULT_DIA_VALUE,G3.9".toByteArray(StandardCharsets.US_ASCII) + + /** Feature 3.7 (EGV/CGM config), SET+GET - fixed ASCII composite/bitfield value; + * OmnipodKit doesn't decode its bit meaning either, it's just replicated verbatim. */ + private fun egvCommand(): ByteArray = + "S3.7=$DEFAULT_EGV_CONFIG,G3.7".toByteArray(StandardCharsets.US_ASCII) + + /** Feature 2.1 (algorithm insulin history), Extended SET - 24 all-zero 7-byte + * records (no real delivery history to report; AAPS is the dosing decision-maker, + * not the pod). */ + private fun insulinHistoryCommand(): ByteArray { + val body = ByteArray(INSULIN_HISTORY_RECORD_COUNT * INSULIN_HISTORY_RECORD_SIZE) + val header = ByteBuffer.allocate(2).putShort(body.size.toShort()).array() + return "SE2.1=".toByteArray(StandardCharsets.US_ASCII) + header + body + } + + private const val TARGET_SLOT_COUNT = 48 + private const val DEFAULT_TARGET_MGDL = 110 + private const val DEFAULT_DIA_VALUE = 8 + private const val DEFAULT_EGV_CONFIG = 3670015 + private const val INSULIN_HISTORY_RECORD_COUNT = 24 + private const val INSULIN_HISTORY_RECORD_SIZE = 7 + private const val INSULIN_HISTORY_BATCH_COUNT = 3 +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/definition/O5Protocol.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/definition/O5Protocol.kt new file mode 100644 index 000000000000..6585d2f7cba2 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/definition/O5Protocol.kt @@ -0,0 +1,12 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.definition + +/** + * The Omnipod 5 pod protocol uses a fixed nonce for every `NonceEnabledCommand` - same + * finding as Dash's own fixed `NONCE` constant in + * [app.aaps.pump.omnipod.dash.driver.OmnipodDashManagerImpl], a pod-firmware-level + * property of the shared command/response layer, not specific to either pod type. + * Shared here so [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin] and + * [app.aaps.pump.omnipod.omnipod5.ui.wizard.compose.O5OmnipodWizardViewModel] don't each + * define their own copy. + */ +const val O5_FIXED_NONCE = 1229869870 diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/AndroidKeystoreAesCipher.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/AndroidKeystoreAesCipher.kt new file mode 100644 index 000000000000..84b97f01ed7b --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/AndroidKeystoreAesCipher.kt @@ -0,0 +1,110 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.security + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.security.KeyStore +import java.util.Base64 +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.ContributesBinding +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.binding + +/** + * Encrypts/decrypts small byte payloads (here, serialized O5 registration data) using an + * AES-256-GCM key that lives inside the Android Keystore - the key material itself never + * leaves secure hardware (or the OS's protected keystore on devices without a secure + * element) and is never present in plaintext in application memory or storage. + * + * This replaces storing private key material as plain Gson-serialized `SharedPreferences` + * text, which is not meaningfully protected against a rooted device or a backup-extraction + * attack - matching OmnipodKit's own choice to use the iOS Keychain (rather than + * `UserDefaults`) for exactly this data. `AndroidKeyStore` is Android's equivalent + * hardware/OS-backed protection. + * + * IMPORTANT CAVEAT: `AndroidKeyStore` is a real Android OS keystore provider that only + * exists on an actual Android device or emulator - it cannot be exercised in a plain JVM + * test. Every other piece of cryptography built this session was verified against a real + * running implementation; this class could not be, for that reason. The AES-GCM API usage + * here follows Android's own documented key-generation and cipher patterns exactly (same + * shape as Android's official EncryptedSharedPreferences implementation), but the standard + * caveat that applies to compiled-but-unexecuted code applies doubly here - please verify + * this actually round-trips correctly on a real device/emulator before relying on it. + */ +/** + * Narrow encrypt/decrypt contract, extracted purely so [SecureO5RegistrationStorage]'s + * surrounding logic (serialization, entry merging, install orchestration) can be tested + * against a fake implementation - [AndroidKeystoreAesCipher] itself can't be exercised + * outside a real Android device/emulator (see its own class doc). + */ +interface O5RegistrationCipher { + fun encrypt(plaintext: ByteArray): String + fun decrypt(encoded: String): ByteArray +} + +@ContributesBinding(AppScope::class, binding = binding()) +class AndroidKeystoreAesCipher @Inject constructor() : O5RegistrationCipher { + + private val keyAlias: String = DEFAULT_KEY_ALIAS + + private val keyStore: KeyStore by lazy { + KeyStore.getInstance(ANDROID_KEY_STORE).apply { load(null) } + } + + private fun getOrCreateKey(): SecretKey { + (keyStore.getKey(keyAlias, null) as? SecretKey)?.let { return it } + + val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE) + val spec = KeyGenParameterSpec.Builder( + keyAlias, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT + ) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build() + keyGenerator.init(spec) + return keyGenerator.generateKey() + } + + /** + * Encrypts [plaintext] and returns a single base64 string encoding both the + * Keystore-generated IV and the ciphertext (`base64(ivLength(1 byte) || iv || ciphertext)`), + * so [decrypt] can recover the IV without needing it passed separately. + */ + override fun encrypt(plaintext: ByteArray): String { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey()) + val iv = cipher.iv + val ciphertext = cipher.doFinal(plaintext) + + require(iv.size <= 0xFF) { "Unexpectedly long IV: ${iv.size} bytes" } + val combined = byteArrayOf(iv.size.toByte()) + iv + ciphertext + return Base64.getEncoder().encodeToString(combined) + } + + /** Inverse of [encrypt]. Throws if [encoded] is malformed or decryption/auth fails. */ + override fun decrypt(encoded: String): ByteArray { + val combined = Base64.getDecoder().decode(encoded) + require(combined.isNotEmpty()) { "Encoded ciphertext is empty" } + + val ivLength = combined[0].toInt() and 0xFF + require(combined.size > 1 + ivLength) { "Encoded ciphertext is truncated" } + val iv = combined.copyOfRange(1, 1 + ivLength) + val ciphertext = combined.copyOfRange(1 + ivLength, combined.size) + + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_LENGTH_BITS, iv)) + return cipher.doFinal(ciphertext) + } + + companion object { + private const val ANDROID_KEY_STORE = "AndroidKeyStore" + private const val DEFAULT_KEY_ALIAS = "app.aaps.pump.omnipod.o5_registration_key" + private const val TRANSFORMATION = "AES/GCM/NoPadding" + private const val GCM_TAG_LENGTH_BITS = 128 + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/SecureO5RegistrationStorage.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/SecureO5RegistrationStorage.kt new file mode 100644 index 000000000000..6e7616469cf1 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/security/SecureO5RegistrationStorage.kt @@ -0,0 +1,142 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.security + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +import com.google.gson.Gson +import com.google.gson.reflect.TypeToken +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.Inject +import dev.zacsweers.metro.SingleIn + +/** + * Persists O5 registration (credential) data across app restarts, encrypted at rest via + * [AndroidKeystoreAesCipher] - the persistence-layer counterpart to + * [app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData]'s in-memory + * registry, mirroring OmnipodKit's O5CertificateKeychain.swift. + * + * Call [loadAndInstallAll] once at app startup (before any O5 pairing/connection code + * runs) to restore previously-imported credentials into the in-memory registry. Call + * [persistEntry] whenever a new credential is imported (e.g. via a future settings screen + * accepting a packed string or keypair file) so it survives the next cold start. + * + * Note on scope: only [O5RegistrationData.O5RegistrationSource.IMPORTED] entries are + * persisted here - BUILT_IN entries are, by definition, re-derived from the compiled + * ServiceLoader-discovered module on every app start, and DOWNLOADED entries aren't a + * pattern this codebase actually implements yet (see O5RegistrationData's class doc). + */ +@SingleIn(AppScope::class) +class SecureO5RegistrationStorage @Inject constructor( + private val logger: AAPSLogger, + private val preferences: Preferences, + private val cipher: O5RegistrationCipher +) { + + private val gson = Gson() + + /** JSON-serializable shape for one persisted entry (Gson can't serialize the real + * [O5RegistrationData.O5RegistrationSource] enum's name reliably across app updates + * if it's ever reordered, so persist the name as a plain string defensively). */ + private data class PersistedEntry( + val controllerId: Long, + val privateKeyHex: String, + val publicKeyHex: String, + val intermediateCABase64: String, + val tlsCertificateBase64: String, + val sourceName: String + ) + + /** + * Loads any previously-persisted, imported registration entries and installs them into + * [O5RegistrationData]'s in-memory registry. Safe to call even if nothing has ever been + * persisted (no-ops). Logs and skips (rather than throwing) if decryption fails - e.g. + * after a device restore where the Keystore key itself didn't survive, which is + * expected Android Keystore behavior, not a bug. + */ + fun loadAndInstallAll() { + val encrypted = preferences.getIfExists(O5StringNonPreferenceKey.RegistrationData) + if (encrypted.isNullOrEmpty()) return + + try { + val json = String(cipher.decrypt(encrypted), Charsets.UTF_8) + val entries = parseEntries(json) + for (entry in entries) { + val data = O5RegistrationData( + controllerId = entry.controllerId, + privateKeyHex = entry.privateKeyHex, + publicKeyHex = entry.publicKeyHex, + intermediateCABase64 = entry.intermediateCABase64, + tlsCertificateBase64 = entry.tlsCertificateBase64 + ) + val source = try { + O5RegistrationData.O5RegistrationSource.valueOf(entry.sourceName) + } catch (_: IllegalArgumentException) { + O5RegistrationData.O5RegistrationSource.IMPORTED + } + O5RegistrationData.install(data, source) + } + logger.debug(LTag.PUMPCOMM, "Restored ${entries.size} persisted O5 registration entr${if (entries.size == 1) "y" else "ies"}") + } catch (ex: Exception) { + logger.error(LTag.PUMPCOMM, "Failed to load/decrypt persisted O5 registration data", ex) + } + } + + /** + * Persists [data] (with the given [source]) so it survives app restarts, alongside any + * other already-persisted entries. Re-encrypts and re-saves the entire entry set - simple + * and safe for the very small number of entries (realistically 1) this ever holds. + */ + fun persistEntry(data: O5RegistrationData, source: O5RegistrationData.O5RegistrationSource) { + try { + val current = loadPersistedEntriesOnly().filterNot { it.controllerId == data.controllerId } + val updated = current + PersistedEntry( + controllerId = data.controllerId, + privateKeyHex = data.privateKeyHex, + publicKeyHex = data.publicKeyHex, + intermediateCABase64 = data.intermediateCABase64, + tlsCertificateBase64 = data.tlsCertificateBase64, + sourceName = source.name + ) + saveEntries(updated) + logger.debug(LTag.PUMPCOMM, "Persisted O5 registration entry for controller 0x%08X".format(data.controllerId)) + } catch (ex: Exception) { + logger.error(LTag.PUMPCOMM, "Failed to encrypt/persist O5 registration data", ex) + } + } + + /** Removes a persisted entry (e.g. when the user deletes a saved credential). Does not + * affect the in-memory registry - call [O5RegistrationData.remove] separately if the + * entry should also stop being usable immediately, not just on next restart. */ + fun removeEntry(controllerId: Long) { + try { + val current = loadPersistedEntriesOnly().filterNot { it.controllerId == controllerId } + saveEntries(current) + } catch (ex: Exception) { + logger.error(LTag.PUMPCOMM, "Failed to remove persisted O5 registration entry", ex) + } + } + + private fun loadPersistedEntriesOnly(): List { + val encrypted = preferences.getIfExists(O5StringNonPreferenceKey.RegistrationData) + if (encrypted.isNullOrEmpty()) return emptyList() + return try { + parseEntries(String(cipher.decrypt(encrypted), Charsets.UTF_8)) + } catch (ex: Exception) { + logger.error(LTag.PUMPCOMM, "Failed to decrypt existing O5 registration data before update", ex) + emptyList() + } + } + + private fun saveEntries(entries: List) { + val json = gson.toJson(entries) + val encrypted = cipher.encrypt(json.toByteArray(Charsets.UTF_8)) + preferences.put(O5StringNonPreferenceKey.RegistrationData, encrypted) + } + + private fun parseEntries(json: String): List { + val type = object : TypeToken>() {}.type + return gson.fromJson(json, type) ?: emptyList() + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManager.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManager.kt new file mode 100644 index 000000000000..f72ac4dc369f --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManager.kt @@ -0,0 +1,676 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.core.data.model.BS +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.pump.omnipod.common.bledriver.comm.pair.PairResult +import app.aaps.pump.omnipod.common.bledriver.comm.session.EapSqn +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.SoftwareVersion +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse +import app.aaps.pump.omnipod.common.util.PodTimeZone +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5IdRotation +import java.io.Serializable +import java.util.Calendar +import java.util.EnumSet +import java.util.TimeZone +import java.util.concurrent.atomic.AtomicInteger +import kotlin.math.roundToInt + +/** + * Persisted/in-memory state needed to connect to, pair with, and read status from an + * Omnipod 5 pod, plus the dosing/control state ([app.aaps.pump.omnipod.omnipod5.O5PumpPlugin] + * needs to track basal program, last bolus, active temp basal, and + * an in-flight dose command whose outcome is still uncertain (BLE response never + * arrived) so it can be reconciled on the next status poll. Deliberately does NOT use a + * Dash-style historyId/persisted-ledger (`OmnipodDashPodStateManager.ActiveCommand`) + * to track in-flight commands - [app.aaps.pump.omnipod.omnipod5.bledriver.comm + * .O5BleManager.sendCommand] already gives 1:1 request/response correlation per call + * (unlike Dash's continuous connection-scoped event bus), so [pendingDoseCommand] only + * needs to be a single flat marker, not a ledger. + * + * [updateFromDefaultStatusResponse] also saves command acceptance before another command + * can replace its sequence. Responses are reused from [VersionResponse]/[DefaultStatusResponse], which turned + * out to have no Dash-specific assumptions baked in (pure byte-offset parsing), matching + * the same finding as [app.aaps.pump.omnipod.common.bledriver.pod.command.base + * .HeaderEnabledCommand]. + */ +interface O5PodStateManager { + + enum class BluetoothConnectionState { CONNECTING, CONNECTED, DISCONNECTED } + + var bluetoothConnectionState: BluetoothConnectionState + var connectionAttempts: Int + var successfulConnections: Int + + /** The Bluetooth MAC address of the paired pod, once known. */ + var bluetoothAddress: String? + + /** The certificate-derived controller id used for this pod's O5 identity (see + * [app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5CertificateStore.controllerId]). */ + var controllerId: Long? + + /** The pod's own id, once paired. */ + var podId: Long? + + var nextPodId: Long? + + /** The pod's long-term key, once paired. Null until [updateFromPairing] is called. */ + var ltk: ByteArray? + + /** Message sequence number to resume from after pairing/reconnection. */ + var msgSequenceNumber: Byte + + /** Advances [msgSequenceNumber] by one, wrapping at 4 bits (0x0-0xf) - the pod's + * command-header sequence number, distinct from the BLE-packet-level session + * sequence number the [app.aaps.pump.omnipod.common.bledriver.comm.session.Session] + * layer manages on its own. Must be called after every command round trip (sent, + * send-unconfirmed, or response received) or the pod will NAK every command after + * the first in a session - mirrors [OmnipodDashPodStateManager + * .increaseMessageSequenceNumber]. */ + fun increaseMessageSequenceNumber() + + var eapAkaSequenceNumber: Long + + /** How far through physical pod activation (pairing, prime, cannula insertion) the + * pod has progressed - default [ActivationProgress.NOT_STARTED]. Drives + * [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin.isBusy] and lets + * [app.aaps.pump.omnipod.omnipod5.ui.wizard.compose.O5OmnipodWizardViewModel] resume + * a retried activation without resending already-completed steps. */ + var activationProgress: ActivationProgress + + + var primePulseRate: Short? + var firstPrimeBolusVolume: Short? + var secondPrimeBolusVolume: Short? + var podLifeInHours: Short? + + + /** The basal program currently believed to be running on the pod. */ + var basalProgram: BasalProgram? + + /** Time zone id of the phone when the pod clock was last set (with [basalProgram]). + * Null until the first basal program is sent. */ + val timeZoneId: String? + + /** UTC offset (ms) of the phone when the pod clock was last set. Null until the first + * basal program is sent. */ + val timeZoneOffset: Int? + + /** Wall-clock time when [timeZoneOffset] was last set. */ + val timeZoneUpdated: Long? + + /** Records the phone's current time zone as the pod's time zone. Call after every + * successful basal program, because that command also sets the pod clock. Mirrors + * `OmnipodDashPodStateManager.updateTimeZone`. */ + fun updateTimeZone() + fun confirmTimeZone(timeZone: PodTimeZone) + + /** Allows recovery of a suspend started by automatic time correction, including after restart. */ + var timeChangeInProgress: Boolean + + /** False when the phone's current UTC offset differs from the pod's, so the pod runs + * the basal schedule at the wrong hours. True when the pod offset is not known yet + * (for example a pod activated before this was tracked), so no false warning is shown. */ + val sameTimeZone: Boolean + get() { + val podOffset = timeZoneOffset ?: return true + return TimeZone.getDefault().getOffset(System.currentTimeMillis()) == podOffset + } + + /** True while the pod's delivery is suspended (no basal/temp basal delivery). */ + var deliverySuspended: Boolean + + var lastBolusStartTime: Long? + var lastBolusRequestedUnits: Double? + + /** Null until the bolus is confirmed delivered (fully or partially - see + * [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin]'s bolus-completion polling). */ + var lastBolusDeliveredUnits: Double? + + var activeTempBasalStartTime: Long? + var activeTempBasalRate: Double? + var activeTempBasalDurationMinutes: Short? + + /** + * A single dose-affecting command whose outcome is not yet confirmed - set + * optimistically right before the [app.aaps.pump.omnipod.omnipod5.bledriver.comm + * .O5BleManager.sendCommand] `Observable` for a bolus/temp-basal/basal-program + * command is subscribed, and cleared once the next status response confirms (or + * denies) it actually took effect. This is the field that makes uncertain BLE + * outcomes (dose sent but response never arrived) recoverable rather than silently + * lost - see [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin]'s reconciliation logic. + */ + var pendingDoseCommand: PendingDoseCommand? + + enum class PendingDoseType { BOLUS, TEMP_BASAL_START, TEMP_BASAL_CANCEL, BASAL_PROGRAM } + + data class PendingDoseCommand( + val type: PendingDoseType, + val requestedUnits: Double? = null, + val requestedRate: Double? = null, + val requestedDurationMinutes: Short? = null, + /** Only set for [PendingDoseType.BOLUS] - needed to correctly finalize + * [app.aaps.core.interfaces.pump.PumpSync.syncBolusWithPumpId] if the original + * call never reached its own sync step. */ + val bolusType: BS.Type? = null, + val startedAt: Long, + /** + * The 4-bit command sequence number this dose was sent with, captured from + * [msgSequenceNumber] immediately before building the command. + * + * This is what makes an uncertain outcome *decidable* rather than guessable: the pod + * reports the sequence number of the last programming command it accepted (see + * [sequenceNumberOfLastProgrammingCommand]). A later bolus stop replaces that value, + * so its sequence is saved separately and cannot reject the original bolus. + * Without a sequence, reconciliation can only look at + * whether delivery is currently active, which cannot tell a bolus that finished from + * one that never started. + * + * Null only for a [PendingDoseCommand] restored from a state file written before this + * field existed; reconciliation falls back to the delivery-status heuristic then. + */ + val sequenceNumber: Short? = null, + /** True only for the micro-bolus `O5PumpPlugin.deliverBasalCorrection` + * issues - excluded from [cumulativeBolusPulsesDelivered] + * tracking so it counts toward delivered *basal* insulin, not bolus insulin + * (the whole point of the correction is to true up basal drift). */ + val isBasalCorrection: Boolean = false, + val bolusRecordExpected: Boolean = false, + /** Pod acceptance saved from a matching sequence or observed bolus delivery, + * never from a BLE write alone. */ + val confirmedByStatus: Boolean = false, + val historyId: Long? = null, + val tempBasalType: PumpSync.TemporaryBasalType? = null, + val requestedBasalProgram: BasalProgram? = null, + val basalTimeZone: PodTimeZone? = null, + /** A stop command replaces the pod's last programming sequence. Keep its intent + * separate from acceptance of the original bolus, including across restarts. + * Null in older state files, where cancellation intent was not saved. */ + val bolusCancelRequested: Boolean? = false, + val bolusCancelSequenceNumber: Short? = null, + val bolusCancelHistoryId: Long? = null, + /** Ordinary bolus pulses already included in [cumulativeBolusPulsesDelivered]. + * Saved with each status; completion adds only the remainder. Older files start at zero. */ + val accountedBolusPulses: Int = 0 + ) : Serializable { + + /** Acceptance alone does not make an unrelated status's remaining count belong to this bolus. + * A stop sequence is useful only if acceptance of the original bolus was already saved. + * Use remaining pulses, not total pulse growth: basal can run at the same time. */ + internal fun deliveredBolusPulses(podSequence: Short?, status: DeliveryStatus?, remaining: Short?): Int? { + if (type != PendingDoseType.BOLUS || !confirmedByStatus || + status == null || status == DeliveryStatus.UNKNOWN || status == DeliveryStatus.PRIMING || remaining == null + ) return null + val matchesBolus = sequenceNumber != null && podSequence != null && + (sequenceNumber.toInt() and 0x0f) == (podSequence.toInt() and 0x0f) + val matchesCancel = bolusCancelRequested == true && bolusCancelSequenceNumber != null && podSequence != null && + (bolusCancelSequenceNumber.toInt() and 0x0f) == (podSequence.toInt() and 0x0f) + if (!matchesBolus && !matchesCancel && !status.bolusDeliveringActive()) return null + val requestedPulses = ((requestedUnits ?: return null) / PodConstants.POD_PULSE_BOLUS_UNITS).roundToInt() + if (remaining.toInt() !in 0..requestedPulses) return null + return requestedPulses - remaining + } + + /** Saved progress only grows, so repeated status never adds the same ordinary bolus pulses twice. */ + internal fun withPodProgress(podSequence: Short, status: DeliveryStatus, remaining: Short): PendingDoseCommand { + val accepted = withPodAcceptance(podSequence, status) + if (isBasalCorrection) return accepted + val delivered = accepted.deliveredBolusPulses(podSequence, status, remaining) ?: return accepted + return if (delivered > accountedBolusPulses) accepted.copy(accountedBolusPulses = delivered) else accepted + } + } + + + val podStatus: PodStatus? + val deliveryStatus: DeliveryStatus? + + val isActivationCompleted: Boolean + get() = activationProgress == ActivationProgress.COMPLETED + + val isSuspended: Boolean + get() = deliveryStatus?.equals(DeliveryStatus.SUSPENDED) == true + + val isPodRunning: Boolean + get() = podStatus?.isRunning() == true + + /** + * The pod has stopped delivering for good - it faulted or was deactivated. + * + * Derived from [podStatus], which every routine status poll refreshes, so this is the + * dependable fault signal. [alarmType] carries the *reason* but only arrives with an + * alarm-status response, which the pod sends solely in reply to an explicit request for + * that page - so a fault would otherwise go unnoticed until something asked. Mirrors the + * Dash driver's `isPodKaput`. + */ + val isPodKaput: Boolean + get() = podStatus in arrayOf(PodStatus.ALARM, PodStatus.DEACTIVATED) || isPodActivationTimeExceeded + val isPodActivationTimeExceeded: Boolean + get() = podStatus?.isActivationTimeExceeded() == true + val firmwareVersion: SoftwareVersion? + val bleVersion: SoftwareVersion? + val lotNumber: Long? + val podSequenceNumber: Long? + val totalPulsesDelivered: Short? + val bolusPulsesRemaining: Short? + val reservoirPulsesRemaining: Short? + val activeAlerts: EnumSet? + val minutesSinceActivation: Short? + val sequenceNumberOfLastProgrammingCommand: Short? + + /** System.currentTimeMillis() when the last status was received, or null if never. */ + val lastStatusResponseReceived: Long? + + + val alarmType: AlarmType? + /** Dash-style fault reference captured from the first detailed fault response. */ + val pdmRef: String? + /** Pod-clock minutes-since-activation timestamp of when the alarm occurred (not a + * wall-clock time - the pod has no wall clock of its own). */ + val alarmTime: Short? + val occlusionAlarm: Boolean? + val podStatusWhenAlarmOccurred: PodStatus? + val rssi: Short? + + /** True after recording the current fault or activation timeout with [PumpSync.insertAnnouncement]. + * An unread fault stays pending so a later status check can record its code and reference. + * Set by `O5PumpPlugin.checkPodFault`, called from its stopped-pod handling. + * Mirrors `OmnipodDashPodStateManager.alarmSynced`; reset only via [reset] (a new pod pairing). */ + var alarmSynced: Boolean + + + /** Wall-clock epoch millis the pod was activated, computed from status page 5's + * date fields - unlike [minutesSinceActivation], this survives across app + * restarts without drifting (it isn't a relative counter). Null until page 5 has + * been fetched at least once. */ + val podActivatedAt: Long? + + /** Pod-clock minutes-since-activation each [AlertType] slot last triggered, from + * status page 1. Only contains entries for slots that have actually triggered + * (value 0 = never triggered, per OmnipodKit's own convention, so those are + * filtered out here). Null until page 1 has been fetched at least once. */ + val triggeredAlertTimes: Map? + + + /** True while the pod's SUSPEND_ENDED alert is still armed from a prior suspend - + * set by [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin]'s suspendDelivery(), cleared by + * its disableSuspendAlerts() once delivery resumes (silences the nuisance beep for a + * suspend/resume the user/algorithm caused intentionally). */ + var suspendAlertsEnabled: Boolean + + data class SyncedAlertSettings( + val expirationReminderEnabled: Boolean, + val expirationReminderHours: Int, + val expirationAlarmEnabled: Boolean, + val expirationAlarmHours: Int, + val lowReservoirAlertEnabled: Boolean, + val lowReservoirAlertUnits: Int + ) : Serializable + + /** The alert preference values last successfully pushed to the pod - null until + * [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin]'s updateAlertConfiguration() first + * succeeds. Compared against current preferences to skip redundant re-syncs. */ + var syncedAlertSettings: SyncedAlertSettings? + + + /** Integrated expected basal delivery (units) since [O5PodStateManager] started + * tracking it (right after activation completes) - compared against actual delivered + * basal insulin ([app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.basalDelivered]) + * to detect drift. Null until the first post-activation status poll. */ + var basalExpected: Double? + + /** Wall-clock time of the last basal-drift correction bolus - a cooldown to prevent + * rapid repeated corrections. Null if none has ever been delivered. */ + var lastBasalCorrectionTime: Long? + + /** True while a basal-drift correction bolus is in flight - prevents + * [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin.deliverTreatment] + * concurrency guards from misreading it as a user-requested bolus. */ + var basalCorrectionInProgress: Boolean + + /** Cumulative pod pulses attributed to boluses (not basal) since activation completed - + * subtracted from [totalPulsesDelivered] to isolate delivered basal insulin. Excludes + * basal-correction boluses themselves (see [PendingDoseCommand.isBasalCorrection]). + * Initialized to [totalPulsesDelivered] at the moment activation completes (see + * [app.aaps.pump.omnipod.omnipod5.ui.wizard.compose.O5OmnipodWizardViewModel]), so + * priming/cannula-insertion pulses are excluded from the basal bucket too. */ + var cumulativeBolusPulsesDelivered: Short? + + fun updateFromVersionResponse(response: VersionResponse) + fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) + fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) + + /** Populates [podActivatedAt] plus [alarmType]/[alarmTime] (page 5 reports the same + * fault info [AlarmStatusResponse] does). */ + fun updateFromActivationTimeResponse(response: PodInfoActivationTimeResponse) + + /** Populates [triggeredAlertTimes] from page 1's 8 alert-slot values. */ + fun updateFromTriggeredAlertsResponse(response: PodInfoTriggeredAlertsResponse) + + /** Populates the prime-bolus parameters ([primePulseRate], [firstPrimeBolusVolume], + * [secondPrimeBolusVolume], [podLifeInHours]) plus version/status/lot/sequence + * fields - mirrors [OmnipodDashPodStateManager.updateFromSetUniqueIdResponse]. */ + fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) + + /** + * Returns the next EAP-AKA sequence number (as its 6-byte on-wire [EapSqn] + * representation) without yet committing it - matching + * [OmnipodDashPodStateManager]'s increment-then-commit-on-success pattern, so a + * failed session establishment doesn't advance the persisted counter. + */ + fun increaseEapAkaSequenceNumber(): ByteArray + fun commitEapAkaSequenceNumber() + + fun updateFromPairing(controllerId: Long, podId: Long, pairResult: PairResult) + + fun completeBolus(startedAt: Long, requestedUnits: Double, deliveredUnits: Double, deliveredPulses: Short?) + + fun reset() +} + +/** + * Simple in-memory [O5PodStateManager]. Not persisted across process restarts - use + * [PersistedO5PodStateManager] for that; this is mainly useful for tests. + */ +class InMemoryO5PodStateManager : O5PodStateManager { + + @Volatile override var bluetoothConnectionState: O5PodStateManager.BluetoothConnectionState = + O5PodStateManager.BluetoothConnectionState.DISCONNECTED + + private val connectionAttemptsCounter = AtomicInteger(0) + override var connectionAttempts: Int + get() = connectionAttemptsCounter.get() + set(value) { connectionAttemptsCounter.set(value) } + + private val successfulConnectionsCounter = AtomicInteger(0) + override var successfulConnections: Int + get() = successfulConnectionsCounter.get() + set(value) { successfulConnectionsCounter.set(value) } + + @Volatile override var bluetoothAddress: String? = null + @Volatile override var controllerId: Long? = null + @Volatile override var podId: Long? = null + @Volatile override var nextPodId: Long? = null + @Volatile override var ltk: ByteArray? = null + @Volatile override var msgSequenceNumber: Byte = 1 + + @Volatile override var eapAkaSequenceNumber: Long = 0 + @Volatile private var pendingEapAkaSequenceNumber: Long = 0 + + @Volatile override var activationProgress: ActivationProgress = ActivationProgress.NOT_STARTED + @Volatile override var primePulseRate: Short? = null + @Volatile override var firstPrimeBolusVolume: Short? = null + @Volatile override var secondPrimeBolusVolume: Short? = null + @Volatile override var podLifeInHours: Short? = null + + @Volatile override var basalProgram: BasalProgram? = null + @Volatile override var timeZoneId: String? = null + private set + @Volatile override var timeZoneOffset: Int? = null + private set + @Volatile override var timeZoneUpdated: Long? = null + private set + @Volatile override var deliverySuspended: Boolean = false + @Volatile override var lastBolusStartTime: Long? = null + @Volatile override var lastBolusRequestedUnits: Double? = null + @Volatile override var lastBolusDeliveredUnits: Double? = null + @Volatile override var activeTempBasalStartTime: Long? = null + @Volatile override var activeTempBasalRate: Double? = null + @Volatile override var activeTempBasalDurationMinutes: Short? = null + @Volatile override var pendingDoseCommand: O5PodStateManager.PendingDoseCommand? = null + @Volatile override var timeChangeInProgress: Boolean = false + + override fun increaseMessageSequenceNumber() { + msgSequenceNumber = ((msgSequenceNumber.toInt() + 1) and 0x0f).toByte() + } + + override fun updateTimeZone() = confirmTimeZone(PodTimeZone.now()) + + override fun confirmTimeZone(timeZone: PodTimeZone) { + timeZoneOffset = timeZone.offset + timeZoneId = timeZone.id + timeZoneUpdated = timeZone.updatedAt + } + + @Volatile override var podStatus: PodStatus? = null + private set + @Volatile override var deliveryStatus: DeliveryStatus? = null + private set + @Volatile override var firmwareVersion: SoftwareVersion? = null + private set + @Volatile override var bleVersion: SoftwareVersion? = null + private set + @Volatile override var lotNumber: Long? = null + private set + @Volatile override var podSequenceNumber: Long? = null + private set + @Volatile override var totalPulsesDelivered: Short? = null + private set + @Volatile override var bolusPulsesRemaining: Short? = null + private set + @Volatile override var reservoirPulsesRemaining: Short? = null + private set + @Volatile override var activeAlerts: EnumSet? = null + private set + @Volatile override var minutesSinceActivation: Short? = null + private set + @Volatile override var sequenceNumberOfLastProgrammingCommand: Short? = null + private set + @Volatile override var lastStatusResponseReceived: Long? = null + private set + + @Volatile override var alarmType: AlarmType? = null + private set + @Volatile override var pdmRef: String? = null + private set + @Volatile override var alarmTime: Short? = null + private set + @Volatile override var occlusionAlarm: Boolean? = null + private set + @Volatile override var podStatusWhenAlarmOccurred: PodStatus? = null + private set + @Volatile override var rssi: Short? = null + private set + @Volatile override var alarmSynced: Boolean = false + + @Volatile override var podActivatedAt: Long? = null + private set + @Volatile override var triggeredAlertTimes: Map? = null + private set + + @Volatile override var suspendAlertsEnabled: Boolean = true + @Volatile override var syncedAlertSettings: O5PodStateManager.SyncedAlertSettings? = null + @Volatile override var basalExpected: Double? = null + @Volatile override var lastBasalCorrectionTime: Long? = null + @Volatile override var basalCorrectionInProgress: Boolean = false + @Volatile override var cumulativeBolusPulsesDelivered: Short? = null + + override fun increaseEapAkaSequenceNumber(): ByteArray { + pendingEapAkaSequenceNumber = eapAkaSequenceNumber + 1 + return EapSqn(pendingEapAkaSequenceNumber).value + } + + override fun commitEapAkaSequenceNumber() { + eapAkaSequenceNumber = pendingEapAkaSequenceNumber + } + + override fun updateFromPairing(controllerId: Long, podId: Long, pairResult: PairResult) { + this.controllerId = controllerId + this.podId = podId + ltk = pairResult.ltk + msgSequenceNumber = pairResult.msgSeq + } + + override fun updateFromVersionResponse(response: VersionResponse) { + podStatus = response.podStatus + firmwareVersion = SoftwareVersion(response.firmwareVersionMajor, response.firmwareVersionMinor, response.firmwareVersionInterim) + bleVersion = SoftwareVersion(response.bleVersionMajor, response.bleVersionMinor, response.bleVersionInterim) + lotNumber = response.lotNumber + podSequenceNumber = response.podSequenceNumber + lastStatusResponseReceived = System.currentTimeMillis() + } + + @Synchronized + override fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) { + val previousUpdate = lastStatusResponseReceived + val now = System.currentTimeMillis() + totalPulsesDelivered = response.totalPulsesDelivered + updatePendingBolus(response.sequenceNumberOfLastProgrammingCommand, response.deliveryStatus, response.bolusPulsesRemaining) + basalExpected = nextBasalExpected(previousUpdate, now) + podStatus = response.podStatus + deliveryStatus = response.deliveryStatus + bolusPulsesRemaining = response.bolusPulsesRemaining + if (response.reservoirPulsesRemaining < 1023) { + reservoirPulsesRemaining = response.reservoirPulsesRemaining + } + activeAlerts = response.activeAlerts + minutesSinceActivation = response.minutesSinceActivation + sequenceNumberOfLastProgrammingCommand = response.sequenceNumberOfLastProgrammingCommand + lastStatusResponseReceived = now + } + + @Synchronized + override fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) { + podStatus = response.podStatus + deliveryStatus = response.deliveryStatus + totalPulsesDelivered = response.totalPulsesDelivered + bolusPulsesRemaining = response.bolusPulsesRemaining + if (response.reservoirPulsesRemaining < 1023) { + reservoirPulsesRemaining = response.reservoirPulsesRemaining + } + activeAlerts = response.activeAlerts + minutesSinceActivation = response.minutesSinceActivation + sequenceNumberOfLastProgrammingCommand = response.sequenceNumberOfLastProgrammingCommand + updatePendingBolus(response.sequenceNumberOfLastProgrammingCommand, response.deliveryStatus, response.bolusPulsesRemaining) + alarmType = response.alarmType + alarmTime = response.alarmTime + // Later responses can change the diagnostic snapshot used in the reference. + if (pdmRef == null) pdmRef = response.pdmRef + occlusionAlarm = response.occlusionAlarm + podStatusWhenAlarmOccurred = response.podStatusWhenAlarmOccurred + rssi = response.rssi + lastStatusResponseReceived = System.currentTimeMillis() + } + + private fun updatePendingBolus(sequence: Short, status: DeliveryStatus, remaining: Short) { + val pending = pendingDoseCommand ?: return + val updated = pending.withPodProgress(sequence, status, remaining) + val delta = updated.accountedBolusPulses - pending.accountedBolusPulses + if (delta > 0) cumulativeBolusPulsesDelivered = ((cumulativeBolusPulsesDelivered ?: 0) + delta).toShort() + pendingDoseCommand = updated + } + + override fun updateFromActivationTimeResponse(response: PodInfoActivationTimeResponse) { + val calendar = Calendar.getInstance() + calendar.set(2000 + response.year, response.month - 1, response.day, response.hour, response.minute, 0) + calendar.set(Calendar.MILLISECOND, 0) + podActivatedAt = calendar.timeInMillis + alarmType = response.faultEventCode + alarmTime = response.faultTime + } + + override fun updateFromTriggeredAlertsResponse(response: PodInfoTriggeredAlertsResponse) { + triggeredAlertTimes = response.alertActivations.filterValues { it != 0.toShort() } + } + + override fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) { + primePulseRate = response.primePumpRate + firstPrimeBolusVolume = response.numberOfEngagingClutchDrivePulses + secondPrimeBolusVolume = response.numberOfPrimePulses + podLifeInHours = response.podExpirationTimeInHours + firmwareVersion = SoftwareVersion(response.firmwareVersionMajor, response.firmwareVersionMinor, response.firmwareVersionInterim) + bleVersion = SoftwareVersion(response.bleVersionMajor, response.bleVersionMinor, response.bleVersionInterim) + podStatus = response.podStatus + lotNumber = response.lotNumber + podSequenceNumber = response.podSequenceNumber + lastStatusResponseReceived = System.currentTimeMillis() + } + + @Synchronized + override fun completeBolus(startedAt: Long, requestedUnits: Double, deliveredUnits: Double, deliveredPulses: Short?) { + val alreadyCompleted = lastBolusStartTime == startedAt && lastBolusDeliveredUnits != null + val pending = pendingDoseCommand?.takeIf { it.startedAt == startedAt } + if (!alreadyCompleted && deliveredPulses != null && pending?.isBasalCorrection != true) { + val remainder = (deliveredPulses.toInt() - (pending?.accountedBolusPulses ?: 0)).coerceAtLeast(0) + cumulativeBolusPulsesDelivered = ((cumulativeBolusPulsesDelivered ?: 0) + remainder).toShort() + } + lastBolusStartTime = startedAt + lastBolusRequestedUnits = requestedUnits + lastBolusDeliveredUnits = deliveredUnits + if (pendingDoseCommand?.startedAt == startedAt) { + pendingDoseCommand = null + } + } + + override fun reset() { + val retainedControllerId = controllerId + val retainedNextPodId = podId?.let(O5IdRotation::nextPodId) ?: nextPodId + bluetoothConnectionState = O5PodStateManager.BluetoothConnectionState.DISCONNECTED + connectionAttemptsCounter.set(0) + successfulConnectionsCounter.set(0) + bluetoothAddress = null + controllerId = retainedControllerId + podId = null + nextPodId = retainedNextPodId + ltk = null + msgSequenceNumber = 1 + eapAkaSequenceNumber = 0 + pendingEapAkaSequenceNumber = 0 + activationProgress = ActivationProgress.NOT_STARTED + primePulseRate = null + firstPrimeBolusVolume = null + secondPrimeBolusVolume = null + podLifeInHours = null + basalProgram = null + timeZoneId = null + timeZoneOffset = null + timeZoneUpdated = null + timeChangeInProgress = false + deliverySuspended = false + lastBolusStartTime = null + lastBolusRequestedUnits = null + lastBolusDeliveredUnits = null + activeTempBasalStartTime = null + activeTempBasalRate = null + activeTempBasalDurationMinutes = null + pendingDoseCommand = null + podStatus = null + deliveryStatus = null + firmwareVersion = null + bleVersion = null + lotNumber = null + podSequenceNumber = null + totalPulsesDelivered = null + bolusPulsesRemaining = null + reservoirPulsesRemaining = null + activeAlerts = null + minutesSinceActivation = null + sequenceNumberOfLastProgrammingCommand = null + lastStatusResponseReceived = null + alarmType = null + pdmRef = null + alarmTime = null + occlusionAlarm = null + podStatusWhenAlarmOccurred = null + rssi = null + alarmSynced = false + podActivatedAt = null + triggeredAlertTimes = null + suspendAlertsEnabled = true + syncedAlertSettings = null + basalExpected = null + lastBasalCorrectionTime = null + basalCorrectionInProgress = false + cumulativeBolusPulsesDelivered = null + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManagerExtensions.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManagerExtensions.kt new file mode 100644 index 000000000000..799f6e8de549 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManagerExtensions.kt @@ -0,0 +1,165 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import java.time.Duration +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.util.TimeZone + +/** + * Estimated pod expiration time, mirroring + * `OmnipodDashPodStateManagerImpl.expiry`'s formula (including its unexplained + * `.minusHours(8)` grace-period adjustment, copied verbatim rather than guessed at) - + * null until [O5PodStateManager.podLifeInHours]/[O5PodStateManager.minutesSinceActivation] + * are known (i.e. before [app.aaps.pump.omnipod.common.bledriver.pod.response + * .SetUniqueIdResponse] has been received during activation). + */ +val O5PodStateManager.expiry: ZonedDateTime? + get() { + val hours = podLifeInHours ?: return null + val minutes = minutesSinceActivation ?: return null + val lastUpdated = lastStatusResponseReceived ?: return null + return ZonedDateTime.now() + .plusHours(hours.toLong()) + .minusMinutes(minutes.toLong()) + .minus(Duration.ofMillis(System.currentTimeMillis() - lastUpdated)) + .minusHours(8) + } + + +/** + * Wall-clock epoch millis the pod was activated. Prefers [O5PodStateManager.podActivatedAt] + * (read from status page 5) and falls back to the same derivation Dash uses when that page + * has not been fetched: the time of the last status response minus + * [O5PodStateManager.minutesSinceActivation]. Null when neither is known. + */ +val O5PodStateManager.activationTime: Long? + get() = podActivatedAt ?: run { + val minutes = minutesSinceActivation ?: return null + val lastUpdated = lastStatusResponseReceived ?: return null + lastUpdated - minutes * 60_000L + } + +/** + * The current time on the pod's own clock, in the time zone the pod was last set to. + * The pod has no wall clock, so this is rebuilt the same way + * [app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManagerImpl.time] + * does it: activation instant, plus the elapsed minutes the pod reported, plus the time + * that has passed since that report arrived. Null until the pod clock's time zone is + * known, which happens the first time a basal program is sent. + */ +val O5PodStateManager.time: ZonedDateTime? + get() { + val activatedAt = activationTime ?: return null + val minutes = minutesSinceActivation ?: return null + val offset = timeZoneOffset ?: return null + val lastUpdated = lastStatusResponseReceived ?: return null + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(activatedAt), ZoneId.ofOffset("", ZoneOffset.ofTotalSeconds(offset / 1000))) + .plusMinutes(minutes.toLong()) + .plus(Duration.ofMillis(System.currentTimeMillis() - lastUpdated)) + } + +/** How far [time] runs ahead (positive) or behind (negative) the phone clock. */ +val O5PodStateManager.timeDrift: Duration? + get() = time?.let { Duration.between(ZonedDateTime.now(), it) } + + +/** [O5PodStateManager.totalPulsesDelivered] minus pulses already attributed to boluses - + * null until both are known (i.e. before activation completes and + * [O5PodStateManager.cumulativeBolusPulsesDelivered] is initialized). */ +val O5PodStateManager.basalPulsesDelivered: Short? + get() { + val total = totalPulsesDelivered ?: return null + val bolus = cumulativeBolusPulsesDelivered ?: return null + return (total - bolus).toShort() + } + +val O5PodStateManager.basalDelivered: Double + get() = (basalPulsesDelivered ?: 0) * PodConstants.POD_PULSE_BOLUS_UNITS + +/** Positive = over-delivery, negative = under-delivery, relative to [O5PodStateManager + * .basalExpected]. */ +val O5PodStateManager.basalDrift: Double + get() = basalDelivered - (basalExpected ?: basalDelivered) + +/** + * Integrates expected basal delivery (units) over `[startTime, endTime]`, accounting for + * an active temp basal overriding the scheduled program during its window. Mirrors + * `OmnipodDashPodStateManagerImpl.integrateExpectedDelivery`. A known pod offset stays + * fixed until a basal program confirms the new time, including during a DST transition. + */ +fun integrateO5ExpectedDelivery( + startTime: Long, + endTime: Long, + activeTempBasalStartTime: Long?, + activeTempBasalRate: Double?, + activeTempBasalDurationMinutes: Short?, + basalProgram: BasalProgram?, + podOffset: Int? = null +): Double? { + if (startTime > endTime) return null + + val tempBasalEnd = if (activeTempBasalStartTime != null && activeTempBasalDurationMinutes != null) + activeTempBasalStartTime + activeTempBasalDurationMinutes * 60_000L + else null + + val boundaries = mutableSetOf(startTime, endTime) + if (activeTempBasalStartTime != null && tempBasalEnd != null) { + if (activeTempBasalStartTime in startTime until endTime) boundaries.add(activeTempBasalStartTime) + if (tempBasalEnd in startTime until endTime) boundaries.add(tempBasalEnd) + } + basalProgram?.segments?.forEach { segment -> + val offset = podOffset ?: TimeZone.getDefault().getOffset(startTime) + val dayStartLocal = ((startTime + offset) / 86400_000L) * 86400_000L - offset + var segmentStart = dayStartLocal + segment.startSlotIndex.toLong() * 30 * 60_000L + if (segmentStart <= startTime) segmentStart += 86400_000L + while (segmentStart < endTime) { + boundaries.add(segmentStart) + segmentStart += 86400_000L + } + } + + return boundaries.sorted().windowed(2).map { (boundaryStart, boundaryEnd) -> + val segmentHours = (boundaryEnd - boundaryStart) / 3600_000.0 + val segmentMid = (boundaryStart + boundaryEnd) / 2 + val rate = if (activeTempBasalStartTime != null && activeTempBasalRate != null && tempBasalEnd != null && + segmentMid in activeTempBasalStartTime until tempBasalEnd + ) { + activeTempBasalRate + } else { + basalProgram?.rateAt(segmentMid, podOffset) ?: return null + } + rate * segmentHours + }.sum() +} + +/** Integrates [integrateO5ExpectedDelivery] into [O5PodStateManager.basalExpected] since + * its last update, or seeds it from [basalDelivered] the first time this is called after + * activation completes - call from every `updateFromDefaultStatusResponse`, matching + * [OmnipodDashPodStateManagerImpl.updatePodState]'s equivalent step. [previousUpdate] must + * be the OLD [O5PodStateManager.lastStatusResponseReceived], captured before it's + * overwritten with the new response's timestamp. */ +fun O5PodStateManager.nextBasalExpected(previousUpdate: Long?, now: Long): Double? = + basalExpected?.let { current -> + previousUpdate?.let { start -> + integrateO5ExpectedDelivery( + start, now, activeTempBasalStartTime, activeTempBasalRate, activeTempBasalDurationMinutes, basalProgram, timeZoneOffset + )?.let { delta -> current + delta } + } ?: current + } ?: basalDelivered.takeIf { activationProgress == ActivationProgress.COMPLETED } + +/** Save acceptance with the status itself, before a later stop can replace its sequence. */ +internal fun O5PodStateManager.PendingDoseCommand.withPodAcceptance( + podSequence: Short, + status: DeliveryStatus +): O5PodStateManager.PendingDoseCommand { + val sequenceMatches = bolusCancelRequested != true && + sequenceNumber?.let { (it.toInt() and 0x0f) == (podSequence.toInt() and 0x0f) } == true + val bolusActive = type == O5PodStateManager.PendingDoseType.BOLUS && status.bolusDeliveringActive() + return if (!confirmedByStatus && (sequenceMatches || bolusActive)) copy(confirmedByStatus = true) else this +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/PersistedO5PodStateManager.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/PersistedO5PodStateManager.kt new file mode 100644 index 000000000000..9a0e25e70f8f --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/PersistedO5PodStateManager.kt @@ -0,0 +1,598 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.bledriver.comm.pair.PairResult +import app.aaps.pump.omnipod.common.bledriver.comm.session.EapSqn +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.SoftwareVersion +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse +import app.aaps.pump.omnipod.common.util.PodTimeZone +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5IdRotation +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +import com.google.gson.Gson +import java.io.Serializable +import java.util.Calendar +import java.util.EnumSet +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 + +/** + * [O5PodStateManager] persisted across app restarts, mirroring + * `OmnipodDashPodStateManagerImpl`'s Gson + [Preferences] store/load pattern exactly - + * just for O5's smaller state surface (see [O5PodStateManager]'s class doc for why). + */ +@ContributesBinding(AppScope::class, binding = binding()) +@SingleIn(AppScope::class) +class PersistedO5PodStateManager @Inject constructor( + private val logger: AAPSLogger, + private val preferences: Preferences +) : O5PodStateManager { + + private val gson = Gson() + + private var _podState: PodState? = null + + /** Internal (rather than private) to allow unit testing within this module. + * Lazily deserialized on first access, matching Dash's rationale: keep Gson + * reflection off the main thread during app startup (Dagger constructs this + * @Singleton eagerly). */ + internal var podState: PodState + get() = _podState ?: synchronized(this) { _podState ?: load().also { _podState = it } } + set(value) { + synchronized(this) { _podState = value } + } + + override var bluetoothConnectionState: O5PodStateManager.BluetoothConnectionState + get() = podState.bluetoothConnectionState + set(value) { + podState.bluetoothConnectionState = value + store() + } + + override var connectionAttempts: Int + get() = podState.connectionAttempts + set(value) { + podState.connectionAttempts = value + store() + } + + override var successfulConnections: Int + get() = podState.successfulConnections + set(value) { + podState.successfulConnections = value + store() + } + + override var bluetoothAddress: String? + get() = podState.bluetoothAddress + set(value) { + podState.bluetoothAddress = value + store() + } + + override var controllerId: Long? + get() = podState.controllerId + set(value) { + podState.controllerId = value + store() + } + + override var podId: Long? + get() = podState.podId + set(value) { + podState.podId = value + store() + } + + override var nextPodId: Long? + get() = podState.nextPodId + set(value) { + podState.nextPodId = value + store() + } + + override var ltk: ByteArray? + get() = podState.ltk + set(value) { + podState.ltk = value + store() + } + + override var msgSequenceNumber: Byte + get() = podState.msgSequenceNumber + set(value) { + podState.msgSequenceNumber = value + store() + } + + override var eapAkaSequenceNumber: Long + get() = podState.eapAkaSequenceNumber + set(value) { + podState.eapAkaSequenceNumber = value + store() + } + + private var pendingEapAkaSequenceNumber: Long = 0 + + override fun increaseMessageSequenceNumber() { + podState.msgSequenceNumber = ((podState.msgSequenceNumber.toInt() + 1) and 0x0f).toByte() + store() + } + + override var activationProgress: ActivationProgress + get() = podState.activationProgress + set(value) { + podState.activationProgress = value + store() + } + + override var primePulseRate: Short? + get() = podState.primePulseRate + set(value) { + podState.primePulseRate = value + store() + } + + override var firstPrimeBolusVolume: Short? + get() = podState.firstPrimeBolusVolume + set(value) { + podState.firstPrimeBolusVolume = value + store() + } + + override var secondPrimeBolusVolume: Short? + get() = podState.secondPrimeBolusVolume + set(value) { + podState.secondPrimeBolusVolume = value + store() + } + + override var podLifeInHours: Short? + get() = podState.podLifeInHours + set(value) { + podState.podLifeInHours = value + store() + } + + override var basalProgram: BasalProgram? + get() = podState.basalProgram + set(value) { + podState.basalProgram = value + store() + } + + override val timeZoneId: String? get() = podState.timeZone + override val timeZoneOffset: Int? get() = podState.timeZoneOffset + override val timeZoneUpdated: Long? get() = podState.timeZoneUpdated + + override fun updateTimeZone() = confirmTimeZone(PodTimeZone.now()) + + override fun confirmTimeZone(timeZone: PodTimeZone) { + podState.timeZoneOffset = timeZone.offset + podState.timeZone = timeZone.id + podState.timeZoneUpdated = timeZone.updatedAt + store() + } + + override var timeChangeInProgress: Boolean + get() = podState.timeChangeInProgress + set(value) { + podState.timeChangeInProgress = value + store() + } + + override var deliverySuspended: Boolean + get() = podState.deliverySuspended + set(value) { + podState.deliverySuspended = value + store() + } + + override var lastBolusStartTime: Long? + get() = podState.lastBolusStartTime + set(value) { + podState.lastBolusStartTime = value + store() + } + + override var lastBolusRequestedUnits: Double? + get() = podState.lastBolusRequestedUnits + set(value) { + podState.lastBolusRequestedUnits = value + store() + } + + override var lastBolusDeliveredUnits: Double? + get() = podState.lastBolusDeliveredUnits + set(value) { + podState.lastBolusDeliveredUnits = value + store() + } + + override var activeTempBasalStartTime: Long? + get() = podState.activeTempBasalStartTime + set(value) { + podState.activeTempBasalStartTime = value + store() + } + + override var activeTempBasalRate: Double? + get() = podState.activeTempBasalRate + set(value) { + podState.activeTempBasalRate = value + store() + } + + override var activeTempBasalDurationMinutes: Short? + get() = podState.activeTempBasalDurationMinutes + set(value) { + podState.activeTempBasalDurationMinutes = value + store() + } + + override var pendingDoseCommand: O5PodStateManager.PendingDoseCommand? + get() = podState.pendingDoseCommand + set(value) { + podState.pendingDoseCommand = value + store() + } + + override val podStatus: PodStatus? get() = podState.podStatus + override val deliveryStatus: DeliveryStatus? get() = podState.deliveryStatus + override val firmwareVersion: SoftwareVersion? get() = podState.firmwareVersion + override val bleVersion: SoftwareVersion? get() = podState.bleVersion + override val lotNumber: Long? get() = podState.lotNumber + override val podSequenceNumber: Long? get() = podState.podSequenceNumber + override val totalPulsesDelivered: Short? get() = podState.totalPulsesDelivered + override val bolusPulsesRemaining: Short? get() = podState.bolusPulsesRemaining + override val reservoirPulsesRemaining: Short? get() = podState.reservoirPulsesRemaining?.takeIf { it < 1023 } + override val activeAlerts: EnumSet? get() = podState.activeAlerts + override val minutesSinceActivation: Short? get() = podState.minutesSinceActivation + override val sequenceNumberOfLastProgrammingCommand: Short? get() = podState.sequenceNumberOfLastProgrammingCommand + override val lastStatusResponseReceived: Long? get() = podState.lastStatusResponseReceived + + override val alarmType: AlarmType? get() = podState.alarmType + override val pdmRef: String? get() = podState.pdmRef + override val alarmTime: Short? get() = podState.alarmTime + override val occlusionAlarm: Boolean? get() = podState.occlusionAlarm + override val podStatusWhenAlarmOccurred: PodStatus? get() = podState.podStatusWhenAlarmOccurred + override val rssi: Short? get() = podState.rssi + + private inline fun logBasalTracking(block: () -> Unit) { + val driftBefore = basalDrift.takeIf { isActivationCompleted } ?: 0.0 + block() + if (isActivationCompleted) { + logger.info( + LTag.PUMP, + "PUMP_BASAL act=%.2fU (tot=%.2fU bol=%.2fU) exp=%.4fU err=%+.4fU dErr=%+.4fU".format( + basalDelivered, + (podState.totalPulsesDelivered ?: 0) * PodConstants.POD_PULSE_BOLUS_UNITS, + (podState.cumulativeBolusPulsesDelivered ?: 0) * PodConstants.POD_PULSE_BOLUS_UNITS, + podState.basalExpected ?: 0.0, + basalDrift, + basalDrift - driftBefore + ) + ) + } + } + + override var alarmSynced: Boolean + get() = podState.alarmSynced + set(value) { + podState.alarmSynced = value + store() + } + + override val podActivatedAt: Long? get() = podState.podActivatedAt + override val triggeredAlertTimes: Map? get() = podState.triggeredAlertTimes + + override var suspendAlertsEnabled: Boolean + get() = podState.suspendAlertsEnabled + set(value) { + podState.suspendAlertsEnabled = value + store() + } + + override var syncedAlertSettings: O5PodStateManager.SyncedAlertSettings? + get() = podState.syncedAlertSettings + set(value) { + podState.syncedAlertSettings = value + store() + } + + override var basalExpected: Double? + get() = podState.basalExpected + set(value) { + podState.basalExpected = value + store() + } + + override var lastBasalCorrectionTime: Long? + get() = podState.lastBasalCorrectionTime + set(value) { + podState.lastBasalCorrectionTime = value + store() + } + + override var basalCorrectionInProgress: Boolean + get() = podState.basalCorrectionInProgress + set(value) { + podState.basalCorrectionInProgress = value + store() + } + + override var cumulativeBolusPulsesDelivered: Short? + get() = podState.cumulativeBolusPulsesDelivered + set(value) { + podState.cumulativeBolusPulsesDelivered = value + store() + } + + override fun increaseEapAkaSequenceNumber(): ByteArray { + pendingEapAkaSequenceNumber = eapAkaSequenceNumber + 1 + return EapSqn(pendingEapAkaSequenceNumber).value + } + + override fun commitEapAkaSequenceNumber() { + eapAkaSequenceNumber = pendingEapAkaSequenceNumber + store() + } + + override fun updateFromPairing(controllerId: Long, podId: Long, pairResult: PairResult) { + podState.controllerId = controllerId + podState.podId = podId + podState.ltk = pairResult.ltk + podState.msgSequenceNumber = pairResult.msgSeq + store() + } + + override fun updateFromVersionResponse(response: VersionResponse) { + podState.podStatus = response.podStatus + podState.firmwareVersion = SoftwareVersion( + response.firmwareVersionMajor, response.firmwareVersionMinor, response.firmwareVersionInterim + ) + podState.bleVersion = SoftwareVersion( + response.bleVersionMajor, response.bleVersionMinor, response.bleVersionInterim + ) + podState.lotNumber = response.lotNumber + podState.podSequenceNumber = response.podSequenceNumber + podState.lastStatusResponseReceived = System.currentTimeMillis() + store() + } + + @Synchronized + override fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) { + val previousUpdate = podState.lastStatusResponseReceived + val now = System.currentTimeMillis() + logger.debug(LTag.PUMPCOMM, "Default status response :$response") + logBasalTracking { + updatePodState( + response.totalPulsesDelivered, + response.podStatus, + response.deliveryStatus, + response.bolusPulsesRemaining, + response.reservoirPulsesRemaining, + response.activeAlerts, + response.minutesSinceActivation, + response.sequenceNumberOfLastProgrammingCommand, + now + ) + podState.basalExpected = nextBasalExpected(previousUpdate, now) + } + store() + } + + private fun updatePodState( + totalPulsesDelivered: Short, + podStatus: PodStatus, + deliveryStatus: DeliveryStatus, + bolusPulsesRemaining: Short, + reservoirPulsesRemaining: Short, + activeAlerts: EnumSet, + minutesSinceActivation: Short, + sequenceNumberOfLastProgrammingCommand: Short, + now: Long + ) { + podState.totalPulsesDelivered = totalPulsesDelivered + podState.podStatus = podStatus + podState.deliveryStatus = deliveryStatus + podState.bolusPulsesRemaining = bolusPulsesRemaining + if (reservoirPulsesRemaining < 1023) { + podState.reservoirPulsesRemaining = reservoirPulsesRemaining + } + podState.activeAlerts = activeAlerts + podState.minutesSinceActivation = minutesSinceActivation + podState.sequenceNumberOfLastProgrammingCommand = sequenceNumberOfLastProgrammingCommand + podState.pendingDoseCommand?.let { pending -> + val updated = pending.withPodProgress(sequenceNumberOfLastProgrammingCommand, deliveryStatus, bolusPulsesRemaining) + val delta = updated.accountedBolusPulses - pending.accountedBolusPulses + if (delta > 0) podState.cumulativeBolusPulsesDelivered = ((podState.cumulativeBolusPulsesDelivered ?: 0) + delta).toShort() + podState.pendingDoseCommand = updated + } + podState.lastStatusResponseReceived = now + } + + @Synchronized + override fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) { + logger.info(LTag.PUMPCOMM, "Received AlarmStatusResponse: $response") + logBasalTracking { + updatePodState( + response.totalPulsesDelivered, + response.podStatus, + response.deliveryStatus, + response.bolusPulsesRemaining, + response.reservoirPulsesRemaining, + response.activeAlerts, + response.minutesSinceActivation, + response.sequenceNumberOfLastProgrammingCommand, + System.currentTimeMillis() + ) + } + podState.alarmType = response.alarmType + podState.alarmTime = response.alarmTime + // Keep the first fault snapshot, including across app restarts. + if (podState.pdmRef == null) podState.pdmRef = response.pdmRef + podState.occlusionAlarm = response.occlusionAlarm + podState.podStatusWhenAlarmOccurred = response.podStatusWhenAlarmOccurred + podState.rssi = response.rssi + store() + } + + override fun updateFromActivationTimeResponse(response: PodInfoActivationTimeResponse) { + val calendar = Calendar.getInstance() + calendar.set(2000 + response.year, response.month - 1, response.day, response.hour, response.minute, 0) + calendar.set(Calendar.MILLISECOND, 0) + podState.podActivatedAt = calendar.timeInMillis + podState.alarmType = response.faultEventCode + podState.alarmTime = response.faultTime + store() + } + + override fun updateFromTriggeredAlertsResponse(response: PodInfoTriggeredAlertsResponse) { + podState.triggeredAlertTimes = response.alertActivations.filterValues { it != 0.toShort() } + store() + } + + override fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) { + podState.primePulseRate = response.primePumpRate + podState.firstPrimeBolusVolume = response.numberOfEngagingClutchDrivePulses + podState.secondPrimeBolusVolume = response.numberOfPrimePulses + podState.podLifeInHours = response.podExpirationTimeInHours + podState.firmwareVersion = SoftwareVersion( + response.firmwareVersionMajor, response.firmwareVersionMinor, response.firmwareVersionInterim + ) + podState.bleVersion = SoftwareVersion( + response.bleVersionMajor, response.bleVersionMinor, response.bleVersionInterim + ) + podState.podStatus = response.podStatus + podState.lotNumber = response.lotNumber + podState.podSequenceNumber = response.podSequenceNumber + podState.lastStatusResponseReceived = System.currentTimeMillis() + store() + } + + @Synchronized + override fun completeBolus(startedAt: Long, requestedUnits: Double, deliveredUnits: Double, deliveredPulses: Short?) { + val alreadyCompleted = podState.lastBolusStartTime == startedAt && podState.lastBolusDeliveredUnits != null + val pending = podState.pendingDoseCommand?.takeIf { it.startedAt == startedAt } + if (!alreadyCompleted && deliveredPulses != null && pending?.isBasalCorrection != true) { + val remainder = (deliveredPulses.toInt() - (pending?.accountedBolusPulses ?: 0)).coerceAtLeast(0) + podState.cumulativeBolusPulsesDelivered = + ((podState.cumulativeBolusPulsesDelivered ?: 0) + remainder).toShort() + } + podState.lastBolusStartTime = startedAt + podState.lastBolusRequestedUnits = requestedUnits + podState.lastBolusDeliveredUnits = deliveredUnits + if (pending != null) { + podState.pendingDoseCommand = null + } + store() + } + + override fun reset() { + val retainedControllerId = podState.controllerId + val retainedNextPodId = podState.podId?.let(O5IdRotation::nextPodId) ?: podState.nextPodId + podState = PodState(controllerId = retainedControllerId, nextPodId = retainedNextPodId) + store() + } + + private fun store() { + try { + val cleanPodState = podState.copy(ltk = null) + logger.debug(LTag.PUMPCOMM, "Storing O5 Pod state: ${gson.toJson(cleanPodState)}") + + val serialized = gson.toJson(podState) + preferences.put(O5StringNonPreferenceKey.PodState, serialized) + } catch (ex: Exception) { + logger.error(LTag.PUMPCOMM, "Failed to store O5 Pod state", ex) + } + } + + private fun load(): PodState { + if (preferences.getIfExists(O5StringNonPreferenceKey.PodState) != null) { + try { + return gson.fromJson(preferences.get(O5StringNonPreferenceKey.PodState), PodState::class.java) + } catch (ex: Exception) { + logger.error(LTag.PUMPCOMM, "Failed to deserialize O5 Pod state", ex) + } + } + return PodState() + } + + /** Internal (rather than private) to allow unit testing within this module. */ + internal data class PodState( + var bluetoothConnectionState: O5PodStateManager.BluetoothConnectionState = + O5PodStateManager.BluetoothConnectionState.DISCONNECTED, + var connectionAttempts: Int = 0, + var successfulConnections: Int = 0, + var bluetoothAddress: String? = null, + var controllerId: Long? = null, + var podId: Long? = null, + var nextPodId: Long? = null, + var ltk: ByteArray? = null, + var msgSequenceNumber: Byte = 1, + var eapAkaSequenceNumber: Long = 0, + var activationProgress: ActivationProgress = ActivationProgress.NOT_STARTED, + var primePulseRate: Short? = null, + var firstPrimeBolusVolume: Short? = null, + var secondPrimeBolusVolume: Short? = null, + var podLifeInHours: Short? = null, + var basalProgram: BasalProgram? = null, + var timeZone: String? = null, // TimeZone ID (e.g. "Europe/Amsterdam") + var timeZoneOffset: Int? = null, + var timeZoneUpdated: Long? = null, + var timeChangeInProgress: Boolean = false, + var deliverySuspended: Boolean = false, + var lastBolusStartTime: Long? = null, + var lastBolusRequestedUnits: Double? = null, + var lastBolusDeliveredUnits: Double? = null, + var activeTempBasalStartTime: Long? = null, + var activeTempBasalRate: Double? = null, + var activeTempBasalDurationMinutes: Short? = null, + var pendingDoseCommand: O5PodStateManager.PendingDoseCommand? = null, + var podStatus: PodStatus? = null, + var deliveryStatus: DeliveryStatus? = null, + var firmwareVersion: SoftwareVersion? = null, + var bleVersion: SoftwareVersion? = null, + var lotNumber: Long? = null, + var podSequenceNumber: Long? = null, + var totalPulsesDelivered: Short? = null, + var bolusPulsesRemaining: Short? = null, + var reservoirPulsesRemaining: Short? = null, + var activeAlerts: EnumSet? = null, + var minutesSinceActivation: Short? = null, + var sequenceNumberOfLastProgrammingCommand: Short? = null, + var lastStatusResponseReceived: Long? = null, + var alarmType: AlarmType? = null, + var pdmRef: String? = null, + var alarmTime: Short? = null, + var occlusionAlarm: Boolean? = null, + var podStatusWhenAlarmOccurred: PodStatus? = null, + var rssi: Short? = null, + var alarmSynced: Boolean = false, + var podActivatedAt: Long? = null, + var triggeredAlertTimes: Map? = null, + var suspendAlertsEnabled: Boolean = true, + var syncedAlertSettings: O5PodStateManager.SyncedAlertSettings? = null, + var basalExpected: Double? = null, + var lastBasalCorrectionTime: Long? = null, + var basalCorrectionInProgress: Boolean = false, + var cumulativeBolusPulsesDelivered: Short? = null + ) : Serializable +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/LotDecode.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/LotDecode.kt new file mode 100644 index 000000000000..74e9b3dbf95c --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/LotDecode.kt @@ -0,0 +1,113 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.util + +import java.util.Calendar +import java.util.Locale + +/** + * Decoded fields of a modern (Dash / Omnipod 5) 32-bit Insulet lot number. + * + * Ported from OmnipodKit's LotDecode.swift (loopandlearn/OmnipodKit). Does NOT work + * for older (Eros and earlier) lot numbers, which use a different, simpler encoding + * already handled elsewhere in the Eros driver. + */ +data class LotDecode( + val lot: Long, + val lotHex: String, + val prefix: String, + val productNum: Int, + val productCode: String, + val locationNum: Int, + val locationCode: String, + val dateMMDD: String, + val dateYY: Int, + val line: Int, + val batch: String, + val readableText: String +) { + + companion object { + + private val PRODUCT_CODE: Map = mapOf( + 0x04 to "D1", + 0x18 to "D2", + 0x36 to "D5", + + 0x07 to "H1", + 0x1B to "H2", + 0x39 to "H5", + + 0x02 to "E1", + 0x16 to "E2", + 0x34 to "E5", + + 0x05 to "P1", + 0x19 to "P2", + 0x37 to "P5", + + 0x03 to "A0", + 0x09 to "R1" + ) + + private val MFG_LOC: Map = mapOf( + 0 to "C", + 1 to "U", + 2 to "K", + 6 to "M" + ) + + private fun mask(bits: Int): Long = (1L shl bits) - 1L + + /** + * Returns the decoded lot information for a modern Insulet 32-bit lot #. + * This function does not work for older (Eros and before) lot #s. + * + * @param lot the 32-bit lot number, passed as a Long so the full unsigned + * range fits without overflow. + */ + fun decode(lot: Long): LotDecode { + val lot32 = lot and 0xFFFFFFFFL + + val prefix = if ((lot32 and 0x80000000L) == 0L) "P" else "E" + + val productNum = ((lot32 shr 25) and mask(6)).toInt() + val productCode = PRODUCT_CODE[productNum] ?: "XX" + + val locationNum = ((lot32 shr 22) and mask(3)).toInt() + val locationCode = MFG_LOC[locationNum] ?: "X" + + val dayNumber = ((lot32 shr 7) and mask(15)).toInt() + val dateYY = dayNumber shr 9 + val dayOfYear = dayNumber - (dateYY shl 9) + + val dateMMDD: String = if (dayOfYear > 0) { + val calendar = Calendar.getInstance() + calendar.clear() + calendar.set(dateYY + 2000, Calendar.JANUARY, 1) + calendar.add(Calendar.DAY_OF_YEAR, dayOfYear - 1) + String.format(Locale.US, "%02d%02d", calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)) + } else { + "0000" + } + + val line = ((lot32 shr 4) and mask(3)).toInt() + val batch = (lot32 and mask(4)).toString(16).uppercase(Locale.US) + + val readableText = "$prefix$productCode$locationCode$dateMMDD$dateYY$line$batch" + + return LotDecode( + lot = lot32, + lotHex = String.format(Locale.US, "0x%08X", lot32), + prefix = prefix, + productNum = productNum, + productCode = productCode, + locationNum = locationNum, + locationCode = locationCode, + dateMMDD = dateMMDD, + dateYY = dateYY, + line = line, + batch = batch, + readableText = readableText + ) + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/O5AlertConfigBuilder.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/O5AlertConfigBuilder.kt new file mode 100644 index 000000000000..1607dc011181 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/O5AlertConfigBuilder.kt @@ -0,0 +1,97 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.util + +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertConfiguration +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertTrigger +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepRepetitionType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.expiry +import app.aaps.pump.omnipod.common.keys.OmnipodBooleanPreferenceKey +import app.aaps.pump.omnipod.common.keys.OmnipodIntPreferenceKey +import app.aaps.core.keys.interfaces.Preferences +import java.time.Duration +import java.time.ZonedDateTime +import java.util.concurrent.TimeUnit + +/** + * Builds the expiration/expiration-imminent/user-set-expiration [AlertConfiguration]s from + * current preferences - based on [app.aaps.pump.omnipod.dash.driver.OmnipodDashManagerImpl + * .createActivationPart2Observables]'s expiration-alert delay math, using O5's own + * [expiry] extension in place of Dash's pod-state-manager property. Shared between + * [app.aaps.pump.omnipod.omnipod5.ui.wizard.compose.O5OmnipodWizardViewModel] (initial + * programming during activation) and [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin] (re-sync + * when preferences change afterward) - hoisted here rather than duplicated. + * + * Note: unlike Dash, the USER_SET_EXPIRATION reminder is always added to the returned list + * (with enabled=false when the reminder is disabled) rather than being omitted. The pod's + * ProgramAlerts command only updates the slots it contains, so omitting it would leave a + * previously programmed reminder beeping on the pod even after the user disables it. + */ +fun buildO5ExpirationAlerts(podStateManager: O5PodStateManager, preferences: Preferences, aapsLogger: AAPSLogger): List { + val userConfiguredExpirationReminderHours = + preferences.get(OmnipodBooleanPreferenceKey.ExpirationReminder).let { enabled -> + if (enabled) preferences.get(OmnipodIntPreferenceKey.ExpirationReminderHours).toLong() else null + } + val userConfiguredExpirationAlarmHours = + preferences.get(OmnipodBooleanPreferenceKey.ExpirationAlarm).let { enabled -> + if (enabled) preferences.get(OmnipodIntPreferenceKey.ExpirationAlarmHours).toLong() else null + } + + val podLifeLeft = Duration.between(ZonedDateTime.now(), requireNotNull(podStateManager.expiry) { "Missing pod expiry" }) + + val expirationAlarmEnabled = userConfiguredExpirationAlarmHours != null && userConfiguredExpirationAlarmHours > 0 + val expirationAlarmDelay = podLifeLeft.minus( + Duration.ofHours(userConfiguredExpirationAlarmHours ?: PodConstants.POD_EXPIRATION_ALERT_HOURS_REMAINING_DEFAULT) + ).plus(Duration.ofHours(8)) + + val expirationImminentDelay = podLifeLeft.minus( + Duration.ofHours(PodConstants.POD_EXPIRATION_IMMINENT_ALERT_HOURS_REMAINING) + ).plus(Duration.ofHours(8)) + + val alerts = mutableListOf( + AlertConfiguration( + AlertType.EXPIRATION, + enabled = expirationAlarmEnabled, + durationInMinutes = (TimeUnit.HOURS.toMinutes(userConfiguredExpirationAlarmHours ?: PodConstants.POD_EXPIRATION_ALERT_HOURS_REMAINING_DEFAULT) - 60).toShort(), + autoOff = false, + AlertTrigger.TimerTrigger(expirationAlarmDelay.toMinutes().toShort()), + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX3 + ), + AlertConfiguration( + AlertType.EXPIRATION_IMMINENT, + enabled = expirationAlarmEnabled, + durationInMinutes = 0, + autoOff = false, + AlertTrigger.TimerTrigger(expirationImminentDelay.toMinutes().toShort()), + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX4 + ) + ) + + val userExpiryReminderEnabled = userConfiguredExpirationReminderHours != null && userConfiguredExpirationReminderHours > 0 + val userExpiryReminderDelay = podLifeLeft.minus( + Duration.ofHours(userConfiguredExpirationReminderHours ?: (PodConstants.MAX_POD_LIFETIME.toHours() + 1)) + ) + // Always include USER_SET_EXPIRATION in the list. + val reminderActive = userExpiryReminderEnabled && !userExpiryReminderDelay.isNegative + if (userExpiryReminderEnabled && userExpiryReminderDelay.isNegative) { + aapsLogger.warn(LTag.PUMPBTCOMM, "buildO5ExpirationAlerts negative expiryAlertDuration=$userExpiryReminderDelay") + } + alerts.add( + AlertConfiguration( + AlertType.USER_SET_EXPIRATION, + enabled = reminderActive, + durationInMinutes = 0, + autoOff = false, + AlertTrigger.TimerTrigger(if (reminderActive) userExpiryReminderDelay.toMinutes().toShort() else 0), + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.EVERY_MINUTE_AND_EVERY_15_MIN + ) + ) + return alerts +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/P256Codec.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/P256Codec.kt new file mode 100644 index 000000000000..656ef08e75e0 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/P256Codec.kt @@ -0,0 +1,93 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.util + +import java.math.BigInteger +import java.security.AlgorithmParameters +import java.security.KeyFactory +import java.security.interfaces.ECPrivateKey +import java.security.interfaces.ECPublicKey +import java.security.spec.ECGenParameterSpec +import java.security.spec.ECParameterSpec +import java.security.spec.ECPoint +import java.security.spec.ECPrivateKeySpec +import java.security.spec.ECPublicKeySpec + +/** + * Shared encode/decode helpers between NIST P-256 raw key representations (as used by + * Apple's CryptoKit, and therefore by Insulet's Omnipod 5 protocol) and the JCE's + * ECPrivateKey/ECPublicKey types. + * + * Used by both [P256KeyGenerator] (ECDH key agreement, for pairing) and O5CertificateStore + * (ECDSA signing/verification, for pod command authentication) since both operate on raw + * keys over the same curve and need the same raw-bytes <-> JCE-key-object conversions. + * + * Raw encodings match CryptoKit's `rawRepresentation` for P-256 keys: + * - Private key: the 32-byte big-endian scalar. + * - Public key: the 64-byte plain X || Y coordinate concatenation, **without** the 0x04 + * uncompressed-point prefix byte. This is deliberately different from the 65-byte ANSI + * X9.63 format (CryptoKit's separate `x963Representation`) - confirmed against both + * Apple's swift-crypto source (rawRepresentation and x963Representation are distinct + * properties there) and OmnipodKit's own O5KeyExchange.swift, which hardcodes + * `PUBLIC_KEY_SIZE = 64` for exactly this value. + */ +object P256Codec { + + const val CURVE_NAME = "secp256r1" + const val SCALAR_LENGTH_BYTES = 32 + + /** Raw public key length: 64 bytes (X || Y), no 0x04 prefix. See class doc. */ + const val RAW_POINT_LENGTH_BYTES = 64 + + fun ecParameterSpec(): ECParameterSpec { + val algorithmParameters = AlgorithmParameters.getInstance("EC") + algorithmParameters.init(ECGenParameterSpec(CURVE_NAME)) + return algorithmParameters.getParameterSpec(ECParameterSpec::class.java) + } + + fun decodePrivateKey(rawScalar: ByteArray): ECPrivateKey { + require(rawScalar.size == SCALAR_LENGTH_BYTES) { + "P-256 private key scalar must be $SCALAR_LENGTH_BYTES bytes, got ${rawScalar.size}" + } + val params = ecParameterSpec() + val s = BigInteger(1, rawScalar) + val keyFactory = KeyFactory.getInstance("EC") + return keyFactory.generatePrivate(ECPrivateKeySpec(s, params)) as ECPrivateKey + } + + /** Decodes a raw 64-byte (X || Y, no prefix) public key. */ + fun decodePublicKey(rawPoint: ByteArray): ECPublicKey { + require(rawPoint.size == RAW_POINT_LENGTH_BYTES) { + "P-256 public key must be $RAW_POINT_LENGTH_BYTES raw bytes (X || Y, no prefix), got ${rawPoint.size}" + } + val x = BigInteger(1, rawPoint.copyOfRange(0, SCALAR_LENGTH_BYTES)) + val y = BigInteger(1, rawPoint.copyOfRange(SCALAR_LENGTH_BYTES, RAW_POINT_LENGTH_BYTES)) + val params = ecParameterSpec() + val keyFactory = KeyFactory.getInstance("EC") + return keyFactory.generatePublic(ECPublicKeySpec(ECPoint(x, y), params)) as ECPublicKey + } + + /** Encodes a point as raw 64 bytes (X || Y, no 0x04 prefix). */ + fun encodePoint(point: ECPoint): ByteArray { + val x = point.affineX.toFixedLengthBytes(SCALAR_LENGTH_BYTES) + val y = point.affineY.toFixedLengthBytes(SCALAR_LENGTH_BYTES) + return x + y + } + + fun encodePublicKey(publicKey: ECPublicKey): ByteArray = encodePoint(publicKey.w) + + /** + * Normalizes a BigInteger's magnitude to exactly [length] bytes, big-endian. + * [BigInteger.toByteArray] may prepend a 0x00 sign byte, or be shorter than + * expected for small values; this pads/strips as needed. + */ + fun BigInteger.toFixedLengthBytes(length: Int): ByteArray { + val raw = this.toByteArray() + return when { + raw.size == length -> raw + raw.size == length + 1 && raw[0] == 0.toByte() -> raw.copyOfRange(1, raw.size) + raw.size < length -> ByteArray(length - raw.size) + raw + else -> throw IllegalStateException( + "Value does not fit in $length bytes (got ${raw.size})" + ) + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/P256KeyGenerator.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/P256KeyGenerator.kt new file mode 100644 index 000000000000..c3c52f81ba7b --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/P256KeyGenerator.kt @@ -0,0 +1,104 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.util + +import java.math.BigInteger +import java.security.KeyPairGenerator +import java.security.interfaces.ECPrivateKey +import java.security.spec.ECFieldFp +import java.security.spec.ECGenParameterSpec +import java.security.spec.ECParameterSpec +import java.security.spec.ECPoint +import javax.crypto.KeyAgreement +import dev.zacsweers.metro.Inject + +/** + * NIST P-256 (secp256r1) key generation and ECDH key agreement for Omnipod 5 pairing. + * + * Ported from OmnipodKit's P256KeyGenerator.swift (loopandlearn/OmnipodKit), which wraps + * Apple's CryptoKit P256.KeyAgreement. There is no equivalent to CryptoKit available on + * Android, so this uses the standard java.security / javax.crypto EC APIs directly, via + * the shared raw-key encode/decode helpers in [P256Codec] (see that file's doc comment + * for why public keys here are 64 raw bytes, not 65). + * + * The shared secret returned by [computeSharedSecret] is the raw ECDH result (the X + * coordinate of the agreed point), matching CryptoKit's `sharedSecretFromKeyAgreement`, + * which also returns the raw (un-hashed) agreed secret. Any KDF/hashing on top of this + * shared secret is the caller's responsibility, same as with the Swift original. + */ +class P256KeyGenerator @Inject constructor() { + + fun generatePrivateKey(): ByteArray { + val keyPairGenerator = KeyPairGenerator.getInstance("EC") + keyPairGenerator.initialize(ECGenParameterSpec(P256Codec.CURVE_NAME)) + val keyPair = keyPairGenerator.generateKeyPair() + val privateKey = keyPair.private as ECPrivateKey + with(P256Codec) { return privateKey.s.toFixedLengthBytes(P256Codec.SCALAR_LENGTH_BYTES) } + } + + /** Returns the raw 64-byte (X || Y, no 0x04 prefix) public key. */ + fun publicFromPrivate(privateKey: ByteArray): ByteArray { + require(privateKey.size == P256Codec.SCALAR_LENGTH_BYTES) { + "P-256 private key scalar must be ${P256Codec.SCALAR_LENGTH_BYTES} bytes, got ${privateKey.size}" + } + val params = P256Codec.ecParameterSpec() + val s = BigInteger(1, privateKey) + val publicPoint = multiplyPoint(params.generator, s, params) + return P256Codec.encodePoint(publicPoint) + } + + fun computeSharedSecret(privateKey: ByteArray, publicKey: ByteArray): ByteArray { + val ecPrivateKey = P256Codec.decodePrivateKey(privateKey) + val ecPublicKey = P256Codec.decodePublicKey(publicKey) + + val keyAgreement = KeyAgreement.getInstance("ECDH") + keyAgreement.init(ecPrivateKey) + keyAgreement.doPhase(ecPublicKey, true) + return keyAgreement.generateSecret() + } + + + private val POINT_AT_INFINITY = ECPoint(BigInteger.valueOf(-1), BigInteger.valueOf(-1)) + + private fun isInfinity(point: ECPoint) = point == POINT_AT_INFINITY + + private fun multiplyPoint(point: ECPoint, scalar: BigInteger, params: ECParameterSpec): ECPoint { + val p = (params.curve.field as ECFieldFp).p + val a = params.curve.a + + var result = POINT_AT_INFINITY + var addend = point + var k = scalar + + while (k.signum() > 0) { + if (k.testBit(0)) { + result = addPoints(result, addend, p, a) + } + addend = addPoints(addend, addend, p, a) + k = k.shiftRight(1) + } + return result + } + + private fun addPoints(p1: ECPoint, p2: ECPoint, p: BigInteger, a: BigInteger): ECPoint { + if (isInfinity(p1)) return p2 + if (isInfinity(p2)) return p1 + + val lambda: BigInteger + if (p1.affineX == p2.affineX) { + if ((p1.affineY.add(p2.affineY)).mod(p) == BigInteger.ZERO) { + return POINT_AT_INFINITY + } + val numerator = p1.affineX.pow(2).multiply(BigInteger.valueOf(3)).add(a).mod(p) + // Not BigInteger.TWO: Android has it only from API 33, and on Android 12 the pairing failed with NoSuchFieldError. + val denominator = p1.affineY.multiply(BigInteger.valueOf(2)).mod(p) + lambda = numerator.multiply(denominator.modInverse(p)).mod(p) + } else { + val numerator = p2.affineY.subtract(p1.affineY).mod(p) + val denominator = p2.affineX.subtract(p1.affineX).mod(p) + lambda = numerator.multiply(denominator.modInverse(p)).mod(p) + } + + val x3 = lambda.pow(2).subtract(p1.affineX).subtract(p2.affineX).mod(p) + val y3 = lambda.multiply(p1.affineX.subtract(x3)).subtract(p1.affineY).mod(p) + return ECPoint(x3, y3) + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/PodAdvertisement.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/PodAdvertisement.kt new file mode 100644 index 000000000000..25e576ad6018 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/PodAdvertisement.kt @@ -0,0 +1,116 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.util + +import android.os.ParcelUuid +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType + +/** + * Parses a BLE advertisement's service UUID list into pod identity fields, branching on + * [PodType] since Dash and Omnipod 5 pods advertise completely different UUID layouts. + * + * Ported from OmnipodKit's PodAdvertisement.swift (loopandlearn/OmnipodKit). This is an + * additive, standalone parser - it does not replace the existing Dash-only parsing in + * [app.aaps.pump.omnipod.common.bledriver.comm.legacy.scan.BleDiscoveredDevice]. Wiring pod-type + * detection into the live scan path is a separate, follow-up change so existing Dash pairing + * is not put at risk by this addition. + * + * Unlike the Swift original (a failable initializer that throws/returns nil on malformed + * input), [parse] simply returns null for anything that doesn't match the expected shape + * for the given [PodType]. + */ +data class PodAdvertisement private constructor( + val podType: PodType, + /** Dash only: the pod's 32-bit id, decoded from service UUIDs 3 & 4. */ + val podId: Long?, + /** Dash only: the pod's lot number, decoded from service UUIDs 5-7. */ + val lotNo: Long?, + /** Dash only: the pod's sequence number, decoded from service UUIDs 7-8. */ + val sequenceNo: Int?, + /** Omnipod 5 only: the PDM id embedded in the single 128-bit service UUID. */ + val pdmId: Long?, + /** + * True if this advertisement represents a pod that has not yet been paired to any PDM + * (i.e. still showing its placeholder id), and is therefore eligible for pairing. + */ + val pairable: Boolean +) { + + companion object { + + private const val DASH_MAIN_SERVICE_UUID = "4024" + private const val DASH_UNKNOWN_THIRD_SERVICE_UUID = "000a" + private const val DASH_UNPAIRED_POD_ID_HIGH = "ffff" + private const val DASH_UNPAIRED_POD_ID_LOW = "fffe" + private const val O5_UNPAIRED_PDM_ID_HEX = "fffffffe" + + /** + * Attempts to parse [serviceUuids] as an advertisement from a pod of the given + * [podType]. Returns null if the advertisement doesn't match the shape expected + * for that pod type (wrong UUID count, wrong fixed UUIDs, unparseable ids, etc). + */ + fun parse(serviceUuids: List?, podType: PodType): PodAdvertisement? { + if (serviceUuids.isNullOrEmpty()) return null + return when (podType) { + PodType.DASH -> parseDash(serviceUuids) + PodType.OMNIPOD_5 -> parseO5(serviceUuids) + PodType.EROS, + PodType.UNKNOWN -> null + } + } + + /** Extracts the 16-bit UUID hex (4 chars) from a standard 36-char UUID string. */ + private fun extractUuid16(uuid: ParcelUuid): String = + uuid.toString().substring(4, 8) + + private fun parseDash(serviceUuids: List): PodAdvertisement? { + if (serviceUuids.size != 9) return null + if (extractUuid16(serviceUuids[0]) != DASH_MAIN_SERVICE_UUID) return null + if (extractUuid16(serviceUuids[2]) != DASH_UNKNOWN_THIRD_SERVICE_UUID) return null + + val podIdHigh = extractUuid16(serviceUuids[3]) + val podIdLow = extractUuid16(serviceUuids[4]) + val podId = (podIdHigh + podIdLow).toLongOrNull(16) ?: return null + + val lotSeqPrefix = extractUuid16(serviceUuids[5]) + + extractUuid16(serviceUuids[6]) + + extractUuid16(serviceUuids[7]) + if (lotSeqPrefix.length < 10) return null + val lotNo = lotSeqPrefix.substring(0, 10).toLongOrNull(16) ?: return null + + val seqHex = extractUuid16(serviceUuids[7]) + extractUuid16(serviceUuids[8]) + if (seqHex.length < 3) return null + val sequenceNo = seqHex.substring(2).toIntOrNull(16) ?: return null + + val pairable = podIdHigh.equals(DASH_UNPAIRED_POD_ID_HIGH, ignoreCase = true) && + podIdLow.equals(DASH_UNPAIRED_POD_ID_LOW, ignoreCase = true) + + return PodAdvertisement( + podType = PodType.DASH, + podId = podId, + lotNo = lotNo, + sequenceNo = sequenceNo, + pdmId = null, + pairable = pairable + ) + } + + private fun parseO5(serviceUuids: List): PodAdvertisement? { + if (serviceUuids.size != 1) return null + + val idString = serviceUuids[0].toString() + if (idString.length != 36) return null + + val pdmIdHex = idString.substring(26, 34) + val pdmId = pdmIdHex.toLongOrNull(16) ?: return null + val pairable = pdmIdHex.equals(O5_UNPAIRED_PDM_ID_HEX, ignoreCase = true) + + return PodAdvertisement( + podType = PodType.OMNIPOD_5, + podId = null, + lotNo = null, + sequenceNo = null, + pdmId = pdmId, + pairable = pairable + ) + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/PodTypeAwarePodScanner.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/PodTypeAwarePodScanner.kt new file mode 100644 index 000000000000..2271fb18873e --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/util/PodTypeAwarePodScanner.kt @@ -0,0 +1,135 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.util +import app.aaps.pump.omnipod.common.bledriver.pod.util.BluetoothServiceUuids + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanFilter +import android.bluetooth.le.ScanResult +import android.bluetooth.le.ScanSettings +import android.os.ParcelUuid +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ScanException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ScanFailFoundTooManyException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.scan.BleDiscoveredDevice +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodType +import java.util.Collections +import java.util.concurrent.ConcurrentHashMap + +/** + * A pairable pod found during a [PodTypeAwarePodScanner] scan, holding both the raw + * Android scan result and the parsed [PodAdvertisement] for whichever pod type matched. + */ +class PodTypeAwareDiscoveredDevice( + val scanResult: ScanResult, + val advertisement: PodAdvertisement +) : BleDiscoveredDevice { + + override val address: String get() = scanResult.device.address + + override fun toString(): String = + "PodTypeAwareDiscoveredDevice{address=$address, podType=${advertisement.podType}, " + + "pairable=${advertisement.pairable}}" +} + +/** + * BLE scanner supporting pod discovery across pod types (currently Dash and Omnipod 5), + * additive alongside the existing Dash-only + * [app.aaps.pump.omnipod.common.bledriver.comm.legacy.scan.PodScanner] rather than + * replacing it - that class's existing single-pod-type contract and callers are + * untouched by this file. + * + * Scanning behavior intentionally differs by pod type, matching how each pod's + * advertisement actually works (see [PodAdvertisement]): + * - **Dash**: the target pod's id is already known (e.g. from a prior scan or user + * input), so [scanForPod] filters for a specific [expectedPodId]. + * - **Omnipod 5**: a fresh pod's real identity isn't known before pairing - its + * advertisement only indicates "not yet paired to anyone" - so [expectedPodId] is + * ignored for O5 and [scanForPod] simply returns the first pairable O5 advertisement + * found. + */ +class PodTypeAwarePodScanner( + private val aapsLogger: AAPSLogger, + private val bluetoothAdapter: BluetoothAdapter +) { + + @Throws(InterruptedException::class, ScanException::class) + fun scanForPod(podType: PodType, expectedPodId: Long? = null): PodTypeAwareDiscoveredDevice { + val scanner = bluetoothAdapter.bluetoothLeScanner + ?: throw ScanException("BluetoothLeScanner not available (Bluetooth may be off or unsupported)") + val filter = ScanFilter.Builder() + .setServiceUuid(ParcelUuid.fromString(BluetoothServiceUuids.unpairedAdvertisementUuid(podType))) + .build() + val scanSettings = ScanSettings.Builder() + .setLegacy(false) + .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build() + + val collector = PodTypeAwareScanCollector(aapsLogger, podType, expectedPodId) + aapsLogger.debug(LTag.PUMPBTCOMM, "Scanning for $podType with filter: $filter settings: $scanSettings") + scanner.startScan(listOf(filter), scanSettings, collector) + Thread.sleep(SCAN_DURATION_MS) + scanner.flushPendingScanResults(collector) + scanner.stopScan(collector) + + val found = collector.collect() + aapsLogger.debug(LTag.PUMPBTCOMM, "Scan for $podType complete: ${found.size} pairable pod(s) found") + return when { + found.isEmpty() -> throw ScanException("No pairable $podType pod found") + found.size > 1 -> throw ScanFailFoundTooManyException(found) + else -> found[0] + } + } + + companion object { + + private const val SCAN_DURATION_MS = 5000L + } +} + +private class PodTypeAwareScanCollector( + private val aapsLogger: AAPSLogger, + private val podType: PodType, + private val expectedPodId: Long? +) : ScanCallback() { + + private val found: ConcurrentHashMap = ConcurrentHashMap() + private var scanFailed = 0 + + override fun onScanResult(callbackType: Int, result: ScanResult) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Scan found: $result") + + val serviceUuids: List? = result.scanRecord?.serviceUuids + val advertisement = PodAdvertisement.parse(serviceUuids, podType) ?: return + + if (!advertisement.pairable) return + + if (podType == PodType.DASH && expectedPodId != null && advertisement.podId != expectedPodId) { + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Ignoring pairable pod with non-matching podId: found=${advertisement.podId}, expected=$expectedPodId" + ) + return + } + + found[result.device.address] = PodTypeAwareDiscoveredDevice(result, advertisement) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "Accepted pairable $podType pod: address=${result.device.address}, podId=${advertisement.podId}" + ) + } + + override fun onScanFailed(errorCode: Int) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Scan failed with errorCode: $errorCode") + scanFailed = errorCode + } + + @Throws(ScanException::class) + fun collect(): List { + if (scanFailed != 0) { + throw ScanException(scanFailed) + } + return Collections.unmodifiableList(found.values.toList()) + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/di/O5HistoryBindings.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/di/O5HistoryBindings.kt new file mode 100644 index 000000000000..798b4ea4ffaa --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/di/O5HistoryBindings.kt @@ -0,0 +1,33 @@ +package app.aaps.pump.omnipod.omnipod5.di + +import android.content.Context +import app.aaps.pump.omnipod.omnipod5.history.HistoryMapper +import app.aaps.pump.omnipod.omnipod5.history.O5History +import app.aaps.pump.omnipod.omnipod5.history.database.HistoryRecordDao +import app.aaps.pump.omnipod.omnipod5.history.database.O5HistoryDatabase +import dev.zacsweers.metro.AppScope +import dev.zacsweers.metro.BindingContainer +import dev.zacsweers.metro.ContributesTo +import dev.zacsweers.metro.Provides +import dev.zacsweers.metro.SingleIn + +@ContributesTo(AppScope::class) +@BindingContainer +object O5HistoryBindings { + + @Provides + @SingleIn(AppScope::class) + fun provideDatabase(context: Context): O5HistoryDatabase = O5HistoryDatabase.build(context) + + @Provides + @SingleIn(AppScope::class) + fun provideDao(database: O5HistoryDatabase): HistoryRecordDao = database.historyRecordDao() + + @Provides + @SingleIn(AppScope::class) + fun provideMapper(): HistoryMapper = HistoryMapper() + + @Provides + @SingleIn(AppScope::class) + fun provideHistory(dao: HistoryRecordDao, mapper: HistoryMapper): O5History = O5History(dao, mapper) +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/HistoryMapper.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/HistoryMapper.kt new file mode 100644 index 000000000000..9e8b4a79d6a1 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/HistoryMapper.kt @@ -0,0 +1,19 @@ +package app.aaps.pump.omnipod.omnipod5.history + +import app.aaps.pump.omnipod.common.history.data.HistoryRecord +import app.aaps.pump.omnipod.omnipod5.history.database.HistoryRecordEntity + +class HistoryMapper { + + fun toDomain(entity: HistoryRecordEntity): HistoryRecord = HistoryRecord( + id = entity.id, + createdAt = entity.createdAt, + date = entity.date, + commandType = entity.commandType, + initialResult = entity.initialResult, + record = entity.bolusRecord ?: entity.tempBasalRecord ?: entity.basalProfileRecord, + totalAmountDelivered = entity.totalAmountDelivered, + resolvedResult = entity.resolvedResult, + resolvedAt = entity.resolvedAt + ) +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/O5History.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/O5History.kt new file mode 100644 index 000000000000..f2f3037cd39e --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/O5History.kt @@ -0,0 +1,122 @@ +package app.aaps.pump.omnipod.omnipod5.history + +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.common.history.data.BasalValuesRecord +import app.aaps.pump.omnipod.common.history.data.BolusRecord +import app.aaps.pump.omnipod.common.history.data.HistoryRecord +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.ResolvedResult +import app.aaps.pump.omnipod.common.history.data.TempBasalRecord +import app.aaps.pump.omnipod.omnipod5.history.database.HistoryRecordDao +import app.aaps.pump.omnipod.omnipod5.history.database.HistoryRecordEntity +import dev.zacsweers.metro.Inject +import io.reactivex.rxjava3.core.Single +import io.reactivex.rxjava3.core.Completable + +@Inject +class O5History( + private val dao: HistoryRecordDao, + private val mapper: HistoryMapper +) { + + fun recordSuccess( + commandType: OmnipodCommandType, + date: Long = System.currentTimeMillis(), + bolusRecord: BolusRecord? = null, + tempBasalRecord: TempBasalRecord? = null, + basalProfileRecord: BasalValuesRecord? = null, + totalAmountDelivered: Double? = null, + initialResult: InitialResult = InitialResult.SENT, + resolvedResult: ResolvedResult? = ResolvedResult.SUCCESS, + resolvedAt: Long? = System.currentTimeMillis() + ) { + createRecord( + commandType = commandType, + date = date, + bolusRecord = bolusRecord, + tempBasalRecord = tempBasalRecord, + basalProfileRecord = basalProfileRecord, + totalAmountDelivered = totalAmountDelivered, + initialResult = initialResult, + resolvedResult = resolvedResult, + resolvedAt = resolvedAt + ).blockingGet() + } + + fun recordFailure(commandType: OmnipodCommandType, date: Long = System.currentTimeMillis()) { + createRecord( + commandType = commandType, + date = date, + initialResult = InitialResult.FAILURE_SENDING, + resolvedResult = ResolvedResult.FAILURE, + resolvedAt = System.currentTimeMillis() + ).blockingGet() + } + + fun createRecord( + commandType: OmnipodCommandType, + date: Long = System.currentTimeMillis(), + initialResult: InitialResult = InitialResult.SENT, + bolusRecord: BolusRecord? = null, + tempBasalRecord: TempBasalRecord? = null, + basalProfileRecord: BasalValuesRecord? = null, + totalAmountDelivered: Double? = null, + resolvedResult: ResolvedResult? = null, + resolvedAt: Long? = null + ): Single = dao.save( + HistoryRecordEntity( + createdAt = System.currentTimeMillis(), + date = date, + commandType = commandType, + initialResult = initialResult, + tempBasalRecord = tempBasalRecord, + bolusRecord = bolusRecord, + basalProfileRecord = basalProfileRecord, + totalAmountDelivered = totalAmountDelivered, + resolvedResult = resolvedResult, + resolvedAt = resolvedAt + ) + ) + + fun getById(id: Long): HistoryRecord = + dao.byIdBlocking(id)?.let(mapper::toDomain) + ?: throw IllegalArgumentException("history entry [$id] not found") + + fun markSuccess(id: Long): Completable = + dao.markResolved(id, ResolvedResult.SUCCESS, System.currentTimeMillis()) + + fun markFailure(id: Long): Completable = + dao.markResolved(id, ResolvedResult.FAILURE, System.currentTimeMillis()) + + fun markSent(id: Long): Completable = + dao.setInitialResult(id, InitialResult.SENT) + + fun markSendingFailure(id: Long): Completable = + dao.setInitialResult(id, InitialResult.FAILURE_SENDING) + + fun setTotalAmountDelivered(id: Long, amount: Double?): Completable = + dao.setTotalAmountDelivered(id, amount) + + fun delete(record: HistoryRecord): Completable = + dao.delete( + HistoryRecordEntity( + id = record.id, + createdAt = record.createdAt, + date = record.date, + commandType = record.commandType, + initialResult = record.initialResult, + tempBasalRecord = record.record as? TempBasalRecord, + bolusRecord = record.record as? BolusRecord, + basalProfileRecord = record.record as? BasalValuesRecord, + totalAmountDelivered = record.totalAmountDelivered, + resolvedResult = record.resolvedResult, + resolvedAt = record.resolvedAt + ) + ) + + fun getRecords(): Single> = + dao.all().map { records -> records.map(mapper::toDomain) } + + fun getRecordsAfter(time: Long): Single> = + dao.allSince(time).map { records -> records.map(mapper::toDomain) } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/Converters.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/Converters.kt new file mode 100644 index 000000000000..a27ac28149f2 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/Converters.kt @@ -0,0 +1,39 @@ +package app.aaps.pump.omnipod.omnipod5.history.database + +import androidx.room.TypeConverter +import app.aaps.core.interfaces.profile.Profile +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BolusType +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.ResolvedResult +import com.google.gson.GsonBuilder + +class Converters { + + @TypeConverter fun toInitialResult(value: String) = enumValueOf(value) + @TypeConverter fun fromInitialResult(value: InitialResult) = value.name + @TypeConverter fun toResolvedResult(value: String?) = value?.let { enumValueOf(it) } + @TypeConverter fun fromResolvedResult(value: ResolvedResult?) = value?.name + @TypeConverter + fun toBolusType(value: String?): BolusType? = when (value) { + "BASAL_DRIFT_COMPENSATION" -> BolusType.BASAL_CORRECTION + else -> value?.let { enumValueOf(it) } + } + + // Keep the stored name used by older Omnipod 5 builds. + @TypeConverter + fun fromBolusType(value: BolusType?): String? = when (value) { + BolusType.BASAL_CORRECTION -> "BASAL_DRIFT_COMPENSATION" + else -> value?.name + } + + @TypeConverter fun toCommandType(value: String) = enumValueOf(value) + @TypeConverter fun fromCommandType(value: OmnipodCommandType) = value.name + + @TypeConverter + fun toSegments(value: String?): List = + value?.let { GsonBuilder().create().fromJson(it, Array::class.java).toList() } ?: emptyList() + + @TypeConverter + fun fromSegments(value: List): String = GsonBuilder().create().toJson(value) +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/HistoryRecordDao.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/HistoryRecordDao.kt new file mode 100644 index 000000000000..c3623d3efff5 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/HistoryRecordDao.kt @@ -0,0 +1,42 @@ +package app.aaps.pump.omnipod.omnipod5.history.database + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import androidx.room.Delete +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.ResolvedResult +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Single + +@Dao +abstract class HistoryRecordDao { + + @Query("SELECT * FROM historyrecords ORDER BY createdAt DESC") + abstract fun all(): Single> + + @Query("SELECT * FROM historyrecords WHERE createdAt >= :since ORDER BY createdAt DESC") + abstract fun allSince(since: Long): Single> + + @Query("SELECT * FROM historyrecords ORDER BY id LIMIT 1") + abstract fun first(): HistoryRecordEntity? + + @Query("SELECT * FROM historyrecords WHERE id = :id LIMIT 1") + abstract fun byIdBlocking(id: Long): HistoryRecordEntity? + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun save(record: HistoryRecordEntity): Single + + @Delete + abstract fun delete(record: HistoryRecordEntity): Completable + + @Query("UPDATE historyrecords SET resolvedResult = :resolvedResult, resolvedAt = :resolvedAt WHERE id = :id") + abstract fun markResolved(id: Long, resolvedResult: ResolvedResult, resolvedAt: Long): Completable + + @Query("UPDATE historyrecords SET initialResult = :initialResult WHERE id = :id") + abstract fun setInitialResult(id: Long, initialResult: InitialResult): Completable + + @Query("UPDATE historyrecords SET totalAmountDelivered = :totalAmountDelivered WHERE id = :id") + abstract fun setTotalAmountDelivered(id: Long, totalAmountDelivered: Double?): Completable +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/HistoryRecordEntity.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/HistoryRecordEntity.kt new file mode 100644 index 000000000000..f82802b5ba48 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/HistoryRecordEntity.kt @@ -0,0 +1,27 @@ +package app.aaps.pump.omnipod.omnipod5.history.database + +import androidx.room.Embedded +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.common.history.data.BasalValuesRecord +import app.aaps.pump.omnipod.common.history.data.BolusRecord +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.ResolvedResult +import app.aaps.pump.omnipod.common.history.data.TempBasalRecord + +@Entity(tableName = "historyrecords", indices = [Index("createdAt")]) +data class HistoryRecordEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val createdAt: Long, + val date: Long, + val commandType: OmnipodCommandType, + val initialResult: InitialResult, + @Embedded(prefix = "tempBasal_") val tempBasalRecord: TempBasalRecord?, + @Embedded(prefix = "bolus_") val bolusRecord: BolusRecord?, + @Embedded(prefix = "basal_") val basalProfileRecord: BasalValuesRecord?, + val totalAmountDelivered: Double?, + val resolvedResult: ResolvedResult?, + val resolvedAt: Long? +) diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/O5HistoryDatabase.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/O5HistoryDatabase.kt new file mode 100644 index 000000000000..9d7ea5581b1b --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/O5HistoryDatabase.kt @@ -0,0 +1,29 @@ +package app.aaps.pump.omnipod.omnipod5.history.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverters +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +@Database(entities = [HistoryRecordEntity::class], version = 2, exportSchema = false) +@TypeConverters(Converters::class) +abstract class O5HistoryDatabase : RoomDatabase() { + + abstract fun historyRecordDao(): HistoryRecordDao + + companion object { + fun build(context: Context): O5HistoryDatabase = Room.databaseBuilder( + context.applicationContext, + O5HistoryDatabase::class.java, + "omnipod_o5_history_database.db" + ).addMigrations(MIGRATION_1_2).build() + private val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(database: SupportSQLiteDatabase) { + database.execSQL("ALTER TABLE historyrecords ADD COLUMN resolvedAt INTEGER") + } + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/keys/O5IntentKey.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/keys/O5IntentKey.kt new file mode 100644 index 000000000000..724ac6a4adc0 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/keys/O5IntentKey.kt @@ -0,0 +1,38 @@ +package app.aaps.pump.omnipod.omnipod5.keys + +import app.aaps.core.interfaces.configuration.Config +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.pump.omnipod.common.R + +enum class O5IntentKey( + override val key: String, + override val title: TextRef, + override val summary: TextRef? = null, + override val preferenceType: PreferenceType = PreferenceType.ACTIVITY, + override val defaultedBySM: Boolean = false, + override val showInApsMode: Boolean = true, + override val showInNsClientMode: Boolean = true, + override val showInPumpControlMode: Boolean = true, + override val dependency: BooleanPreferenceKey? = null, + override val negativeDependency: BooleanPreferenceKey? = null, + override val hideParentScreenIfHidden: Boolean = false, + override val exportable: Boolean = false +) : IntentPreferenceKey { + + CertificateStore( + key = "omnipod_5_certificate_store", + title = TextRef.AndroidRes(R.string.omnipod_5_certificate_store), + summary = TextRef.AndroidRes(R.string.omnipod_5_certificate_store_summary) + ); + + companion object { + fun ConfigEnabledEntries(config: Config): List = if (config.isEngineeringMode()) { + listOf(CertificateStore) + } else { + emptyList() + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/keys/O5StringNonPreferenceKey.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/keys/O5StringNonPreferenceKey.kt new file mode 100644 index 000000000000..b55073ffb6d5 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/keys/O5StringNonPreferenceKey.kt @@ -0,0 +1,19 @@ +package app.aaps.pump.omnipod.omnipod5.keys + +import app.aaps.core.keys.interfaces.StringNonPreferenceKey + +/** + * Preference key(s) for persisting Omnipod 5 pod state, mirroring [DashStringNonPreferenceKey]. + */ +enum class O5StringNonPreferenceKey( + override val key: String, + override val defaultValue: String, + override val exportable: Boolean = true +) : StringNonPreferenceKey { + + PodState("AAPS.Omnipod5.pod_state", ""), + + /** Holds Keystore-encrypted O5 registration (credential) data - never exported, since + * unlike pod connection state, this contains actual key material. */ + RegistrationData("AAPS.Omnipod5.registration_data_encrypted", "", exportable = false), +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/queue/command/CommandPairNewPod.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/queue/command/CommandPairNewPod.kt new file mode 100644 index 000000000000..089be8ef223c --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/queue/command/CommandPairNewPod.kt @@ -0,0 +1,13 @@ +package app.aaps.pump.omnipod.omnipod5.queue.command + +import app.aaps.core.interfaces.queue.CustomCommand + +/** + * Triggers [app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5BleManager.pairNewPod] via + * [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin.executeCustomCommand] - the only pairing + * entry point for O5 right now, since no pairing/setup wizard UI exists yet. + */ +class CommandPairNewPod : CustomCommand { + + override val statusDescription = "PAIR NEW POD" +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CertificateStoreScreen.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CertificateStoreScreen.kt new file mode 100644 index 000000000000..a1f8cccff6ed --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CertificateStoreScreen.kt @@ -0,0 +1,75 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +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.Modifier +import androidx.compose.ui.res.stringResource +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.ui.compose.AapsTopAppBar +import app.aaps.core.ui.compose.metroViewModel +import app.aaps.pump.omnipod.common.R + +@Composable +fun O5CertificateStoreScreen( + rh: ResourceHelper, + onBack: () -> Unit, +) { + val viewModel: O5CredentialImportViewModel = metroViewModel() + var showManualImport by remember { mutableStateOf(false) } + Scaffold( + topBar = { + AapsTopAppBar( + title = { + Text( + stringResource( + if (showManualImport) R.string.omnipod_5_certificate_store_import + else R.string.omnipod_5_certificate_store + ) + ) + }, + navigationIcon = { + IconButton(onClick = { if (showManualImport) showManualImport = false else onBack() }) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(app.aaps.core.ui.R.string.back) + ) + } + }, + actions = { + if (!showManualImport) { + TextButton(onClick = { showManualImport = true }) { + Text( + text = stringResource(app.aaps.core.ui.R.string.import_btn) + ) + } + } + } + ) + } + ) { paddingValues -> + Box( + modifier = Modifier + .fillMaxSize() + .padding(paddingValues) + ) { + if (showManualImport) { + O5CredentialManualImportScreen(viewModel = viewModel, rh = rh) + } else { + O5CredentialListScreen(viewModel = viewModel, rh = rh) + } + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportViewModel.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportViewModel.kt new file mode 100644 index 000000000000..eab4157f96c2 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportViewModel.kt @@ -0,0 +1,218 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.R +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.security.SecureO5RegistrationStorage +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +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.flow.MutableStateFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.flow.stateIn +import org.json.JSONException +import org.json.JSONObject +import java.util.Locale + +internal fun formatControllerId(controllerId: Long): String = String.format(Locale.US, "0x%08X", controllerId) + +/** One row of the currently installed certificates list shown in the import screen. */ +data class InstalledCredentialRow( + val controllerId: Long, + val source: O5RegistrationData.O5RegistrationSource +) + +/** Result of the last certificate store action, so the screen can show a message. */ +sealed class ImportResult { + object None : ImportResult() + object RemoveBlocked : ImportResult() + data class Success(val controllerId: Long) : ImportResult() + data class Failure(val reason: String) : ImportResult() +} + +/** + * Drives a settings screen for importing an Omnipod 5 certificate and viewing/removing + * already-installed certificates. Accepts either format, auto-detected from the pasted + * text: + * - a `.o5keypair`-shaped JSON object (as produced by OmnipodKit's own `toJSON()` on + * iOS - `controllerId`/`privateKey`/`publicKey`/`intermediateCA`/`tlsCertificate`, + * keys hex-encoded and certs base64-encoded) - see [O5RegistrationData.fromJsonMap] + * - the packed `"controllerId|priv|pub|ica|tls"` string format - see + * [O5RegistrationData.installPacked] + * + * Deliberately has no dosing-related functionality whatsoever - this only manages which + * certificates [O5RegistrationData] knows about, nothing about pairing, connection, or + * pod control. + */ +@ContributesIntoMap(AppScope::class, binding = binding()) +@ViewModelKey +class O5CredentialImportViewModel @Inject constructor( + private val secureO5RegistrationStorage: SecureO5RegistrationStorage, + private val podStateManager: O5PodStateManager, + private val preferences: Preferences, + private val rh: ResourceHelper +) : ViewModel() { + + private val _inputText = MutableStateFlow("") + val inputText: StateFlow = _inputText + + private val _importResult = MutableStateFlow(ImportResult.None) + val importResult: StateFlow = _importResult + + private val _installedCredentials = MutableStateFlow>(emptyList()) + val installedCredentials: StateFlow> = _installedCredentials + + // PodState preference updates signal that persisted pod state changed; re-read the + // active-pod state from podStateManager because it owns the parsed state. + val canRemoveCertificate: StateFlow = preferences.observe(O5StringNonPreferenceKey.PodState) + .map { !hasActivePod() } + .onEach { canRemove -> + if (canRemove && _importResult.value == ImportResult.RemoveBlocked) { + _importResult.value = ImportResult.None + } + } + .stateIn(viewModelScope, SharingStarted.Eagerly, !hasActivePod()) + + init { + refreshInstalledCredentials() + } + + fun onInputChanged(text: String) { + _inputText.value = text + if (_importResult.value != ImportResult.None) { + _importResult.value = ImportResult.None + } + } + + /** + * Attempts to parse and install [inputText]'s current value, auto-detecting whether + * it's a `.o5keypair`-shaped JSON object or a packed certificate string (see class doc). + * On success, also persists it (encrypted) so it survives app restarts, and clears the + * input field. On failure, leaves the input as-is so the user can correct it. + */ + fun importCurrentInput() { + val text = _inputText.value.trim() + if (text.isEmpty()) { + _importResult.value = ImportResult.Failure(rh.gs(R.string.omnipod_5_certificate_import_paste_first)) + return + } + + importText(text) + } + + /** + * Imports a certificate JSON/packed string received from the pairing web page (via the + * WebView message bridge). Runs the same parse/install path as a manual paste and + * returns whether a certificate was successfully installed. + */ + fun importFromWebMessage(text: String): Boolean { + val trimmed = text.trim() + if (trimmed.isEmpty()) { + _importResult.value = ImportResult.Failure(rh.gs(R.string.omnipod_5_certificate_import_empty)) + return false + } + importText(trimmed) + return _importResult.value is ImportResult.Success + } + + fun importError(throwable: Throwable) { + _importResult.value = ImportResult.Failure(throwable.message ?: "Import failed unexpectedly") + return + } + + private fun importText(text: String) { + val controllerId = if (text.startsWith("{")) importJsonCredential(text) else importPackedCredential(text) + if (controllerId == null) { + _importResult.value = ImportResult.Failure( + rh.gs(R.string.omnipod_5_certificate_import_parse_error) + ) + return + } + + val installed = O5RegistrationData.get(controllerId) + if (installed == null) { + _importResult.value = ImportResult.Failure("Import failed unexpectedly") + return + } + + secureO5RegistrationStorage.persistEntry(installed, O5RegistrationData.O5RegistrationSource.IMPORTED) + _importResult.value = ImportResult.Success(controllerId) + _inputText.value = "" + refreshInstalledCredentials() + } + + /** + * Parses [text] as the `.o5keypair`-shaped JSON object OmnipodKit's own `toJSON()` + * produces on iOS and installs it if valid. Returns the resulting controllerId, or + * null if the text wasn't valid JSON or was missing a required field. + */ + private fun importJsonCredential(text: String): Long? { + val json = try { + JSONObject(text) + } catch (e: JSONException) { + return null + } + val map = REQUIRED_JSON_KEYS.associateWith { key -> if (json.has(key) && !json.isNull(key)) json.optString(key) else null } + val data = O5RegistrationData.fromJsonMap(map) ?: return null + O5RegistrationData.install(data, O5RegistrationData.O5RegistrationSource.IMPORTED) + return data.controllerId + } + + /** + * Parses [text] as a packed `"controllerId|priv|pub|ica|tls"` string and installs it + * if valid (see [O5RegistrationData.installPacked]). Returns the resulting + * controllerId, or null if parsing/installation failed. + */ + private fun importPackedCredential(text: String): Long? { + val controllerId = parseControllerIdFromPacked(text) + val ok = O5RegistrationData.installPacked(text) + return controllerId.takeIf { ok } + } + + /** Removes a certificate from both the in-memory registry and persisted storage. */ + fun removeCredential(controllerId: Long) { + if (hasActivePod()) { + _importResult.value = ImportResult.RemoveBlocked + return + } + O5RegistrationData.remove(controllerId) + secureO5RegistrationStorage.removeEntry(controllerId) + _importResult.value = ImportResult.None + refreshInstalledCredentials() + } + + private fun hasActivePod(): Boolean = podStateManager.activationProgress == ActivationProgress.COMPLETED + + private fun refreshInstalledCredentials() { + _installedCredentials.value = O5RegistrationData.allValues.mapNotNull { data -> + O5RegistrationData.source(data.controllerId)?.let { source -> + InstalledCredentialRow(data.controllerId, source) + } + } + } + + /** + * Pulls just the controllerId out of a packed string, without fully parsing/validating + * it - used so a failed [O5RegistrationData.installPacked] call can still be attributed + * to a specific controllerId if the string was at least well-formed enough to read one. + * Returns null for anything that doesn't even have a parseable leading controllerId field. + */ + private fun parseControllerIdFromPacked(packed: String): Long? = + packed.substringBefore("|").toLongOrNull() + + private companion object { + /** Matches the keys OmnipodKit's `O5RegistrationData.toJSON()` produces on iOS. */ + val REQUIRED_JSON_KEYS = listOf("controllerId", "privateKey", "publicKey", "intermediateCA", "tlsCertificate") + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportWebViewScreen.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportWebViewScreen.kt new file mode 100644 index 000000000000..4f8a7d0dc030 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportWebViewScreen.kt @@ -0,0 +1,105 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +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.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.pump.omnipod.common.R +import app.aaps.core.ui.R as CoreUiR + +/** + * Full-screen content that hosts the Omnipod 5 certificate import WebView (see + * [O5CredentialWebViewScreen]). The screen loads [url], waits for the page to post the + * certificate JSON back through the message bridge, and imports it via [onImportCredential]. + * + * - On a successful import [onImported] is called, which opens the Omnipod 5 setup wizard. + * - On a failed import a "Try again" button is shown that re-launches the WebView (reloads + * [url] from scratch). + * - A network failure shows a dialog explaining the one-time internet requirement. + * + * The host provides toolbar navigation for leaving this full-screen flow. + */ +@Composable +fun O5CredentialImportWebViewScreen( + url: String, + onImportCredential: (String) -> Boolean, + onImported: () -> Unit, + onFailed: (Throwable) -> Unit, +) { + var attempt by remember { mutableIntStateOf(0) } + var failed by remember { mutableStateOf(false) } + var networkUnavailable by remember { mutableStateOf(false) } + val retry: () -> Unit = { + networkUnavailable = false + failed = false + attempt++ + } + + Column( + modifier = Modifier.fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large) + ) { + if (failed) { + Column( + modifier = Modifier.padding(horizontal = AapsSpacing.extraLarge), + verticalArrangement = Arrangement.spacedBy(AapsSpacing.large) + ) { + Text( + text = stringResource( + if (networkUnavailable) R.string.omnipod_5_certificate_internet_required_message + else R.string.omnipod_5_certificate_import_failed + ), + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.bodyMedium + ) + Button( + onClick = retry, + modifier = Modifier.fillMaxWidth() + ) { + Text(stringResource(R.string.omnipod_5_certificate_import_try_again)) + } + } + } else { + // key(attempt) recreates the WebView so "Try again" reloads the page. + key(attempt) { + O5CredentialWebViewScreen( + url = url, + onCredentialReceived = { json -> + if (onImportCredential(json)) { + onImported() + } else { + failed = true + } + }, + onCredentialError = { throwable -> + failed = true + if (throwable is O5CertificateNetworkException) { + networkUnavailable = true + } else { + onFailed(throwable) + } + }, + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) + } + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialListScreen.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialListScreen.kt new file mode 100644 index 000000000000..9919bf910885 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialListScreen.kt @@ -0,0 +1,176 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +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.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Card +import androidx.compose.material3.MaterialTheme +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.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.core.ui.compose.stringResource +import app.aaps.pump.omnipod.common.R +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData + +/** + * Settings screen for viewing/removing Omnipod 5 certificates. + */ +@Composable +fun O5CredentialListScreen( + viewModel: O5CredentialImportViewModel, + rh: ResourceHelper +) { + val importResult by viewModel.importResult.collectAsState() + val installedCredentials by viewModel.installedCredentials.collectAsState() + val canRemoveCertificate by viewModel.canRemoveCertificate.collectAsState() + + O5CredentialImportContent( + removeCredential = viewModel::removeCredential, + canRemoveCertificate = canRemoveCertificate, + importResult = importResult, + installedCredentials = installedCredentials, + ) +} + +@Composable +private fun O5CredentialImportContent( + removeCredential: (Long) -> Unit, + canRemoveCertificate: Boolean, + importResult: ImportResult, + installedCredentials: List, +) { + val removeBlockedMessage = stringResource(TextRef.AndroidRes(R.string.omnipod_5_certificate_store_remove_blocked)) + val showRemoveBlockedMessage = !canRemoveCertificate || importResult == ImportResult.RemoveBlocked + + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + when (importResult) { + is ImportResult.Success -> Text( + text = stringResource(TextRef.AndroidRes(R.string.omnipod_5_certificate_store_imported), formatControllerId(importResult.controllerId)), + color = MaterialTheme.colorScheme.primary, + style = MaterialTheme.typography.labelLarge + ) + + is ImportResult.Failure -> Text( + text = importResult.reason, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.labelLarge + ) + + ImportResult.None, ImportResult.RemoveBlocked -> Unit + } + + if (installedCredentials.isNotEmpty()) { + if (showRemoveBlockedMessage) { + Text( + text = removeBlockedMessage, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.labelLarge + ) + } + Text( + text = stringResource(TextRef.AndroidRes(R.string.omnipod_5_certificate_store_installed_certificates)), + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold + ) + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + installedCredentials.forEach { row -> + Card(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column { + Text( + text = stringResource(TextRef.AndroidRes(R.string.omnipod_5_certificate_store_controller_id), formatControllerId(row.controllerId)), + style = MaterialTheme.typography.bodyMedium + ) + Text( + text = row.source.name.lowercase().replaceFirstChar { it.uppercase() }, + style = MaterialTheme.typography.labelSmall + ) + } + TextButton( + onClick = { removeCredential(row.controllerId) }, + enabled = canRemoveCertificate + ) { + Text(stringResource(TextRef.AndroidRes(app.aaps.core.ui.R.string.remove))) + } + } + } + } + } + } + } +} + +@Preview(showBackground = true) +@Composable +private fun PreviewCredentialImportContent() { + MaterialTheme { + O5CredentialImportContent( + removeCredential = {}, + canRemoveCertificate = true, + importResult = ImportResult.None, + installedCredentials = emptyList(), + ) + } +} + +@Preview(showBackground = true) +@Composable +private fun PreviewCredentialImportedCredentialsContent() { + MaterialTheme { + O5CredentialImportContent( + removeCredential = {}, + canRemoveCertificate = true, + importResult = ImportResult.None, + installedCredentials = listOf(InstalledCredentialRow(123, O5RegistrationData.O5RegistrationSource.IMPORTED)), + ) + } +} + +@Preview(showBackground = true) +@Composable +private fun PreviewCredentialImportFailureContent() { + MaterialTheme { + O5CredentialImportContent( + removeCredential = {}, + canRemoveCertificate = true, + importResult = ImportResult.Failure("Failed to import cert"), + installedCredentials = emptyList(), + ) + } +} + +@Preview(showBackground = true) +@Composable +private fun PreviewCredentialImportSuccesssContent() { + MaterialTheme { + O5CredentialImportContent( + removeCredential = {}, + canRemoveCertificate = true, + importResult = ImportResult.Success(123), + installedCredentials = listOf(InstalledCredentialRow(123, O5RegistrationData.O5RegistrationSource.IMPORTED)), + ) + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialManualImportScreen.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialManualImportScreen.kt new file mode 100644 index 000000000000..6fddde81ad16 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialManualImportScreen.kt @@ -0,0 +1,106 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.pump.omnipod.common.R + +/** + * Manual certificate import screen: lets the user paste a certificate string and install it. + * Reached from the "import" action in the top app bar of + * [O5CredentialListScreen]/[O5CertificateStoreScreen]. Purely certificate management - no + * dosing/pairing actions. + */ +@Composable +fun O5CredentialManualImportScreen( + viewModel: O5CredentialImportViewModel, + rh: ResourceHelper +) { + val inputText by viewModel.inputText.collectAsState() + val importResult by viewModel.importResult.collectAsState() + + O5CredentialManualImportContent( + inputText = inputText, + inputChanged = viewModel::onInputChanged, + importInput = viewModel::importCurrentInput, + importResult = importResult, + rh = rh + ) +} + +@Composable +private fun O5CredentialManualImportContent( + inputText: String, + inputChanged: (String) -> Unit, + importInput: () -> Unit, + importResult: ImportResult, + rh: ResourceHelper, +) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Text( + text = rh.gs(R.string.omnipod_5_certificate_manual_import_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + text = rh.gs(R.string.omnipod_5_certificate_manual_import_description), + style = MaterialTheme.typography.bodySmall + ) + + OutlinedTextField( + value = inputText, + onValueChange = inputChanged, + label = { Text(rh.gs(R.string.omnipod_5_certificate_manual_import_label)) }, + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 180.dp), + singleLine = false + ) + + Button( + onClick = importInput, + modifier = Modifier.fillMaxWidth() + ) { + Text(rh.gs(app.aaps.core.ui.R.string.import_btn)) + } + + when (importResult) { + is ImportResult.Success -> Text( + text = rh.gs(R.string.omnipod_5_certificate_store_imported, formatControllerId(importResult.controllerId)), + color = MaterialTheme.colorScheme.primary, + style = MaterialTheme.typography.labelLarge + ) + + is ImportResult.Failure -> Text( + text = importResult.reason, + color = MaterialTheme.colorScheme.error, + style = MaterialTheme.typography.labelLarge + ) + + ImportResult.RemoveBlocked -> Unit + + ImportResult.None -> Unit + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialWebViewScreen.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialWebViewScreen.kt new file mode 100644 index 000000000000..ec37dfe82965 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialWebViewScreen.kt @@ -0,0 +1,157 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +import android.annotation.SuppressLint +import android.webkit.WebChromeClient +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebView +import android.webkit.WebViewClient +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.CircularProgressIndicator +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.viewinterop.AndroidView +import androidx.webkit.WebMessageCompat +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature +import app.aaps.core.ui.compose.AapsSpacing +import app.aaps.pump.omnipod.common.R +import java.io.IOException +import kotlin.math.max +import app.aaps.core.ui.R as CoreUiR + +/** + * Name the web page uses to reach the app bridge: the page calls + * `bridge.postMessage(jsonString)` to hand back the Omnipod 5 certificate. + */ +private const val BRIDGE_NAME = "aapsKeymanagerBridge" + +/** + * Only the certificate service origin may send messages through the bridge. + */ +private val ALLOWED_ORIGIN_RULES = setOf("https://api.osaid-keymanager.org") + +internal class O5CertificateNetworkException(message: String) : IOException(message) + +internal class O5CredentialWebViewClient( + private val onError: (Throwable) -> Unit +) : WebViewClient() { + + override fun onReceivedError(view: WebView?, request: WebResourceRequest, error: WebResourceError) { + if (!request.isForMainFrame) return + + val message = error.description.toString() + val failure = when (error.errorCode) { + ERROR_HOST_LOOKUP, ERROR_CONNECT, ERROR_IO, ERROR_TIMEOUT -> O5CertificateNetworkException(message) + else -> IOException(message) + } + onError(failure) + } +} + +/** + * Full-screen WebView shown instead of the manual certificate import screen when no Omnipod 5 + * certificate is installed yet. It loads [url] (a pairing/certificate page) and listens for a + * single message posted through `bridge.postMessage(...)` using + * [WebViewCompat.addWebMessageListener]. The received message is expected to be the certificate + * JSON string; it is handed back through [onCredentialReceived]. + */ +@SuppressLint("SetJavaScriptEnabled") +@Composable +fun O5CredentialWebViewScreen( + url: String, + onCredentialReceived: (String) -> Unit, + onCredentialError: (Throwable) -> Unit, + modifier: Modifier = Modifier +) { + val currentOnCredentialReceived by rememberUpdatedState(onCredentialReceived) + val currentOnCredentialError by rememberUpdatedState(onCredentialError) + + if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { + Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Text( + text = stringResource(R.string.omnipod_5_certificate_bridge_unsupported), + style = MaterialTheme.typography.bodyMedium + ) + } + return + } + + var progress by remember { mutableIntStateOf(0) } + var maxProgress by remember { mutableIntStateOf(0) } + Column(modifier = modifier.fillMaxSize()) { + LinearProgressIndicator( + progress = { progress.coerceIn(0, 100) / 100f }, + modifier = Modifier.fillMaxWidth(), + trackColor = MaterialTheme.colorScheme.surface, + ) + Box( + modifier = Modifier.fillMaxSize() + ) { + AndroidView( + modifier = Modifier.fillMaxSize(), + factory = { context -> + WebView(context).apply { + settings.javaScriptEnabled = true + settings.domStorageEnabled = true + webChromeClient = object : WebChromeClient() { + override fun onProgressChanged(view: WebView?, newProgress: Int) { + progress = newProgress + maxProgress = max(maxProgress, newProgress) + } + } + webViewClient = O5CredentialWebViewClient { currentOnCredentialError(it) } + if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { + WebViewCompat.addWebMessageListener( + this, + BRIDGE_NAME, + ALLOWED_ORIGIN_RULES + ) { _, message, _, _, _ -> + if (message.type == WebMessageCompat.TYPE_STRING) { + message.data?.let { currentOnCredentialReceived(it) } + } + } + } else { + currentOnCredentialError(UnsupportedOperationException("WebView WebMessageListener feature not supported")) + } + loadUrl(url) + } + }, + onRelease = { webView -> + if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) { + WebViewCompat.removeWebMessageListener(webView, BRIDGE_NAME) + } + webView.stopLoading() + webView.webChromeClient = null + webView.webViewClient = WebViewClient() + webView.destroy() + } + ) + if (maxProgress <= 50) { + Column(modifier = Modifier.align(Alignment.Center)) { + CircularProgressIndicator( + modifier = Modifier.align(Alignment.CenterHorizontally) + ) + Text( + modifier = Modifier.align(Alignment.CenterHorizontally).padding(top = AapsSpacing.small), + text = stringResource(CoreUiR.string.loading) + ) + } + } + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5OverviewViewModel.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5OverviewViewModel.kt new file mode 100644 index 000000000000..f14c931e863d --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5OverviewViewModel.kt @@ -0,0 +1,508 @@ +package app.aaps.pump.omnipod.omnipod5.ui.compose + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.VolumeUp +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.NotificationsOff +import androidx.compose.material.icons.filled.Pause +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.filled.Schedule +import androidx.compose.runtime.Stable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.insulin.ConcentrationHelper +import app.aaps.core.interfaces.pump.PumpInsulin +import app.aaps.core.interfaces.pump.PumpRate +import app.aaps.core.interfaces.pump.defs.determineCorrectBasalSize +import app.aaps.core.interfaces.pump.defs.determineCorrectBolusSize +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.queue.CustomCommand +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.bus.RxBus +import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.ui.compose.ScreenAction +import app.aaps.core.ui.compose.StatusLevel +import app.aaps.core.ui.compose.pump.PumpCommunicationStatus +import app.aaps.core.ui.compose.pump.PumpInfoRow +import app.aaps.core.ui.compose.pump.PumpOverviewUiState +import app.aaps.core.ui.compose.pump.tickerFlow +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.common.ui.compose.podExpiryRows +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.expiry +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.time +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.timeDrift +import app.aaps.pump.omnipod.common.queue.command.CommandDeactivatePod +import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange +import app.aaps.pump.omnipod.common.queue.command.CommandPlayTestBeep +import app.aaps.pump.omnipod.common.queue.command.CommandResumeDelivery +import app.aaps.pump.omnipod.common.queue.command.CommandSilenceAlerts +import app.aaps.pump.omnipod.common.ui.wizard.compose.ActivationType +import app.aaps.pump.omnipod.common.ui.wizard.compose.OmnipodOverviewEvent +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.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch +import java.time.Duration +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import app.aaps.core.ui.R as CoreUiR +import app.aaps.pump.omnipod.common.R as CommonR + +/** + * O5's pod-status display screen, mirroring + * `DashOverviewViewModel`'s structure. O5's + * [O5PodStateManager] is flatter than Dash's state manager (no computed derived + * properties, no `activeCommand`/`lastBolus`/`tempBasal` value objects, no per-retry + * connection-quality counters, no timezone-drift tracking) - those are approximated here + * from O5's own flat fields ([O5PodStateManager.pendingDoseCommand] in place of Dash's + * `activeCommand`, the [expiry] extension in place of Dash's `expiry` property, etc.) + * rather than adding matching complexity to the state manager. + */ +@Stable +@ContributesIntoMap(AppScope::class, binding = binding()) +@ViewModelKey +class O5OverviewViewModel @Inject constructor( + private val rh: ResourceHelper, + private val podStateManager: O5PodStateManager, + private val commandQueue: CommandQueue, + private val rxBus: RxBus, + private val dateUtil: DateUtil, + private val config: Config, + private val ch: ConcentrationHelper +) : ViewModel() { + + companion object { + + private const val PLACEHOLDER = "-" + + /** Pod-clock drift above this is shown as a warning, same threshold as Dash. */ + private const val MAX_TIME_DEVIATION_MINUTES = 10L + private const val POD_GRACE_PERIOD_HOURS = 8L + } + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val communicationStatus = PumpCommunicationStatus(rxBus, commandQueue, rh, scope) + + private val _events = MutableSharedFlow(extraBufferCapacity = 5) + val events: SharedFlow = _events + + val uiState: StateFlow = combine( + communicationStatus.refreshTrigger, + tickerFlow(15_000L) + ) { _, _ -> buildUiState() }.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(5000), + initialValue = buildUiState() + ) + + private fun buildUiState(): PumpOverviewUiState = + PumpOverviewUiState( + statusBanner = communicationStatus.statusBanner(), + infoRows = buildInfoRows(), + primaryActions = buildPrimaryActions(), + managementActions = buildManagementActions(), + queueStatus = communicationStatus.queueStatus() + ) + + private fun buildInfoRows(): List = buildList { + val activated = podStateManager.activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) + + add( + PumpInfoRow( + label = rh.gs(CommonR.string.omnipod_common_overview_bluetooth_address), + value = podStateManager.bluetoothAddress ?: PLACEHOLDER + ) + ) + val attempts = podStateManager.connectionAttempts + val connQuality = if (attempts > 0) { + val pct = podStateManager.successfulConnections.toDouble() / attempts * 100 + "${podStateManager.successfulConnections}/$attempts :: ${String.format(Locale.getDefault(), "%.2f %%", pct)}" + } else PLACEHOLDER + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_bluetooth_connection_quality), value = connQuality)) + + if (config.isEngineeringMode()) { + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_delivery_status), value = podStateManager.deliveryStatus?.toString() ?: PLACEHOLDER)) + } + + if (!activated) { + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_unique_id), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_lot_number), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_sequence_number), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_firmware_version), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_time_on_pod), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_expiry_date), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_hard_end_date), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_status), value = buildPodStatusText(), level = buildPodStatusLevel())) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_last_connection), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_last_bolus), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_base_basal_rate), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_temp_basal_rate), value = PLACEHOLDER, visible = false)) + add(PumpInfoRow(label = rh.gs(CoreUiR.string.reservoir_label), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_total_delivered), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_active_alerts), value = PLACEHOLDER)) + add(PumpInfoRow(label = rh.gs(CoreUiR.string.errors), value = PLACEHOLDER)) + } else { + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_unique_id), value = podStateManager.podId.toString())) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_lot_number), value = podStateManager.lotNumber.toString())) + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_sequence_number), value = podStateManager.podSequenceNumber.toString())) + add( + PumpInfoRow( + label = rh.gs(CommonR.string.omnipod_common_overview_firmware_version), + value = rh.gs(CommonR.string.omnipod_common_overview_firmware_version_value, podStateManager.firmwareVersion.toString(), podStateManager.bleVersion.toString()) + ) + ) + + val timeZoneStr = podStateManager.timeZoneId?.let { tzId -> + podStateManager.timeZoneUpdated?.let { tzUpdated -> + val tz = TimeZone.getTimeZone(tzId) + val inDST = tz.inDaylightTime(Date(tzUpdated)) + tz.getDisplayName(inDST, TimeZone.SHORT, Locale.getDefault()) + } ?: PLACEHOLDER + } ?: PLACEHOLDER + + val timeOnPodValue = podStateManager.time?.let { + rh.gs(CommonR.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(it.toEpochSecond() * 1000), timeZoneStr) + } ?: PLACEHOLDER + + val timeDeviationTooBig = podStateManager.timeDrift?.let { + Duration.ofMinutes(MAX_TIME_DEVIATION_MINUTES).minus(it.abs()).isNegative + } == true + val timeLevel = when { + !podStateManager.sameTimeZone -> StatusLevel.CRITICAL + timeDeviationTooBig -> StatusLevel.WARNING + else -> StatusLevel.NORMAL + } + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_time_on_pod), value = timeOnPodValue, level = timeLevel)) + + podStateManager.podActivatedAt?.let { + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_activated_at), value = dateUtil.dateAndTimeString(it))) + } + + val expiresAt = podStateManager.expiry + addAll( + podExpiryRows( + rh, dateUtil, dateUtil.now(), + expiresAt = expiresAt?.toInstant()?.toEpochMilli(), + hardEndAt = expiresAt?.plusHours(POD_GRACE_PERIOD_HOURS)?.toInstant()?.toEpochMilli() + ) { dateUtil.dateAndTimeString(it) } + ) + + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_status), value = buildPodStatusText(), level = buildPodStatusLevel())) + + val lastConnValue = podStateManager.lastStatusResponseReceived?.let { + readableDuration(Duration.ofMillis(System.currentTimeMillis() - it)) + } ?: PLACEHOLDER + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_last_connection), value = lastConnValue)) + + val (lastBolusText, lastBolusLevel) = buildLastBolus() + lastBolusText?.let { add(PumpInfoRow(label = rh.gs(CoreUiR.string.last_bolus_label), value = it, level = lastBolusLevel)) } + + val basalText = if (podStateManager.basalProgram != null && !podStateManager.deliverySuspended) { + ch.basalRateString( + rate = PumpRate(PumpType.OMNIPOD_5.determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(System.currentTimeMillis(), podStateManager.timeZoneOffset))), + isAbsolute = true + ) + } else PLACEHOLDER + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_base_basal_rate), value = basalText)) + + val tempBasalText = buildTempBasalText() + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_temp_basal_rate), value = tempBasalText, visible = tempBasalText != PLACEHOLDER)) + + val (reservoirText, reservoirLevel) = buildReservoir() + add(PumpInfoRow(label = rh.gs(CoreUiR.string.reservoir_label), value = reservoirText, level = reservoirLevel)) + + val totalDelivered = podStateManager.totalPulsesDelivered?.let { + ch.insulinAmountString(PumpInsulin(it * PodConstants.POD_PULSE_BOLUS_UNITS)) + } ?: PLACEHOLDER + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_total_delivered), value = totalDelivered)) + + val alertsText = podStateManager.activeAlerts?.let { alerts -> + alerts.joinToString("\n") { t -> translatedActiveAlert(t) + (triggeredAlertTimeSuffix(t) ?: "") } + } ?: PLACEHOLDER + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_overview_pod_active_alerts), value = alertsText)) + + val errors = buildList { + podStateManager.alarmType?.let { alarm -> + add(rh.gs(CommonR.string.omnipod_common_pod_status_pod_fault_description, alarm.code, alarm.toString())) + faultTimeText()?.let { add(rh.gs(CommonR.string.omnipod_common_two_strings_concatenated_by_colon, rh.gs(CommonR.string.omnipod_common_pod_fault_time_label), it)) } + } + } + val errorsText = if (errors.isEmpty()) PLACEHOLDER else errors.joinToString("\n") + add(PumpInfoRow(label = rh.gs(CoreUiR.string.errors), value = errorsText, level = if (errors.isEmpty()) StatusLevel.NORMAL else StatusLevel.CRITICAL)) + podStateManager.alarmType?.pdmFaultCategory?.let { category -> + podStateManager.pdmRef?.let { ref -> + add(PumpInfoRow(label = rh.gs(CommonR.string.omnipod_common_pdm_notification_label), value = category.notificationText(rh, ref))) + } + } + } + } + + + + private fun buildPrimaryActions(): List { + val queueEmpty = isQueueEmpty() + val activated = podStateManager.activationProgress == ActivationProgress.COMPLETED + val podRunning = activated && podStateManager.podStatus?.isRunning() == true + + return listOf( + ScreenAction( + label = rh.gs(CoreUiR.string.refresh), + icon = Icons.Filled.Refresh, + enabled = podStateManager.activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) && queueEmpty, + onClick = { viewModelScope.launch { commandQueue.readStatus(rh.gs(CoreUiR.string.refresh)) } } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_overview_button_silence_alerts), + icon = Icons.Filled.NotificationsOff, + enabled = queueEmpty, + visible = podRunning && (podStateManager.activeAlerts?.isNotEmpty() == true || commandQueue.isCustomCommandInQueue(CommandSilenceAlerts::class)), + onClick = { runCustomCommandWithErrorDialog(CommandSilenceAlerts(), rh.gs(CommonR.string.omnipod_common_error_failed_to_silence_alerts)) } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_overview_button_resume_delivery), + icon = Icons.Filled.PlayArrow, + enabled = queueEmpty, + visible = podRunning && (podStateManager.deliverySuspended || commandQueue.isCustomCommandInQueue(CommandResumeDelivery::class)), + onClick = { runCustomCommandWithErrorDialog(CommandResumeDelivery(), rh.gs(CommonR.string.omnipod_common_error_failed_to_resume_delivery)) } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_overview_button_set_time), + icon = Icons.Filled.Schedule, + enabled = !podStateManager.deliverySuspended && queueEmpty, + visible = false, + onClick = { runCustomCommandWithErrorDialog(CommandHandleTimeChange(true), rh.gs(CommonR.string.omnipod_common_error_failed_to_set_time)) } + ) + ) + } + + private fun buildManagementActions(): List { + isQueueEmpty() + val activated = podStateManager.activationProgress == ActivationProgress.COMPLETED + + return listOf( + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_pod_management_button_activate_pod), + icon = Icons.Filled.PlayArrow, + visible = !activated, + onClick = { onActivatePodClicked() } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_pod_management_button_deactivate_pod), + icon = Icons.Filled.Pause, + visible = activated, + enabled = podStateManager.bluetoothAddress != null || podStateManager.ltk != null, + onClick = { _events.tryEmit(OmnipodOverviewEvent.StartDeactivation) } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_pod_management_button_play_test_beep), + icon = Icons.AutoMirrored.Filled.VolumeUp, + enabled = podStateManager.activationProgress.isAtLeast(ActivationProgress.PHASE_1_COMPLETED) && !commandQueue.isCustomCommandInQueue(CommandPlayTestBeep::class), + visible = podStateManager.activationProgress.isAtLeast(ActivationProgress.PHASE_1_COMPLETED), + onClick = { runCustomCommandWithErrorDialog(CommandPlayTestBeep(), rh.gs(CommonR.string.omnipod_common_error_failed_to_play_test_beep)) } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_pod_management_button_pod_history), + icon = Icons.Filled.History, + onClick = { _events.tryEmit(OmnipodOverviewEvent.ShowHistory) } + ), + ScreenAction( + label = rh.gs(CommonR.string.omnipod_common_pod_management_button_discard_pod), + icon = Icons.Filled.Delete, + visible = podStateManager.podId != null && podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID), + onClick = { onDiscardPodClicked() } + ) + ) + } + + + + private fun onActivatePodClicked() { + viewModelScope.launch { + val type = if (podStateManager.activationProgress.isAtLeast(ActivationProgress.PRIME_COMPLETED)) { + ActivationType.SHORT + } else { + ActivationType.LONG + } + _events.tryEmit(OmnipodOverviewEvent.StartActivation(type)) + } + } + + private fun onDiscardPodClicked() { + _events.tryEmit( + OmnipodOverviewEvent.ShowDialog( + rh.gs(CommonR.string.omnipod_common_pod_management_button_discard_pod), + rh.gs(CommonR.string.omnipod_common_pod_management_discard_pod_confirmation) + ) + ) + } + + fun confirmDiscardPod() { + podStateManager.reset() + } + + + + private fun buildPodStatusText(): String = + when { + podStateManager.activationProgress == ActivationProgress.NOT_STARTED -> rh.gs(CommonR.string.omnipod_common_pod_status_no_active_pod) + podStateManager.activationProgress != ActivationProgress.COMPLETED -> + if (podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID)) { + rh.gs(CommonR.string.omnipod_common_pod_status_waiting_for_activation) + } else if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { + rh.gs(CommonR.string.omnipod_common_pod_status_waiting_for_activation) + } else { + rh.gs(CommonR.string.omnipod_common_pod_status_waiting_for_cannula_insertion) + } + + podStateManager.podStatus?.isRunning() == true -> + if (podStateManager.deliverySuspended) rh.gs(CommonR.string.omnipod_common_pod_status_suspended) + else rh.gs(CommonR.string.omnipod_common_pod_status_running) + + else -> podStateManager.podStatus.toString() + } + + private fun buildPodStatusLevel(): StatusLevel = when { + podStateManager.activationProgress != ActivationProgress.COMPLETED || + podStateManager.alarmType != null || podStateManager.deliverySuspended -> StatusLevel.CRITICAL + podStateManager.pendingDoseCommand != null -> StatusLevel.WARNING + else -> StatusLevel.NORMAL + } + + private fun buildLastBolus(): Pair { + val pending = podStateManager.pendingDoseCommand + if (pending != null && pending.type == O5PodStateManager.PendingDoseType.BOLUS) { + val requested = pending.requestedUnits ?: return null to StatusLevel.NORMAL + var text = ch.insulinAmountAgoString(PumpInsulin(PumpType.OMNIPOD_5.determineCorrectBolusSize(requested)), pending.startedAt) + text += " (${rh.gs(CommonR.string.omnipod_common_uncertain)})" + return text to StatusLevel.CRITICAL + } + val startTime = podStateManager.lastBolusStartTime ?: return null to StatusLevel.NORMAL + val bolusSize = podStateManager.lastBolusDeliveredUnits ?: podStateManager.lastBolusRequestedUnits ?: return null to StatusLevel.NORMAL + val text = ch.insulinAmountAgoString(PumpInsulin(PumpType.OMNIPOD_5.determineCorrectBolusSize(bolusSize)), startTime) + val level = if (podStateManager.lastBolusDeliveredUnits == null) StatusLevel.WARNING else StatusLevel.NORMAL + return text to level + } + + private fun buildTempBasalText(): String { + val startTime = podStateManager.activeTempBasalStartTime + val rate = podStateManager.activeTempBasalRate + val duration = podStateManager.activeTempBasalDurationMinutes + if (podStateManager.deliveryStatus?.tempBasalActive() == true && startTime != null && rate != null && duration != null) { + return ch.basalTbrString(rate = PumpRate(rate), startTime = startTime, durationInMin = duration.toInt()) + } + return PLACEHOLDER + } + + private fun buildReservoir(): Pair { + val reservoirLevel = podStateManager.reservoirPulsesRemaining?.let { PumpInsulin(it * PodConstants.POD_PULSE_BOLUS_UNITS) } + return reservoirLevel?.let { + val lowThreshold = PodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD.toDouble() + val text = ch.insulinAmountString(it) + val level = if (ch.fromPump(it) < lowThreshold) StatusLevel.CRITICAL else StatusLevel.NORMAL + text to level + } ?: (rh.gs(CoreUiR.string.overview_reservoir_concentration_value_over, ch.insulinAmountString(PumpInsulin(50.0))) to StatusLevel.NORMAL) + } + + private fun translatedActiveAlert(alert: AlertType): String { + val id = when (alert) { + AlertType.LOW_RESERVOIR -> CommonR.string.omnipod_common_alert_low_reservoir + AlertType.EXPIRATION -> CommonR.string.omnipod_common_alert_expiration_advisory + AlertType.EXPIRATION_IMMINENT -> CommonR.string.omnipod_common_alert_expiration + AlertType.USER_SET_EXPIRATION -> CommonR.string.omnipod_common_alert_expiration_advisory + AlertType.AUTO_OFF -> CommonR.string.omnipod_common_alert_shutdown_imminent + AlertType.SUSPEND_IN_PROGRESS -> CommonR.string.omnipod_common_alert_delivery_suspended + AlertType.SUSPEND_ENDED -> CommonR.string.omnipod_common_alert_delivery_suspended + else -> CommonR.string.omnipod_common_alert_unknown_alert + } + return rh.gs(id) + } + + /** " (triggered ago)"-style suffix for [alert], if page 1 has reported a + * trigger time for it - null otherwise (never triggered, or page 1 not fetched). */ + private fun triggeredAlertTimeSuffix(alert: AlertType): String? { + val triggered = podStateManager.triggeredAlertTimes?.get(alert) ?: return null + val minutesSince = podStateManager.minutesSinceActivation ?: return null + val elapsed = (minutesSince - triggered).coerceAtLeast(0) + return " (${readableDuration(Duration.ofMinutes(elapsed.toLong()))})" + } + + /** Elapsed-since-fault text derived from [O5PodStateManager.alarmTime] (a + * pod-clock-relative minutes value, same convention as [O5PodStateManager + * .minutesSinceActivation]) - null until a status read has populated both. */ + private fun faultTimeText(): String? { + val alarmTime = podStateManager.alarmTime ?: return null + val minutesSince = podStateManager.minutesSinceActivation ?: return null + val elapsed = (minutesSince - alarmTime).coerceAtLeast(0) + return readableDuration(Duration.ofMinutes(elapsed.toLong())) + } + + private fun readableDuration(duration: Duration): String { + val hours = duration.toHours().toInt() + val minutes = duration.toMinutes().toInt() + val seconds = duration.seconds + return when { + seconds < 10 -> rh.gs(CommonR.string.omnipod_common_moments_ago) + seconds < 60 -> rh.gs(CommonR.string.omnipod_common_less_than_a_minute_ago) + seconds < 60 * 60 -> rh.gs(CommonR.string.omnipod_common_time_ago, rh.gq(CommonR.plurals.omnipod_common_minutes, minutes, minutes)) + + seconds < 24 * 60 * 60 -> { + val minutesLeft = minutes % 60 + if (minutesLeft > 0) + rh.gs(CommonR.string.omnipod_common_time_ago, rh.gs(CommonR.string.omnipod_common_composite_time, rh.gq(CommonR.plurals.omnipod_common_hours, hours, hours), rh.gq(CommonR.plurals.omnipod_common_minutes, minutesLeft, minutesLeft))) + else + rh.gs(CommonR.string.omnipod_common_time_ago, rh.gq(CommonR.plurals.omnipod_common_hours, hours, hours)) + } + + else -> { + val days = hours / 24 + val hoursLeft = hours % 24 + if (hoursLeft > 0) + rh.gs(CommonR.string.omnipod_common_time_ago, rh.gs(CommonR.string.omnipod_common_composite_time, rh.gq(CommonR.plurals.omnipod_common_days, days, days), rh.gq(CommonR.plurals.omnipod_common_hours, hoursLeft, hoursLeft))) + else + rh.gs(CommonR.string.omnipod_common_time_ago, rh.gq(CommonR.plurals.omnipod_common_days, days, days)) + } + } + } + + private fun isQueueEmpty(): Boolean = commandQueue.size() == 0 && commandQueue.performing() == null + + + private fun runCustomCommandWithErrorDialog(customCommand: CustomCommand, errorMessagePrefix: String) { + viewModelScope.launch { + val result = commandQueue.customCommand(customCommand) + if (!result.success) { + _events.tryEmit( + OmnipodOverviewEvent.ShowErrorDialog( + rh.gs(CoreUiR.string.warning), + rh.gs(CommonR.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment) + ) + ) + } + } + } + + override fun onCleared() { + super.onCleared() + scope.cancel() + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5PodHistoryViewModel.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5PodHistoryViewModel.kt new file mode 100644 index 000000000000..345085c3210f --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5PodHistoryViewModel.kt @@ -0,0 +1,41 @@ +package app.aaps.pump.omnipod.omnipod5.ui.compose + +import androidx.compose.runtime.Stable +import androidx.lifecycle.ViewModel +import app.aaps.core.interfaces.profile.ProfileUtil +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.AapsSchedulers +import app.aaps.pump.omnipod.omnipod5.history.O5History +import app.aaps.pump.omnipod.common.history.data.HistoryRecord +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.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import java.util.Calendar +import java.util.GregorianCalendar + +@Stable +@ContributesIntoMap(AppScope::class, binding = binding()) +@ViewModelKey +@Inject +class O5PodHistoryViewModel( + private val o5History: O5History, + private val aapsSchedulers: AapsSchedulers, + val rh: ResourceHelper, + val profileUtil: ProfileUtil +) : ViewModel() { + + private val _records = MutableStateFlow>(emptyList()) + val records: StateFlow> = _records + + init { + val calendar = GregorianCalendar() + calendar.add(Calendar.DAY_OF_MONTH, -5) + _records.value = o5History.getRecordsAfter(calendar.timeInMillis) + .subscribeOn(aapsSchedulers.io) + .blockingGet() + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/OmnipodO5ComposeContent.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/OmnipodO5ComposeContent.kt new file mode 100644 index 000000000000..2362e02b3eae --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/OmnipodO5ComposeContent.kt @@ -0,0 +1,122 @@ +package app.aaps.pump.omnipod.omnipod5.ui.compose + +import android.widget.Toast +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +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.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.core.interfaces.protection.ProtectionCheck +import app.aaps.core.interfaces.pump.BlePreCheck +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.ui.compose.ComposablePluginContent +import app.aaps.core.ui.compose.ToolbarConfig +import app.aaps.core.ui.compose.metroViewModel +import app.aaps.pump.omnipod.common.R +import app.aaps.pump.omnipod.common.ui.compose.OmnipodComposeHost +import app.aaps.pump.omnipod.common.ui.compose.OmnipodPodHistoryScreen +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.omnipod5.ui.O5CredentialImportViewModel +import app.aaps.pump.omnipod.omnipod5.ui.O5CredentialImportWebViewScreen +import app.aaps.pump.omnipod.omnipod5.ui.wizard.compose.O5OmnipodWizardViewModel +import app.aaps.core.ui.R as CoreUiR + +class OmnipodO5ComposeContent( + private val pluginName: String, + private val protectionCheck: ProtectionCheck, + private val blePreCheck: BlePreCheck, + private val rh: ResourceHelper +) : ComposablePluginContent { + + @Composable + override fun Render( + setToolbarConfig: (ToolbarConfig) -> Unit, + onNavigateBack: () -> Unit, + onSettings: (() -> Unit)? + ) { + val overviewViewModel: O5OverviewViewModel = metroViewModel() + val credentialViewModel: O5CredentialImportViewModel = metroViewModel() + OmnipodComposeHost( + pluginName = pluginName, + blePreCheck = blePreCheck, + setToolbarConfig = setToolbarConfig, + onNavigateBack = onNavigateBack, + onSettings = onSettings, + overviewState = overviewViewModel.uiState, + overviewEvents = overviewViewModel.events, + wizardViewModel = { + val viewModel: O5OmnipodWizardViewModel = metroViewModel() + viewModel + }, + onConfirmDiscardPod = overviewViewModel::confirmDiscardPod, + activationNeedsExtraContent = { O5RegistrationData.pickControllerId == 0L }, + showExtraContentForHistory = true, + credentialImportContent = { onImported, onBack -> + val context = LocalContext.current + val title = stringResource(R.string.omnipod_5_certificate_store_import) + val importedMessage = stringResource(R.string.omnipod_5_certificate_imported) + val importErrorMessage = stringResource(R.string.omnipod_5_certificate_import_error) + LaunchedEffect(Unit) { + setToolbarConfig( + ToolbarConfig( + title = title, + navigationIcon = { + IconButton(onClick = onBack) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(CoreUiR.string.back)) + } + }, + actions = {} + ) + ) + } + O5CredentialImportWebViewScreen( + url = stringResource(R.string.omnipod_5_login), + onImportCredential = credentialViewModel::importFromWebMessage, + onImported = { + Toast.makeText(context, importedMessage, Toast.LENGTH_LONG).show() + onImported() + }, + onFailed = { throwable -> + credentialViewModel.importError(throwable) + Toast.makeText(context, importErrorMessage, Toast.LENGTH_LONG).show() + } + ) + }, + extraContent = { onBack -> + val title = stringResource(R.string.omnipod_5_name) + LaunchedEffect(title) { + setToolbarConfig( + ToolbarConfig( + title = title, + navigationIcon = { + IconButton(onClick = { onBack.invoke() }) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(CoreUiR.string.back)) + } + }, + actions = {} + ) + ) + } + val historyViewModel: O5PodHistoryViewModel = metroViewModel() + val records by historyViewModel.records.collectAsStateWithLifecycle() + Box(Modifier.fillMaxSize()) { + OmnipodPodHistoryScreen( + records = records, + rh = historyViewModel.rh, + profileUtil = historyViewModel.profileUtil, + pumpType = PumpType.OMNIPOD_5 + ) + } + } + ) + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/PodFaultText.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/PodFaultText.kt new file mode 100644 index 000000000000..9504c9790766 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/PodFaultText.kt @@ -0,0 +1,23 @@ +package app.aaps.pump.omnipod.omnipod5.ui.compose + +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PdmFaultCategory +import app.aaps.pump.omnipod.omnipod5.R +import app.aaps.pump.omnipod.common.R as CommonR + +/** Omnipod 5 wording for the fault notification. */ +fun PdmFaultCategory.notificationText(rh: ResourceHelper, ref: String): String { + val templateRes = when (this) { + PdmFaultCategory.RESERVOIR_EMPTY -> R.string.omnipod_o5_pdm_notification_reservoir_empty + PdmFaultCategory.AUTO_OFF -> R.string.omnipod_o5_pdm_notification_auto_off + PdmFaultCategory.POD_EXPIRED -> R.string.omnipod_o5_pdm_notification_pod_expired + PdmFaultCategory.OCCLUDED -> R.string.omnipod_o5_pdm_notification_occluded + PdmFaultCategory.POD_ERROR -> R.string.omnipod_o5_pdm_notification_pod_error + } + val message = rh.gs(templateRes) + return when (this) { + PdmFaultCategory.POD_EXPIRED, PdmFaultCategory.POD_ERROR -> + message + "\n\n" + rh.gs(CommonR.string.omnipod_common_pdm_ref, ref) + else -> message + } +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/wizard/compose/O5OmnipodWizardViewModel.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/wizard/compose/O5OmnipodWizardViewModel.kt new file mode 100644 index 000000000000..333a38581157 --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/ui/wizard/compose/O5OmnipodWizardViewModel.kt @@ -0,0 +1,429 @@ +package app.aaps.pump.omnipod.omnipod5.ui.wizard.compose +import app.aaps.pump.omnipod.common.ui.wizard.compose.OmnipodWizardStep +import app.aaps.pump.omnipod.common.ui.wizard.compose.OmnipodWizardViewModel +import app.aaps.pump.omnipod.common.R + +import androidx.annotation.StringRes +import androidx.compose.runtime.Stable +import androidx.lifecycle.viewModelScope +import app.aaps.core.data.model.TE +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.core.data.ue.Sources +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.insulin.InsulinManager +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.notifications.NotificationId +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.profile.ProfileFunction +import app.aaps.core.interfaces.profile.ProfileRepository +import app.aaps.core.interfaces.pump.PumpEnactResult +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.AapsSchedulers +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.IntKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.ui.compose.siteRotation.BodyType +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5BleManager +import app.aaps.pump.omnipod.common.bledriver.pod.command.GetStatusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.GetVersionCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramAlertsCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBolusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.SetUniqueIdCommand +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertConfiguration +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertTrigger +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepRepetitionType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BeepType +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.definition.O5_FIXED_NONCE +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ProgramReminder +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType +import app.aaps.pump.omnipod.common.bledriver.pod.response.SetUniqueIdResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.buildO5ExpirationAlerts +import app.aaps.pump.omnipod.omnipod5.util.I8n +import app.aaps.pump.omnipod.common.keys.OmnipodBooleanPreferenceKey +import app.aaps.pump.omnipod.common.keys.OmnipodIntPreferenceKey +import app.aaps.pump.omnipod.common.queue.command.CommandDeactivatePod +import app.aaps.pump.omnipod.common.util.mapProfileToBasalProgram +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.omnipod5.history.O5History +import androidx.lifecycle.ViewModel +import app.aaps.core.interfaces.rx.bus.RxBus +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 io.reactivex.rxjava3.core.Single +import io.reactivex.rxjava3.kotlin.subscribeBy +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.rx3.await +import kotlinx.coroutines.rx3.rxSingle +import java.util.Date +import app.aaps.pump.omnipod.common.R as CommonR + +/** + * O5's concrete [OmnipodWizardViewModel] - physical pod activation (pairing, prime, + * cannula insertion) and deactivation. Replicates + * [app.aaps.pump.omnipod.dash.driver.OmnipodDashManagerImpl]'s `activatePodPart1`/ + * `activatePodPart2` command sequence exactly (see that class for the reference this was + * built from), but calls [O5BleManager]/command classes directly rather than delegating + * to a Dash-style manager layer - O5 has no such layer, and its per-call + * `Observable` correlation (see [O5BleManager.sendCommand]) makes the + * sequential/blocking style used elsewhere in [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin] + * simpler here too than replicating Dash's reversed-Observable-list construction. + * + * Every sub-step is guarded on [O5PodStateManager.activationProgress] so the wizard's + * built-in retry-on-failure button can be pressed repeatedly without resending + * already-completed commands (matches Dash's identical resumability property). + */ +@Stable +@ContributesIntoMap(AppScope::class, binding = binding()) +@ViewModelKey +class O5OmnipodWizardViewModel @Inject constructor( + private val bleManager: O5BleManager, + private val podStateManager: O5PodStateManager, + private val preferences: Preferences, + private val rh: ResourceHelper, + private val commandQueue: CommandQueue, + private val notificationManager: NotificationManager, + private val history: O5History, + private val pumpSync: PumpSync, + insulinManager: InsulinManager, + persistenceLayer: PersistenceLayer, + profileFunction: ProfileFunction, + profileRepository: ProfileRepository, + pumpEnactResultProvider: () -> PumpEnactResult, + logger: AAPSLogger, + aapsSchedulers: AapsSchedulers, + rxBus: RxBus +) : OmnipodWizardViewModel( + logger, + aapsSchedulers, + pumpEnactResultProvider, + profileFunction, + profileRepository, + insulinManager, + persistenceLayer, + rh, + rxBus +) { + + public override val pumpSource: Sources = Sources.Omnipod5 + + init { + initializeWizard() + } + + override val concentrationEnabled: Boolean + get() = preferences.get(BooleanKey.GeneralInsulinConcentration) + + override val showSiteLocationStep: Boolean + get() = preferences.get(BooleanKey.SiteRotationManagePump) + + override fun bodyType(): BodyType = + BodyType.fromPref(preferences.get(IntKey.SiteRotationUserProfile)) + + + private fun requirePodId(): Int = + podStateManager.podId?.toInt() ?: throw IllegalStateException("O5 pod not paired") + + private fun nextSeq(): Short = podStateManager.msgSequenceNumber.toShort() + + + override fun doInitializePod(): Single = rxSingle(Dispatchers.IO) { + bleManager.isActivationRunning = true + try { + if (podStateManager.ltk == null) { + bleManager.pairNewPod().ignoreElements().await() + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.GOT_POD_VERSION)) { + val cmd = GetVersionCommand.Builder() + .setUniqueId(GetVersionCommand.DEFAULT_UNIQUE_ID) + .setSequenceNumber(nextSeq()) + .build() + bleManager.sendCommand(cmd, VersionResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.GOT_POD_VERSION + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.AID_SETUP)) { + bleManager.sendAidSetupCommands().await() + podStateManager.activationProgress = ActivationProgress.AID_SETUP + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID)) { + val cmd = SetUniqueIdCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setLotNumber(requireNotNull(podStateManager.lotNumber) { "Missing lotNumber" }.toInt()) + .setPodSequenceNumber(requireNotNull(podStateManager.podSequenceNumber) { "Missing podSequenceNumber" }.toInt()) + .setInitializationTime(Date()) + .build() + bleManager.sendCommand(cmd, SetUniqueIdResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.SET_UNIQUE_ID + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.PROGRAMMED_LOW_RESERVOIR_ALERTS)) { + if (preferences.get(OmnipodBooleanPreferenceKey.LowReservoirAlert)) { + val lowReservoirAlertUnits = preferences.get(OmnipodIntPreferenceKey.LowReservoirAlertUnits) + val cmd = ProgramAlertsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setNonce(O5_FIXED_NONCE) + .setAlertConfigurations( + listOf( + AlertConfiguration( + AlertType.LOW_RESERVOIR, enabled = true, durationInMinutes = 0, autoOff = false, + AlertTrigger.ReservoirVolumeTrigger((lowReservoirAlertUnits * 10).toShort()), + BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX + ) + ) + ) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + } + podStateManager.activationProgress = ActivationProgress.PROGRAMMED_LOW_RESERVOIR_ALERTS + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.REPROGRAMMED_LUMP_OF_COAL_ALERT)) { + val cmd = ProgramAlertsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setNonce(O5_FIXED_NONCE) + .setAlertConfigurations( + listOf( + AlertConfiguration( + AlertType.EXPIRATION, enabled = true, durationInMinutes = 55, autoOff = false, + AlertTrigger.TimerTrigger(5), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX5 + ) + ) + ) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.REPROGRAMMED_LUMP_OF_COAL_ALERT + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIMING)) { + bleManager.connect().ignoreElements().await() + val firstPrimeBolusVolume = requireNotNull(podStateManager.firstPrimeBolusVolume) { "Missing firstPrimeBolusVolume" } + val primePulseRate = requireNotNull(podStateManager.primePulseRate) { "Missing primePulseRate" } + val cmd = ProgramBolusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setNonce(O5_FIXED_NONCE) + .setNumberOfUnits(firstPrimeBolusVolume * PodConstants.POD_PULSE_BOLUS_UNITS) + .setDelayBetweenPulsesInEighthSeconds(primePulseRate.toByte()) + .setProgramReminder(ProgramReminder(atStart = false, atEnd = false, atInterval = 0)) + .setO5BolusInfo(mealUnits = 0.0, correctionUnits = 0.0) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.PRIMING + } + + if (podStateManager.activationProgress == ActivationProgress.PRIMING) { + val pulses = podStateManager.firstPrimeBolusVolume ?: 0 + val pulseRateEighthSeconds = podStateManager.primePulseRate ?: 8 + Thread.sleep(pulses.toLong() * pulseRateEighthSeconds.toLong() * 1000 / 8) + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { + bleManager.connect().ignoreElements().await() + val cmd = GetStatusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + check(podStateManager.podStatus == PodStatus.CLUTCH_DRIVE_ENGAGED) { + "Unexpected Pod status: got ${podStateManager.podStatus}, expected CLUTCH_DRIVE_ENGAGED" + } + podStateManager.activationProgress = ActivationProgress.PRIME_COMPLETED + } + + podStateManager.activationProgress = ActivationProgress.PHASE_1_COMPLETED + history.recordSuccess(OmnipodCommandType.INITIALIZE_POD) + pumpEnactResultProvider().success(true) + } catch (throwable: Throwable) { + logger.error(LTag.PUMP, "Error in O5 Pod activation part 1", throwable) + pumpEnactResultProvider().success(false).comment(I8n.textFromException(throwable, rh)) + } finally { + bleManager.isActivationRunning = false + } + } + + override fun doInsertCannula(): Single = rxSingle(Dispatchers.IO) { + bleManager.isActivationRunning = true + try { + val profile = pumpSync.expectedPumpState().profile ?: throw IllegalStateException("No profile set") + val basalProgram = mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5) + + if (podStateManager.activationProgress.isBefore(ActivationProgress.PROGRAMMED_BASAL)) { + val basalBeeps = preferences.get(OmnipodBooleanPreferenceKey.BasalBeepsEnabled) + val cmd = ProgramBasalCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setNonce(O5_FIXED_NONCE) + .setBasalProgram(basalProgram) + .setProgramReminder(ProgramReminder(atStart = basalBeeps, atEnd = false, atInterval = 0)) + .setCurrentTime(Date()) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + podStateManager.updateTimeZone() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.PROGRAMMED_BASAL + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.UPDATED_EXPIRATION_ALERTS)) { + val cmd = ProgramAlertsCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setNonce(O5_FIXED_NONCE) + .setMultiCommandFlag(true) + .setAlertConfigurations(buildO5ExpirationAlerts(podStateManager, preferences, logger)) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.UPDATED_EXPIRATION_ALERTS + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.INSERTING_CANNULA)) { + bleManager.connect().ignoreElements().await() + val secondPrimeBolusVolume = requireNotNull(podStateManager.secondPrimeBolusVolume) { "Missing secondPrimeBolusVolume" } + val primePulseRate = requireNotNull(podStateManager.primePulseRate) { "Missing primePulseRate" } + val cmd = ProgramBolusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setNonce(O5_FIXED_NONCE) + .setNumberOfUnits(secondPrimeBolusVolume * PodConstants.POD_PULSE_BOLUS_UNITS) + .setDelayBetweenPulsesInEighthSeconds(primePulseRate.toByte()) + .setProgramReminder(ProgramReminder(atStart = false, atEnd = false, atInterval = 0)) + .setO5BolusInfo(mealUnits = 0.0, correctionUnits = 0.0) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + podStateManager.activationProgress = ActivationProgress.INSERTING_CANNULA + } + + if (podStateManager.activationProgress == ActivationProgress.INSERTING_CANNULA) { + val pulses = podStateManager.secondPrimeBolusVolume ?: 0 + val pulseRateEighthSeconds = podStateManager.primePulseRate ?: 8 + Thread.sleep(pulses.toLong() * pulseRateEighthSeconds.toLong() * 1000 / 8) + } + + if (podStateManager.activationProgress.isBefore(ActivationProgress.CANNULA_INSERTED)) { + bleManager.connect().ignoreElements().await() + val cmd = GetStatusCommand.Builder() + .setUniqueId(requirePodId()) + .setSequenceNumber(nextSeq()) + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) + .build() + bleManager.sendCommand(cmd, DefaultStatusResponse::class).ignoreElements().await() + ensureActivationTimeNotExceeded() + check(podStateManager.podStatus == PodStatus.RUNNING_ABOVE_MIN_VOLUME) { + "Unexpected Pod status: got ${podStateManager.podStatus}, expected RUNNING_ABOVE_MIN_VOLUME" + } + podStateManager.activationProgress = ActivationProgress.CANNULA_INSERTED + } + + podStateManager.basalProgram = basalProgram + // Also ends the zero "no delivery" temp basal that O5PumpPlugin records while no pod + // is running (connectNewPump defaults to endRunning = true, and stops it under the + // serial it was recorded with). + pumpSync.connectNewPump() + val serial = podStateManager.podId?.toString() ?: "n/a" + pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp = System.currentTimeMillis(), type = TE.Type.CANNULA_CHANGE, pumpType = PumpType.OMNIPOD_5, pumpSerial = serial + ) + pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp = System.currentTimeMillis(), type = TE.Type.INSULIN_CHANGE, pumpType = PumpType.OMNIPOD_5, pumpSerial = serial + ) + notificationManager.dismiss(NotificationId.OMNIPOD_POD_NOT_ATTACHED) + podStateManager.activationProgress = ActivationProgress.COMPLETED + podStateManager.cumulativeBolusPulsesDelivered = podStateManager.totalPulsesDelivered ?: 0 + history.recordSuccess(OmnipodCommandType.INSERT_CANNULA) + viewModelScope.launch { commandQueue.readStatus(rh.gs(CommonR.string.omnipod_common_pod_activation_wizard_pod_activated_title)) } + pumpEnactResultProvider().success(true) + } catch (throwable: Throwable) { + logger.error(LTag.PUMP, "Error in O5 Pod activation part 2", throwable) + pumpEnactResultProvider().success(false).comment(I8n.textFromException(throwable, rh)) + } finally { + bleManager.isActivationRunning = false + } + } + + override fun doDeactivatePod(): Single = rxSingle { + commandQueue.customCommand(CommandDeactivatePod()) + } + + + + override fun discardPod() { + podStateManager.reset() + notificationManager.dismiss(NotificationId.OMNIPOD_POD_FAULT) + } + + override fun isPodInAlarm(): Boolean = podStateManager.alarmType != null + + override fun isPodActivationTimeExceeded(): Boolean = podStateManager.isPodActivationTimeExceeded + + override fun isPodDeactivatable(): Boolean = + podStateManager.ltk != null && podStateManager.controllerId != null && podStateManager.podId != null + + private fun ensureActivationTimeNotExceeded() { + if (podStateManager.isPodActivationTimeExceeded) { + throw IllegalStateException(rh.gs(CommonR.string.omnipod_common_error_pod_fault_activation_time_exceeded)) + } + } + + + + @StringRes + override fun getTitleForStep(step: OmnipodWizardStep): Int = when (step) { + OmnipodWizardStep.PROFILE_GATE -> app.aaps.core.ui.R.string.pump_wizard_profile_gate_title + OmnipodWizardStep.START_POD_ACTIVATION -> CommonR.string.omnipod_common_pod_activation_wizard_start_pod_activation_title + OmnipodWizardStep.SELECT_INSULIN -> app.aaps.core.ui.R.string.select_insulin + OmnipodWizardStep.INITIALIZE_POD -> CommonR.string.omnipod_common_pod_activation_wizard_initialize_pod_title + OmnipodWizardStep.SITE_LOCATION -> app.aaps.core.ui.R.string.site_location + OmnipodWizardStep.ATTACH_POD -> CommonR.string.omnipod_common_pod_activation_wizard_attach_pod_title + OmnipodWizardStep.INSERT_CANNULA -> CommonR.string.omnipod_common_pod_activation_wizard_insert_cannula_title + OmnipodWizardStep.POD_ACTIVATED -> CommonR.string.omnipod_common_pod_activation_wizard_pod_activated_title + OmnipodWizardStep.START_POD_DEACTIVATION -> CommonR.string.omnipod_common_pod_deactivation_wizard_start_pod_deactivation_title + OmnipodWizardStep.DEACTIVATE_POD -> CommonR.string.omnipod_common_pod_deactivation_wizard_deactivating_pod_title + OmnipodWizardStep.POD_DEACTIVATED -> CommonR.string.omnipod_common_pod_deactivation_wizard_pod_deactivated_title + OmnipodWizardStep.POD_DISCARDED -> CommonR.string.omnipod_common_pod_deactivation_wizard_pod_discarded_title + } + + @StringRes + override fun getTextForStep(step: OmnipodWizardStep): Int = when (step) { + OmnipodWizardStep.PROFILE_GATE -> 0 + OmnipodWizardStep.START_POD_ACTIVATION -> CommonR.string.omnipod_5_pod_activation_wizard_start_pod_activation_text + OmnipodWizardStep.SELECT_INSULIN -> app.aaps.core.ui.R.string.select_insulin_description + OmnipodWizardStep.INITIALIZE_POD -> CommonR.string.omnipod_5_pod_activation_wizard_initialize_pod_text + OmnipodWizardStep.SITE_LOCATION -> app.aaps.core.ui.R.string.select_site_location + OmnipodWizardStep.ATTACH_POD -> CommonR.string.omnipod_common_pod_activation_wizard_attach_pod_text + OmnipodWizardStep.INSERT_CANNULA -> CommonR.string.omnipod_common_pod_activation_wizard_insert_cannula_text + OmnipodWizardStep.POD_ACTIVATED -> CommonR.string.omnipod_common_pod_activation_wizard_pod_activated_text + OmnipodWizardStep.START_POD_DEACTIVATION -> CommonR.string.omnipod_common_pod_deactivation_wizard_start_pod_deactivation_text + OmnipodWizardStep.DEACTIVATE_POD -> CommonR.string.omnipod_common_pod_deactivation_wizard_deactivating_pod_text + OmnipodWizardStep.POD_DEACTIVATED -> CommonR.string.omnipod_common_pod_deactivation_wizard_pod_deactivated_text + OmnipodWizardStep.POD_DISCARDED -> CommonR.string.omnipod_common_pod_deactivation_wizard_pod_discarded_text + } + +} diff --git a/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/util/I8n.kt b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/util/I8n.kt new file mode 100644 index 000000000000..72c06de4739e --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/kotlin/app/aaps/pump/omnipod/omnipod5/util/I8n.kt @@ -0,0 +1,24 @@ +package app.aaps.pump.omnipod.omnipod5.util + +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.FailedToConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.NotConnectedException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ScanException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ScanFailFoundTooManyException +import app.aaps.pump.omnipod.omnipod5.R + +class I8n { + companion object { + + fun textFromException(exception: Throwable, rs: ResourceHelper): String { + return when (exception) { + is FailedToConnectException -> rs.gs(R.string.omnipod_o5_failed_to_connect) + is ScanFailFoundTooManyException -> rs.gs(R.string.omnipod_o5_found_too_many_pods) + is ScanException -> rs.gs(R.string.omnipod_o5_scan_failed) + is NotConnectedException -> rs.gs(R.string.omnipod_o5_connection_lost) + else -> + rs.gs(R.string.omnipod_o5_generic_error, exception.toString()) + } + } + } +} diff --git a/pump/omnipod/omnipod5/src/main/res/values/strings.xml b/pump/omnipod/omnipod5/src/main/res/values/strings.xml new file mode 100644 index 000000000000..4fa51f95b99c --- /dev/null +++ b/pump/omnipod/omnipod5/src/main/res/values/strings.xml @@ -0,0 +1,22 @@ + + + Checking delivery status + Command failed + Failed to connect + Found too many Pods + Scan failed + Generic error: %1$s + Connection lost + %1$.2f U/h, %2$d minutes + %1$.2f U + Basal drift compensation bolus: %1$.2f U + + + + Pod Out of Insulin\nPod empty: no insulin left in Pod.\nInsulin delivery stopped.\nChange Pod now. + Pod Shut-Off\nInsulin delivery stopped.\nThe Omnipod 5 App has not communicated with your Pod in the last 4 hours. To start insulin delivery, change your Pod. + Pod Expired\nInsulin delivery stopped.\nChange Pod now. + Blockage detected\nInsulin delivery stopped.\nChange Pod now.\nCheck your BG. + Pod Error\nInsulin delivery stopped.\nChange Pod now. + diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/O5DoseRecoveryTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/O5DoseRecoveryTest.kt new file mode 100644 index 000000000000..2b0a4ce0fce0 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/O5DoseRecoveryTest.kt @@ -0,0 +1,1212 @@ +package app.aaps.pump.omnipod.omnipod5 + +import app.aaps.core.data.model.BS +import app.aaps.core.data.pump.defs.TimeChangeType +import app.aaps.core.interfaces.constraints.Constraint +import app.aaps.core.interfaces.protection.ProtectionCheck +import app.aaps.core.interfaces.notifications.NotificationId +import app.aaps.core.interfaces.pump.BlePreCheck +import app.aaps.core.interfaces.pump.BolusProgressData +import app.aaps.core.interfaces.pump.DetailedBolusInfo +import app.aaps.core.interfaces.pump.PumpInsulin +import app.aaps.core.interfaces.pump.PumpEnactResult +import app.aaps.core.interfaces.pump.PumpProfile +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.profile.Profile +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.pump.omnipod.common.R +import app.aaps.pump.omnipod.common.bledriver.event.PodEvent +import app.aaps.pump.omnipod.common.bledriver.pod.command.GetStatusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBolusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramTempBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.StopDeliveryCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.SuspendDeliveryCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.base.Command +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.queue.command.CommandDeliverBasalCorrection +import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange +import app.aaps.pump.omnipod.common.queue.command.CommandSuspendDelivery +import app.aaps.pump.omnipod.common.util.PodTimeZone +import app.aaps.pump.omnipod.common.util.mapProfileToBasalProgram +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5BleManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.InMemoryO5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.PersistedO5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.nextBasalExpected +import app.aaps.pump.omnipod.omnipod5.history.O5History +import app.aaps.pump.omnipod.omnipod5.history.database.O5HistoryDatabase +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +import app.aaps.shared.tests.TestBaseWithProfile +import com.google.common.truth.Truth.assertThat +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Observable +import io.reactivex.rxjava3.core.Single +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.joinAll +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.EnumSource +import org.junit.jupiter.params.provider.ValueSource +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.atLeastOnce +import org.mockito.kotlin.argThat +import org.mockito.kotlin.doSuspendableAnswer +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.nio.ByteBuffer +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.seconds +import kotlin.time.ExperimentalTime +import kotlin.time.TestTimeSource +import app.aaps.pump.omnipod.omnipod5.R as O5R + +@OptIn(ExperimentalTime::class) +class O5DoseRecoveryTest : TestBaseWithProfile() { + + private companion object { + const val CONCURRENCY_TIMEOUT_MS = 5_000L + // Short wait used to prove that something is still blocked. It is a bound, not a sleep. + const val BLOCKED_PROBE_MS = 200L + } + + @Mock lateinit var ble: O5BleManager + @Mock lateinit var history: O5History + @Mock lateinit var historyDatabase: O5HistoryDatabase + @Mock lateinit var sync: PumpSync + @Mock lateinit var queue: CommandQueue + @Mock lateinit var progress: BolusProgressData + @Mock lateinit var protection: ProtectionCheck + @Mock lateinit var preCheck: BlePreCheck + + private lateinit var state: O5PodStateManager + private lateinit var plugin: O5PumpPlugin + + @BeforeEach + fun setup() { + state = InMemoryO5PodStateManager().also { + it.podId = 12345L + it.ltk = ByteArray(16) + it.cumulativeBolusPulsesDelivered = 0 + it.updateFromDefaultStatusResponse(status(0, DeliveryStatus.BASAL_ACTIVE)) + } + plugin = newPlugin() + whenever(history.createRecord(any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenReturn(Single.just(7L)) + whenever(history.markSent(any())).thenReturn(Completable.complete()) + whenever(history.markSuccess(any())).thenReturn(Completable.complete()) + whenever(history.markSendingFailure(any())).thenReturn(Completable.complete()) + whenever(history.markFailure(any())).thenReturn(Completable.complete()) + whenever(history.setTotalAmountDelivered(any(), anyOrNull())).thenReturn(Completable.complete()) + whenever(ble.connect()).thenReturn(Observable.empty()) + whenever(rh.gs(R.string.omnipod_5_error_bolus_delivery_status_uncertain)).thenReturn("Bolus outcome unknown") + whenever(rh.gs(R.string.omnipod_5_error_unresolved_dose_pending)).thenReturn("Earlier dose unknown") + whenever(rh.gs(R.string.omnipod_5_error_setting_temp_basal_might_have_failed)).thenReturn("Temp basal outcome unknown") + whenever(rh.gs(R.string.omnipod_5_error_setting_basal_profile_might_have_failed)).thenReturn("Profile outcome unknown") + whenever(rh.gs(R.string.omnipod_5_error_uncertain_smb)).thenReturn("SMB outcome unknown: %s") + runBlocking { + whenever(sync.syncStopTemporaryBasalWithPumpId(any(), any(), any(), any(), any())).thenReturn(true) + whenever(sync.syncTemporaryBasalWithPumpId(any(), any(), any(), any(), anyOrNull(), any(), any(), any())).thenReturn(true) + whenever(sync.syncBolusWithPumpId(any(), any(), any(), any(), any(), any())).thenReturn(true) + } + } + + private fun newPlugin() = O5PumpPlugin( + aapsLogger, rh, preferences, queue, ble, state, history, sync, + notificationManager, pumpEnactResultProvider, progress, protection, preCheck, config, historyDatabase + ) + + private fun status(sequence: Int, delivery: DeliveryStatus, remaining: Int = 0): DefaultStatusResponse { + val bytes = ByteBuffer.allocate(10) + .put(0x1d.toByte()) + .put(((delivery.value.toInt() shl 4) or 8).toByte()) + .putInt((sequence shl 11) or remaining) + .putInt(1000) + .array() + return DefaultStatusResponse(bytes) + } + + private fun pendingBolus(accepted: Boolean = false, cancelled: Boolean = false) = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 1.0, + bolusType = BS.Type.SMB, + startedAt = 1000L, + sequenceNumber = 4, + historyId = 7L, + bolusRecordExpected = true, + confirmedByStatus = accepted, + bolusCancelRequested = cancelled, + bolusCancelSequenceNumber = if (cancelled) 6 else null, + bolusCancelHistoryId = if (cancelled) 8L else null + ) + + private fun loopAllowed(): Boolean { + var allowed = true + val constraint = mock>() + doAnswer { allowed = it.getArgument(0); constraint }.whenever(constraint).set(any(), anyOrNull(), any()) + plugin.isLoopInvocationAllowed(constraint) + return allowed + } + + private suspend fun prepareTimeChange(offsetDifference: Int = 3600000) { + state.activationProgress = ActivationProgress.COMPLETED + val zone = PodTimeZone.now() + state.confirmTimeZone(zone.copy(offset = zone.offset - offsetDifference)) + val profile = mock() + whenever(profile.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 1.2))) + whenever(sync.expectedPumpState()).thenReturn(PumpSync.PumpState(null, null, null, profile, "12345")) + } + + private fun respondToTimeCommands() { + var delivery = state.deliveryStatus ?: DeliveryStatus.BASAL_ACTIVE + var acceptedSequence = state.sequenceNumberOfLastProgrammingCommand?.toInt() ?: 0 + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + Observable.defer { + when (command) { + is SuspendDeliveryCommand -> delivery = DeliveryStatus.SUSPENDED + is ProgramBasalCommand -> delivery = DeliveryStatus.BASAL_ACTIVE + is ProgramTempBasalCommand -> delivery = DeliveryStatus.TEMP_BASAL_ACTIVE + } + if (command !is GetStatusCommand) { + acceptedSequence = state.msgSequenceNumber.toInt() + state.increaseMessageSequenceNumber() + } + val response = status(acceptedSequence, delivery) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.ResponseReceived(command, response)) + } + } + } + + @ParameterizedTest + @ValueSource(ints = [3600000, -3600000]) + fun `automatic DST correction releases loop after confirmation in both directions`(difference: Int) = runBlocking { + prepareTimeChange(difference) + respondToTimeCommands() + assertThat(loopAllowed()).isFalse() + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isTrue() + assertThat(state.sameTimeZone).isTrue() + assertThat(state.timeChangeInProgress).isFalse() + assertThat(loopAllowed()).isTrue() + verify(ble).sendCommand(argThat { this is ProgramBasalCommand }, any()) + verify(ble, never()).sendCommand(argThat { this is ProgramBolusCommand }, any()) + } + + @ParameterizedTest + @ValueSource(doubles = [0.0, 0.7, 1.5, 1.2]) + fun `a DST correction suspends and loses any active temp basal, like Medtrum accepts`(rate: Double) = runBlocking { + prepareTimeChange() + val start = System.currentTimeMillis() - 60000 + state.activeTempBasalStartTime = start + state.activeTempBasalRate = rate + state.activeTempBasalDurationMinutes = 30 + state.updateFromDefaultStatusResponse(status(0, DeliveryStatus.TEMP_BASAL_ACTIVE)) + respondToTimeCommands() + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isTrue() + assertThat(state.activeTempBasalRate).isNull() + verify(ble, never()).sendCommand(argThat { this is ProgramTempBasalCommand }, any()) + assertThat(state.timeChangeInProgress).isFalse() + } + + @Test + fun `reported suspend stores the same zero and expected basal stays unchanged`() = runBlocking { + state.activationProgress = ActivationProgress.COMPLETED + state.basalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + state.basalExpected = 2.0 + respondToTimeCommands() + + val result = plugin.executeCustomCommand(CommandSuspendDelivery()) + + assertThat(result.success).isTrue() + val start = requireNotNull(state.activeTempBasalStartTime) + val duration = requireNotNull(state.activeTempBasalDurationMinutes) + assertThat(state.activeTempBasalRate).isEqualTo(0.0) + assertThat(state.nextBasalExpected(start, start + 3_600_000L)).isEqualTo(state.basalExpected) + verify(sync).syncTemporaryBasalWithPumpId( + eq(start), argThat { cU == 0.0 }, eq(duration * 60_000L), eq(true), + eq(PumpSync.TemporaryBasalType.PUMP_SUSPEND), eq(start), eq(PumpType.OMNIPOD_5), eq("12345") + ) + } + + @Test + fun `a denied time update keeps the loop blocked for a retry`() = runBlocking { + prepareTimeChange() + respondToTimeCommands() + whenever(ble.sendCommand(argThat { this is ProgramBasalCommand }, any())).thenReturn(Observable.error(IllegalStateException("denied"))) + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(result.success).isFalse() + assertThat(state.timeChangeInProgress).isTrue() + assertThat(loopAllowed()).isFalse() + assertThat(state.activeTempBasalRate).isEqualTo(0.0) + } + + @Test + fun `automatic time update does not resume a user suspended pod`() = runBlocking { + prepareTimeChange() + state.deliverySuspended = true + state.updateFromDefaultStatusResponse(status(0, DeliveryStatus.SUSPENDED)) + respondToTimeCommands() + + plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + assertThat(state.deliverySuspended).isTrue() + verify(ble, never()).sendCommand(argThat { this is ProgramBasalCommand || this is SuspendDeliveryCommand }, any()) + } + + @Test + fun `automatic time update never interrupts a bolus`() = runBlocking { + prepareTimeChange() + state.updateFromDefaultStatusResponse(status(0, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 10)) + respondToTimeCommands() + + plugin.executeCustomCommand(CommandHandleTimeChange(false)) + + verify(ble, never()).sendCommand(argThat { this is ProgramBasalCommand || this is SuspendDeliveryCommand }, any()) + } + + @Test + fun `DST callback queues correction and polling detects a missed callback after restart`() = runBlocking { + prepareTimeChange() + respondToTimeCommands() + whenever(queue.customCommand(any())).thenAnswer { + plugin.executeCustomCommand(it.getArgument(0)) + } + + plugin.timezoneOrDSTChanged(TimeChangeType.DSTStarted) + plugin.checkTimeChange() + verify(queue, times(1)).customCommand(any()) + state.confirmTimeZone(PodTimeZone.now().let { it.copy(offset = it.offset - 3600000) }) + plugin = newPlugin() + plugin.checkTimeChange() + verify(queue, times(2)).customCommand(any()) + } + + @Test + fun `time correction in-progress flag survives persisted pod restart`() { + val storage = mock() + var json: String? = null + whenever(storage.put(eq(O5StringNonPreferenceKey.PodState), any())).thenAnswer { + json = it.getArgument(1) + Unit + } + whenever(storage.getIfExists(O5StringNonPreferenceKey.PodState)).thenAnswer { json } + whenever(storage.get(O5StringNonPreferenceKey.PodState)).thenAnswer { json ?: "" } + val writer = PersistedO5PodStateManager(aapsLogger, storage) + writer.timeChangeInProgress = true + val reader = PersistedO5PodStateManager(aapsLogger, storage) + + assertThat(reader.timeChangeInProgress).isTrue() + reader.reset() + assertThat(PersistedO5PodStateManager(aapsLogger, storage).timeChangeInProgress).isFalse() + } + + private fun useBolusClock(): TestTimeSource = TestTimeSource().also { clock -> + plugin.bolusTimeSource = clock + plugin.bolusSleep = { clock += it.milliseconds } + } + + private fun stubBolusDelivery(beforeSend: () -> Unit = {}, onStatus: () -> Unit = {}) { + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + Observable.defer { + val pending = requireNotNull(state.pendingDoseCommand) + val response = when (command) { + is ProgramBolusCommand -> { + beforeSend() + status( + requireNotNull(pending.sequenceNumber).toInt(), + DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, + (requireNotNull(pending.requestedUnits) * 20).toInt() + ) + } + is GetStatusCommand -> { + onStatus() + status(requireNotNull(pending.sequenceNumber).toInt(), DeliveryStatus.BASAL_ACTIVE) + } + else -> error("Unexpected command: $command") + } + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + } + } + + @ParameterizedTest + @ValueSource(doubles = [0.05, 1.0, 1.05, 5.0, 10.0]) + fun `bolus progress catches up after delayed sleeps and updates`(amount: Double) = runBlocking { + val clock = useBolusClock() + val start = clock.markNow() + val frames = mutableListOf>() + var confirmationAt = 0L + plugin.bolusSleep = { clock += (it + 125L).milliseconds } + whenever(progress.updateProgress(any())).thenAnswer { + frames += start.elapsedNow().inWholeMilliseconds to it.getArgument(0).cU + clock += 75.milliseconds + Unit + } + stubBolusDelivery(onStatus = { confirmationAt = start.elapsedNow().inWholeMilliseconds }) + + val result = plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = amount }) + + assertThat(result.success).isTrue() + assertThat(result.bolusDelivered).isWithin(0.00001).of(amount) + assertThat(frames).isNotEmpty() + frames.forEach { (elapsedMs, delivered) -> + assertThat(delivered).isWithin(0.00001).of((elapsedMs / 2000L) * 0.05) + assertThat(delivered).isLessThan(amount) + } + val deliveryDurationMs = Math.round(amount * 20) * 2000L + assertThat(confirmationAt).isAtLeast(deliveryDurationMs + 3000L) + assertThat(confirmationAt).isAtMost(deliveryDurationMs + 3125L) + verify(progress, atLeastOnce()).updateProgress( + eq(99), eq(TextRef.AndroidRes(O5R.string.omnipod_5_checking_delivery_status)), eq(PumpInsulin(amount)) + ) + assertThat(state.pendingDoseCommand).isNull() + } + + @Test + fun `bolus progress excludes send preparation and includes history sync time`() = runBlocking { + val clock = useBolusClock() + val start = clock.markNow() + val frames = mutableListOf() + var confirmationAt = 0L + stubBolusDelivery( + beforeSend = { clock += 7.seconds }, + onStatus = { confirmationAt = start.elapsedNow().inWholeMilliseconds } + ) + var syncCalls = 0 + whenever(sync.syncBolusWithPumpId(any(), any(), any(), any(), any(), any())).doSuspendableAnswer { + if (syncCalls++ == 0) clock += 10.seconds + true + } + whenever(progress.updateProgress(any())).thenAnswer { + frames += it.getArgument(0).cU + Unit + } + + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 1.0 }) + + assertThat(frames.first()).isWithin(0.00001).of(0.25) + assertThat(confirmationAt).isEqualTo(50_000L) + assertThat(state.pendingDoseCommand).isNull() + } + + @Test + fun `estimated delivery stays unconfirmed when final status cannot be read`() = runBlocking { + useBolusClock() + stubBolusDelivery(onStatus = { throw IllegalStateException("Status response lost") }) + + val result = plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 1.0 }) + + assertThat(result.comment).isEqualTo("Bolus outcome unknown") + assertThat(state.pendingDoseCommand).isNotNull() + assertThat(state.lastBolusDeliveredUnits).isNull() + verify(history, never()).markSuccess(any()) + verify(progress, atLeastOnce()).updateProgress( + eq(99), eq(TextRef.AndroidRes(O5R.string.omnipod_5_checking_delivery_status)), eq(PumpInsulin(1.0)) + ) + verify(progress, never()).updateProgress(eq(100)) + verify(ble, times(5)).sendCommand(argThat { this is GetStatusCommand }, any()) + } + + @Test + fun `cancellation stops the estimate and confirms the partial delivery`() = runBlocking { + val clock = useBolusClock() + val start = clock.markNow() + plugin.bolusSleep = { + clock += it.milliseconds + if (start.elapsedNow() >= 10.seconds) plugin.stopBolusDelivering() + } + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + val pending = requireNotNull(state.pendingDoseCommand) + val response = when (command) { + is ProgramBolusCommand -> status(requireNotNull(pending.sequenceNumber).toInt(), DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 20) + is StopDeliveryCommand -> status( + requireNotNull(pending.bolusCancelSequenceNumber).toInt(), DeliveryStatus.BASAL_ACTIVE, 15 + ) + else -> error("Unexpected command: $command") + } + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + + val result = plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 1.0 }) + + assertThat(start.elapsedNow()).isEqualTo(10.seconds) + assertThat(result.bolusDelivered).isWithin(0.00001).of(0.25) + assertThat(state.pendingDoseCommand).isNull() + verify(ble).sendCommand(argThat { this is StopDeliveryCommand }, any()) + verify(ble, never()).sendCommand(argThat { this is GetStatusCommand }, any()) + } + + @Test + fun `basal correction uses the same pulse timing and confirmation margin`() { + val clock = useBolusClock() + val start = clock.markNow() + state.activationProgress = ActivationProgress.COMPLETED + state.basalExpected = 0.05 + stubBolusDelivery() + + val result = plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + + assertThat(result.success).isTrue() + assertThat(result.bolusDelivered).isWithin(0.00001).of(0.05) + assertThat(start.elapsedNow()).isEqualTo(5.seconds) + assertThat(state.pendingDoseCommand).isNull() + runBlocking { + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + } + } + + @Test + fun `lost temp response restores original type and delivery once`() = runBlocking { + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + Observable.just(PodEvent.CommandSent(command)) + .concatWith(Observable.error(IllegalStateException("Response lost"))) + } + val result = plugin.setTempBasalAbsolute(0.7, 30, false, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND) + assertThat(result.success).isFalse() + val pending = state.pendingDoseCommand!! + assertThat(pending.tempBasalType).isEqualTo(PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND) + + state.updateFromDefaultStatusResponse(status(1, DeliveryStatus.TEMP_BASAL_ACTIVE)) + joinAll( + launch(Dispatchers.Default) { plugin.reconcilePendingDose() }, + launch(Dispatchers.Default) { plugin.reconcilePendingDose() } + ) + assertThat(state.activeTempBasalStartTime).isEqualTo(pending.startedAt) + assertThat(state.activeTempBasalRate).isEqualTo(0.7) + assertThat(state.activeTempBasalDurationMinutes).isEqualTo(30.toShort()) + assertThat(state.pendingDoseCommand).isNull() + verify(sync, times(1)).syncTemporaryBasalWithPumpId( + eq(pending.startedAt), argThat { cU == 0.7 }, eq(1_800_000L), eq(true), + eq(PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND), eq(7L), eq(PumpType.OMNIPOD_5), eq("12345") + ) + verify(history).markSuccess(7L) + } + + @Test + fun `accepted expired temp is recorded without a running temp`() = runBlocking { + state.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_START, + requestedRate = 0.5, requestedDurationMinutes = 30, startedAt = 1000L, + sequenceNumber = 4, historyId = 7L, tempBasalType = PumpSync.TemporaryBasalType.NORMAL + ) + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNull() + assertThat(state.activeTempBasalStartTime).isNull() + assertThat(state.activeTempBasalRate).isNull() + assertThat(state.activeTempBasalDurationMinutes).isNull() + verify(sync).syncTemporaryBasalWithPumpId( + eq(1000L), argThat { cU == 0.5 }, eq(1_800_000L), eq(true), + eq(PumpSync.TemporaryBasalType.NORMAL), eq(7L), eq(PumpType.OMNIPOD_5), eq("12345") + ) + } + + @Test + fun `lost profile response restores exact program and ends suspension once`() = runBlocking { + state.updateFromDefaultStatusResponse(status(0, DeliveryStatus.SUSPENDED)) + val profile = mock() + whenever(profile.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 0.7), Profile.ProfileValue(43200, 1.2))) + whenever(ble.sendCommand(any(), any())).thenReturn(Observable.error(IllegalStateException("Response lost"))) + assertThat(plugin.setNewBasalProfile(profile).success).isFalse() + val pending = state.pendingDoseCommand!! + val requested = mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5) + assertThat(pending.requestedBasalProgram).isEqualTo(requested) + state.updateFromDefaultStatusResponse(status(1, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + plugin.reconcilePendingDose() + assertThat(state.basalProgram).isEqualTo(requested) + assertThat(state.deliverySuspended).isFalse() + assertThat(state.timeZoneId).isNotNull() + assertThat(state.pendingDoseCommand).isNull() + verify(sync).syncStopTemporaryBasalWithPumpId(eq(pending.startedAt), eq(7L), eq(PumpType.OMNIPOD_5), eq("12345"), any()) + } + + @Test + fun `old active basal does not confirm a rejected new profile`() = runBlocking { + val old = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + state.basalProgram = old + state.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BASAL_PROGRAM, startedAt = 1000L, + sequenceNumber = 4, historyId = 7L, + requestedBasalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 120))) + ) + state.updateFromDefaultStatusResponse(status(2, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + assertThat(state.basalProgram).isEqualTo(old) + assertThat(state.pendingDoseCommand).isNull() + verify(history).markFailure(7L) + verify(sync, never()).syncStopTemporaryBasalWithPumpId(any(), any(), any(), any(), any()) + } + + @Test + fun `old active basal alone leaves a profile with no acceptance evidence pending`() = runBlocking { + val pending = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BASAL_PROGRAM, startedAt = 1000L, + requestedBasalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 120))) + ) + state.pendingDoseCommand = pending + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isEqualTo(pending) + assertThat(state.basalProgram).isNull() + } + + @Test + fun `rejected temp does not create a delivery record`() = runBlocking { + state.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_START, + requestedRate = 0.5, requestedDurationMinutes = 30, startedAt = 1000L, + sequenceNumber = 4, historyId = 7L + ) + state.updateFromDefaultStatusResponse(status(2, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNull() + assertThat(state.activeTempBasalRate).isNull() + verify(sync, never()).syncTemporaryBasalWithPumpId(any(), any(), any(), any(), anyOrNull(), any(), any(), any()) + verify(history).markFailure(7L) + } + + @Test + fun `cancel sequence alone cannot settle an unaccepted bolus or zero its record`() = runBlocking { + state.pendingDoseCommand = pendingBolus(cancelled = true) + state.updateFromDefaultStatusResponse(status(6, DeliveryStatus.BASAL_ACTIVE, 10)) + plugin.reconcilePendingDose() + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNotNull() + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + whenever(ble.sendCommand(any(), any())).thenReturn(Observable.empty()) + val result = plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.5 }) + assertThat(result.success).isFalse() + verify(ble, never()).sendCommand(argThat { this is ProgramBolusCommand }, any()) + } + + @Test + fun `older pending bolus without saved cancel intent cannot be rejected from another sequence`() = runBlocking { + state.pendingDoseCommand = pendingBolus().copy(bolusCancelRequested = null) + state.updateFromDefaultStatusResponse(status(6, DeliveryStatus.BASAL_ACTIVE, 10)) + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNotNull() + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + } + + @Test + fun `accepted bolus survives a later cancel sequence and accounts partial delivery once`() = runBlocking { + state.pendingDoseCommand = pendingBolus(accepted = true, cancelled = true) + state.updateFromDefaultStatusResponse(status(6, DeliveryStatus.BASAL_ACTIVE, 12)) + plugin.reconcilePendingDose() + plugin.reconcilePendingDose() + assertThat(state.lastBolusDeliveredUnits).isWithin(0.00001).of(0.4) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(8.toShort()) + assertThat(state.pendingDoseCommand).isNull() + verify(sync).syncBolusWithPumpId(eq(1000L), argThat { cU > 0.39 && cU < 0.41 }, eq(BS.Type.SMB), eq(7L), any(), any()) + verify(history).markSuccess(8L) + } + + @Test + fun `a running accepted bolus cannot be finalized from its remaining pulses`() = runBlocking { + state.pendingDoseCommand = pendingBolus(accepted = true) + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 12)) + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNotNull() + assertThat(state.lastBolusDeliveredUnits).isNull() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(8.toShort()) + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + } + + @Test + fun `saved acceptance cannot finalize from an unrelated inactive status`() = runBlocking { + state.pendingDoseCommand = pendingBolus() + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 16)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(4.toShort()) + state.updateFromDefaultStatusResponse(status(9, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNotNull() + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(4.toShort()) + assertThat(state.lastBolusDeliveredUnits).isNull() + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + } + + @Test + fun `unknown delivery status cannot finalize or account a requested bolus`() = runBlocking { + state.pendingDoseCommand = pendingBolus() + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.UNKNOWN)) + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNotNull() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(0.toShort()) + assertThat(state.lastBolusDeliveredUnits).isNull() + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + } + + @Test + fun `failed finalization retains accounted progress and retry adds no pulses`() = runBlocking { + state.pendingDoseCommand = pendingBolus() + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 16)) + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(20.toShort()) + whenever(history.setTotalAmountDelivered(eq(7L), anyOrNull())) + .thenReturn(Completable.error(IllegalStateException("Store unavailable")), Completable.complete()) + assertThrows { runBlocking { plugin.reconcilePendingDose() } } + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(20) + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + plugin.reconcilePendingDose() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(20.toShort()) + assertThat(state.pendingDoseCommand).isNull() + verify(sync).syncBolusWithPumpId(eq(1000L), argThat { cU == 1.0 }, any(), eq(7L), any(), any()) + } + + @Test + fun `status recovery waits for bolus accounting and runs after the dose lock is released`() = runBlocking { + val programEntered = CountDownLatch(1) + val allowProgram = CountDownLatch(1) + val accountingEntered = CountDownLatch(1) + val allowAccounting = CountDownLatch(1) + val statusStarted = CountDownLatch(1) + val statusCommandEntered = CountDownLatch(1) + + whenever(history.setTotalAmountDelivered(any(), anyOrNull())).thenReturn( + Completable.fromAction { + accountingEntered.countDown() + check(allowAccounting.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) + } + ) + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + when (command) { + is ProgramBolusCommand -> { + programEntered.countDown() + check(allowProgram.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) + val response = status(1, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 1) + state.updateFromDefaultStatusResponse(response) + state.increaseMessageSequenceNumber() + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is StopDeliveryCommand -> { + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is GetStatusCommand -> { + statusCommandEntered.countDown() + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + else -> Observable.empty() + } + } + + val bolus = async(Dispatchers.IO) { + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.05 }) + } + try { + assertThat(programEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + withTimeout(CONCURRENCY_TIMEOUT_MS) { + async(Dispatchers.IO) { plugin.stopBolusDelivering() }.await() + } + allowProgram.countDown() + assertThat(accountingEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + + val statusRead = async(Dispatchers.IO) { + statusStarted.countDown() + plugin.getPumpStatus("concurrent recovery test") + } + assertThat(statusStarted.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + // Simulated hung accounting holds the dose lock, so the waiting status read must time out. + assertThrows { + runBlocking { withTimeout(BLOCKED_PROBE_MS) { statusRead.await() } } + } + assertThat(statusRead.isActive).isTrue() + assertThat(statusCommandEntered.count).isEqualTo(1L) + + allowAccounting.countDown() + withTimeout(CONCURRENCY_TIMEOUT_MS) { bolus.await() } + withTimeout(CONCURRENCY_TIMEOUT_MS) { statusRead.await() } + assertThat(statusCommandEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + assertThat(state.pendingDoseCommand).isNull() + } finally { + allowProgram.countDown() + allowAccounting.countDown() + } + } + + @Test + fun `status read times out while a hung pod command holds the dose lock and resumes after release`() = runBlocking { + val programEntered = CountDownLatch(1) + val allowProgram = CountDownLatch(1) + val statusCommandEntered = CountDownLatch(1) + + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + when (command) { + is ProgramBolusCommand -> { + // Simulated hung BLE call inside the dose lock. The wait is finite and released in finally. + programEntered.countDown() + check(allowProgram.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) + val response = status(1, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 1) + state.updateFromDefaultStatusResponse(response) + state.increaseMessageSequenceNumber() + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is StopDeliveryCommand -> { + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is GetStatusCommand -> { + statusCommandEntered.countDown() + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + else -> Observable.empty() + } + } + + val bolus = async(Dispatchers.IO) { + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.05 }) + } + try { + assertThat(programEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + val statusRead = async(Dispatchers.IO) { plugin.getPumpStatus("hung pod command test") } + + assertThrows { + runBlocking { withTimeout(BLOCKED_PROBE_MS) { statusRead.await() } } + } + assertThat(statusRead.isActive).isTrue() + assertThat(statusCommandEntered.count).isEqualTo(1L) + + // Stop the bolus so the completion wait ends early, then release the hung command. + withTimeout(CONCURRENCY_TIMEOUT_MS) { + async(Dispatchers.IO) { plugin.stopBolusDelivering() }.await() + } + allowProgram.countDown() + withTimeout(CONCURRENCY_TIMEOUT_MS) { bolus.await() } + withTimeout(CONCURRENCY_TIMEOUT_MS) { statusRead.await() } + assertThat(statusCommandEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + assertThat(state.pendingDoseCommand).isNull() + } finally { + allowProgram.countDown() + } + } + + @Test + fun `BLE callback waiting for plugin status deadlocks the dose lock until externally released`() = runBlocking { + val allowResponse = CountDownLatch(1) + val statusAttempted = CompletableDeferred>() + val statusCommandEntered = CountDownLatch(1) + val scopeJob = SupervisorJob() + val testScope = CoroutineScope(scopeJob + Dispatchers.IO) + + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + when (command) { + is ProgramBolusCommand -> Observable.defer { + // Start inline: getPumpStatus reaches the real dose lock before async returns. + val statusRead = testScope.async(start = CoroutineStart.UNDISPATCHED) { + plugin.getPumpStatus("BLE callback circular wait test") + } + statusRead.invokeOnCompletion { allowResponse.countDown() } + statusAttempted.complete(statusRead) + // Bolus owns doseMutex -> BLE response -> status read -> the same doseMutex. + check(allowResponse.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) + val response = status(1, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 1) + state.updateFromDefaultStatusResponse(response) + state.increaseMessageSequenceNumber() + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is StopDeliveryCommand -> { + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is GetStatusCommand -> { + statusCommandEntered.countDown() + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + else -> Observable.empty() + } + } + + val bolus = testScope.async { + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.05 }) + } + try { + val statusRead = withTimeout(CONCURRENCY_TIMEOUT_MS) { statusAttempted.await() } + withTimeout(CONCURRENCY_TIMEOUT_MS) { + async(Dispatchers.IO) { plugin.stopBolusDelivering() }.await() + } + // Only this test has a timeout. Production has no lock timeout or automatic recovery. + assertThrows { + runBlocking { withTimeout(BLOCKED_PROBE_MS) { statusRead.await() } } + } + assertThrows { + runBlocking { withTimeout(BLOCKED_PROBE_MS) { bolus.await() } } + } + assertThat(statusRead.isActive).isTrue() + assertThat(bolus.isActive).isTrue() + assertThat(allowResponse.count).isEqualTo(1L) + assertThat(statusCommandEntered.count).isEqualTo(1L) + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + + // Break the injected dependency, not the lock, and let both plugin calls finish. + allowResponse.countDown() + val result = withTimeout(CONCURRENCY_TIMEOUT_MS) { bolus.await() } + withTimeout(CONCURRENCY_TIMEOUT_MS) { statusRead.await() } + assertThat(result.success).isTrue() + assertThat(result.bolusDelivered).isWithin(0.00001).of(0.05) + assertThat(statusCommandEntered.count).isEqualTo(0L) + withTimeout(CONCURRENCY_TIMEOUT_MS) { plugin.getPumpStatus("after circular wait recovery") } + assertThat(state.pendingDoseCommand).isNull() + assertThat(state.lastBolusDeliveredUnits).isWithin(0.00001).of(0.05) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(1.toShort()) + verify(history, times(1)).setTotalAmountDelivered(eq(7L), eq(0.05)) + // The expected and final amounts update the same pump record; recovery adds neither. + verify(sync, times(2)).syncBolusWithPumpId( + any(), argThat { cU == 0.05 }, any(), eq(7L), eq(PumpType.OMNIPOD_5), eq("12345") + ) + verify(ble, times(1)).sendCommand(argThat { this is ProgramBolusCommand }, any()) + verify(ble, times(1)).sendCommand(argThat { this is StopDeliveryCommand }, any()) + verify(ble, times(2)).sendCommand(argThat { this is GetStatusCommand }, any()) + } finally { + allowResponse.countDown() + withTimeout(CONCURRENCY_TIMEOUT_MS) { + scopeJob.children.toList().joinAll() + scopeJob.cancelAndJoin() + } + } + assertThat(scopeJob.isCompleted).isTrue() + } + + @Test + fun `bolus cancellation returns while the dose lock is held and sends a stop command`() = runBlocking { + val programEntered = CountDownLatch(1) + val allowProgram = CountDownLatch(1) + val stopCommandEntered = CountDownLatch(1) + + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + when (command) { + is ProgramBolusCommand -> { + programEntered.countDown() + check(allowProgram.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) + val response = status(1, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 1) + state.updateFromDefaultStatusResponse(response) + state.increaseMessageSequenceNumber() + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is StopDeliveryCommand -> { + stopCommandEntered.countDown() + val response = status(2, DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + else -> Observable.empty() + } + } + + val bolus = async(Dispatchers.IO) { + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.05 }) + } + try { + assertThat(programEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + withTimeout(CONCURRENCY_TIMEOUT_MS) { + async(Dispatchers.IO) { plugin.stopBolusDelivering() }.await() + } + allowProgram.countDown() + withTimeout(CONCURRENCY_TIMEOUT_MS) { bolus.await() } + assertThat(stopCommandEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + verify(ble).sendCommand(argThat { this is StopDeliveryCommand }, any()) + } finally { + allowProgram.countDown() + } + } + + @Test + fun `queued basal correction runs after temp basal releases the dose lock`() = runBlocking { + val queueEntered = CountDownLatch(1) + val correctionAttempting = CountDownLatch(1) + val correctionEntered = CountDownLatch(1) + val allowCorrection = CountDownLatch(1) + val queueResult = CompletableDeferred() + val queueCallerReturned = CompletableDeferred() + val scopeJob = SupervisorJob() + val testScope = CoroutineScope(scopeJob + Dispatchers.IO) + + state.activationProgress = ActivationProgress.COMPLETED + state.basalExpected = 0.05 + plugin.scope = testScope + whenever(queue.isCustomCommandInQueue(CommandDeliverBasalCorrection::class)).thenReturn(false) + // Model the real queue: the caller suspends until a separate worker has run the command. + whenever(queue.customCommand(any())).doSuspendableAnswer { + queueEntered.countDown() + testScope.launch { + correctionAttempting.countDown() + queueResult.complete( + plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + ) + } + queueResult.await().also { queueCallerReturned.complete(it) } + } + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + when (command) { + is ProgramTempBasalCommand -> { + val response = status(0, DeliveryStatus.TEMP_BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + state.basalExpected = 0.05 + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is ProgramBolusCommand -> { + correctionEntered.countDown() + check(allowCorrection.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)) + val response = status(state.msgSequenceNumber.toInt(), DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 1) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + is StopDeliveryCommand -> { + val response = status(state.msgSequenceNumber.toInt(), DeliveryStatus.BASAL_ACTIVE) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } + else -> Observable.empty() + } + } + + try { + // The temp basal holds the dose lock while it enqueues the correction. It must return + // without waiting for the queued command, or the two would deadlock. + val tempBasalResult = withTimeout(CONCURRENCY_TIMEOUT_MS) { + async(Dispatchers.IO) { + plugin.setTempBasalAbsolute(0.4, 30, false, PumpSync.TemporaryBasalType.NORMAL) + }.await() + } + assertThat(tempBasalResult.success).isTrue() + assertThat(queueEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + assertThat(correctionAttempting.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + + // The correction now owns the dose lock and is held inside the pod command. + assertThat(correctionEntered.await(CONCURRENCY_TIMEOUT_MS, TimeUnit.MILLISECONDS)).isTrue() + assertThrows { + runBlocking { withTimeout(BLOCKED_PROBE_MS) { queueCallerReturned.await() } } + } + assertThat(queueResult.isActive).isTrue() + + withTimeout(CONCURRENCY_TIMEOUT_MS) { + async(Dispatchers.IO) { plugin.stopBolusDelivering() }.await() + } + allowCorrection.countDown() + withTimeout(CONCURRENCY_TIMEOUT_MS) { queueCallerReturned.await() } + + assertThat(state.pendingDoseCommand).isNull() + assertThat(state.lastBolusDeliveredUnits).isWithin(0.00001).of(0.05) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(0.toShort()) + verify(sync, never()).syncBolusWithPumpId(any(), any(), any(), any(), any(), any()) + verify(ble, times(1)).sendCommand(argThat { this is ProgramBolusCommand }, any()) + verify(queue, times(1)).customCommand(any()) + } finally { + allowCorrection.countDown() + withTimeout(CONCURRENCY_TIMEOUT_MS) { + scopeJob.children.toList().joinAll() + scopeJob.cancelAndJoin() + } + } + } + + @ParameterizedTest + @EnumSource(value = BS.Type::class, names = ["NORMAL", "SMB"]) + fun `normal response saves acceptance before cancellation with lost stop responses`(type: BS.Type) = runBlocking { + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + if (command is ProgramBolusCommand) { + val response = status(1, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 10) + state.updateFromDefaultStatusResponse(response) + state.msgSequenceNumber = 3 + plugin.stopBolusDelivering() + Observable.just(PodEvent.CommandSent(command), PodEvent.ResponseReceived(command, response)) + } else { + assertThat(command).isInstanceOf(StopDeliveryCommand::class.java) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + assertThat(state.pendingDoseCommand!!.bolusCancelRequested).isTrue() + assertThat(state.pendingDoseCommand!!.bolusCancelSequenceNumber).isEqualTo(3.toShort()) + Observable.error(IllegalStateException("Stop response lost")) + } + } + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.5; it.bolusType = type }) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + state.updateFromDefaultStatusResponse(status(3, DeliveryStatus.BASAL_ACTIVE, 4)) + plugin.reconcilePendingDose() + plugin.reconcilePendingDose() + assertThat(state.lastBolusDeliveredUnits).isWithin(0.00001).of(0.3) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(6.toShort()) + assertThat(state.pendingDoseCommand).isNull() + verify(sync, never()).syncBolusWithPumpId(any(), argThat { cU == 0.0 }, any(), any(), any(), any()) + } + + @Test + fun `successful write without response keeps SMB unknown rather than accepted`() = runBlocking { + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + Observable.just(PodEvent.CommandSent(command)).concatWith(Observable.error(IllegalStateException("Response lost"))) + } + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.5; it.bolusType = BS.Type.SMB }) + assertThat(state.pendingDoseCommand).isNotNull() + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_UNCERTAIN_SMB), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + state.updateFromDefaultStatusResponse(status(1, DeliveryStatus.BASAL_ACTIVE)) + plugin.reconcilePendingDose() + assertThat(state.lastBolusDeliveredUnits).isEqualTo(0.5) + assertThat(state.pendingDoseCommand).isNull() + } + + @Test + fun `cancel requested during lost program response sends a stop but does not invent acceptance`() = runBlocking { + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + if (command is ProgramBolusCommand) { + plugin.stopBolusDelivering() + state.msgSequenceNumber = 3 + Observable.just(PodEvent.CommandSent(command)).concatWith(Observable.error(IllegalStateException("Response lost"))) + } else { + assertThat(state.pendingDoseCommand!!.bolusCancelRequested).isTrue() + assertThat(state.pendingDoseCommand!!.bolusCancelSequenceNumber).isEqualTo(3.toShort()) + Observable.error(IllegalStateException("Stop response lost")) + } + } + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 0.5 }) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + state.updateFromDefaultStatusResponse(status(3, DeliveryStatus.BASAL_ACTIVE, 4)) + plugin.reconcilePendingDose() + assertThat(state.pendingDoseCommand).isNotNull() + verify(ble).sendCommand(argThat { this is StopDeliveryCommand }, any()) + verify(sync, never()).syncBolusWithPumpId(any(), argThat { cU == 0.0 }, any(), any(), any(), any()) + } + + @Test + fun `normal temp and profile responses use the same confirmation state`() = runBlocking { + whenever(ble.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + val delivery = when (command) { + is ProgramBasalCommand -> DeliveryStatus.BASAL_ACTIVE + is StopDeliveryCommand -> DeliveryStatus.BASAL_ACTIVE + else -> DeliveryStatus.TEMP_BASAL_ACTIVE + } + val response = status(state.msgSequenceNumber.toInt(), delivery) + state.updateFromDefaultStatusResponse(response) + Observable.just(PodEvent.ResponseReceived(command, response)) + } + assertThat(plugin.setTempBasalAbsolute(0.7, 30, false, PumpSync.TemporaryBasalType.SUPERBOLUS).success).isTrue() + assertThat(state.activeTempBasalRate).isEqualTo(0.7) + assertThat(state.pendingDoseCommand).isNull() + val profile = mock() + whenever(profile.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 1.2))) + assertThat(plugin.setNewBasalProfile(profile).success).isTrue() + assertThat(state.basalProgram).isEqualTo(mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5)) + assertThat(state.activeTempBasalRate).isNull() + assertThat(state.pendingDoseCommand).isNull() + } + + @Test + fun `failed accounting leaves accepted temp pending until it can be saved`() = runBlocking { + state.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_START, + requestedRate = 0.5, requestedDurationMinutes = 30, startedAt = System.currentTimeMillis(), + sequenceNumber = 4, historyId = 7L + ) + state.updateFromDefaultStatusResponse(status(4, DeliveryStatus.TEMP_BASAL_ACTIVE)) + whenever(sync.syncTemporaryBasalWithPumpId(any(), any(), any(), any(), anyOrNull(), any(), any(), any())) + .thenThrow(IllegalStateException("Store unavailable")).thenReturn(true) + try { + plugin.reconcilePendingDose() + } catch (_: IllegalStateException) { + // The pending marker must survive a failed database write. + } + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + plugin.reconcilePendingDose() + assertThat(state.activeTempBasalRate).isEqualTo(0.5) + assertThat(state.pendingDoseCommand).isNull() + } + + @Test + fun `restart after accepted bolus and lost stop response keeps partial accounting once`() = runBlocking { + val storage = mock() + var json: String? = null + whenever(storage.put(eq(O5StringNonPreferenceKey.PodState), any())).thenAnswer { + json = it.getArgument(1) + Unit + } + whenever(storage.getIfExists(O5StringNonPreferenceKey.PodState)).thenAnswer { json } + whenever(storage.get(O5StringNonPreferenceKey.PodState)).thenAnswer { json ?: "" } + val writer = PersistedO5PodStateManager(aapsLogger, storage) + writer.podId = 12345L + writer.cumulativeBolusPulsesDelivered = 10 + writer.pendingDoseCommand = pendingBolus() + writer.updateFromDefaultStatusResponse(status(4, DeliveryStatus.BOLUS_AND_BASAL_ACTIVE, 16)) + assertThat(writer.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + writer.pendingDoseCommand = writer.pendingDoseCommand!!.copy( + bolusCancelRequested = true, bolusCancelSequenceNumber = 6, bolusCancelHistoryId = 8L + ) + state = PersistedO5PodStateManager(aapsLogger, storage) + plugin = newPlugin() + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(4) + state.updateFromDefaultStatusResponse(status(6, DeliveryStatus.BASAL_ACTIVE, 12)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(18.toShort()) + plugin.reconcilePendingDose() + state = PersistedO5PodStateManager(aapsLogger, storage) + plugin = newPlugin() + plugin.reconcilePendingDose() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(18.toShort()) + assertThat(state.lastBolusDeliveredUnits).isWithin(0.00001).of(0.4) + assertThat(state.pendingDoseCommand).isNull() + verify(sync).syncBolusWithPumpId(eq(1000L), argThat { cU > 0.39 && cU < 0.41 }, any(), eq(7L), any(), any()) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/O5PumpPluginTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/O5PumpPluginTest.kt new file mode 100644 index 000000000000..f4b602839480 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/O5PumpPluginTest.kt @@ -0,0 +1,1806 @@ +package app.aaps.pump.omnipod.omnipod5 +import app.aaps.pump.omnipod.common.R + +import app.aaps.core.data.pump.defs.ManufacturerType +import app.aaps.core.data.model.BS +import app.aaps.core.data.pump.defs.PumpType +import app.aaps.core.interfaces.protection.ProtectionCheck +import app.aaps.core.interfaces.pump.BlePreCheck +import app.aaps.core.interfaces.pump.BolusProgressData +import app.aaps.core.interfaces.pump.DetailedBolusInfo +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.pump.PumpProfile +import app.aaps.core.interfaces.profile.Profile +import app.aaps.core.interfaces.plugin.OwnDatabasePlugin +import app.aaps.core.interfaces.notifications.AlarmSound +import app.aaps.core.keys.interfaces.TextRef +import app.aaps.pump.omnipod.common.keys.DashBooleanPreferenceKey +import org.mockito.verification.VerificationMode +import app.aaps.core.interfaces.pump.PumpInsulin +import app.aaps.core.interfaces.notifications.NotificationId +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.queue.CustomCommand +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5BleManager +import app.aaps.pump.omnipod.common.bledriver.event.PodEvent +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.MessageIOException +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.common.bledriver.pod.command.StopDeliveryCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.SuspendDeliveryCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.GetStatusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramBolusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramTempBasalCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.ProgramAlertsCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.base.Command +import app.aaps.pump.omnipod.common.queue.command.CommandDeactivatePod +import app.aaps.pump.omnipod.common.queue.command.CommandDeliverBasalCorrection +import app.aaps.pump.omnipod.common.queue.command.CommandDisableSuspendAlerts +import app.aaps.pump.omnipod.common.queue.command.CommandHandleTimeChange +import app.aaps.pump.omnipod.omnipod5.queue.command.CommandPairNewPod +import app.aaps.pump.omnipod.common.queue.command.CommandPlayTestBeep +import app.aaps.pump.omnipod.common.queue.command.CommandResumeDelivery +import app.aaps.pump.omnipod.common.queue.command.CommandSilenceAlerts +import app.aaps.pump.omnipod.common.queue.command.CommandSuspendDelivery +import app.aaps.pump.omnipod.common.queue.command.CommandUpdateAlertConfiguration +import app.aaps.pump.omnipod.common.util.mapProfileToBasalProgram +import app.aaps.pump.omnipod.omnipod5.history.O5History +import app.aaps.pump.omnipod.omnipod5.history.database.O5HistoryDatabase +import app.aaps.shared.tests.TestBaseWithProfile +import com.google.common.truth.Truth.assertThat +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Observable +import io.reactivex.rxjava3.core.Single +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource +import org.mockito.Mock +import org.mockito.kotlin.after +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.atLeast +import org.mockito.kotlin.eq +import org.mockito.kotlin.argThat +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.timeout +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.util.EnumSet + +/** + * Covers the safety-relevant gating logic and simple property surface of [O5PumpPlugin] - + * not exhaustive RxJava-flow coverage (no other pump plugin in this codebase unit-tests its + * full blocking-RxJava dosing flow either, see `OmnipodErosPumpPluginTest` + * for the closest precedent). Focus: the gates that must reject + * *before* any BLE command is sent (reservoir check, bolus-already-in-progress check, + * no-op temp-basal-cancel), the `isBusy()`/`isConnected()`/`isInitialized()` state + * transitions (the exact thing that caused the queue-deadlock bug during development), and + * `executeCustomCommand` routing. + */ +class O5PumpPluginTest : TestBaseWithProfile() { + + @Mock lateinit var bleManager: O5BleManager + @Mock lateinit var podStateManager: O5PodStateManager + @Mock lateinit var pumpSync: PumpSync + @Mock lateinit var commandQueue: CommandQueue + @Mock lateinit var bolusProgressData: BolusProgressData + @Mock lateinit var protectionCheck: ProtectionCheck + @Mock lateinit var blePreCheck: BlePreCheck + @Mock lateinit var history: O5History + @Mock lateinit var historyDatabase: O5HistoryDatabase + + private lateinit var plugin: O5PumpPlugin + + @BeforeEach + fun setup() { + plugin = O5PumpPlugin( + aapsLogger, rh, preferences, commandQueue, bleManager, podStateManager, history, pumpSync, + notificationManager, pumpEnactResultProvider, bolusProgressData, protectionCheck, blePreCheck, config, historyDatabase + ) + whenever(rh.gs(R.string.omnipod_5_error_not_enough_insulin)).thenReturn("Not enough insulin") + whenever(rh.gs(R.string.omnipod_5_error_bolus_already_in_progress)).thenReturn("Bolus already in progress") + whenever(rh.gs(R.string.omnipod_5_error_extended_bolus_not_supported)).thenReturn("Extended bolus not supported") + whenever(rh.gs(R.string.omnipod_common_error_unsupported_custom_command)).thenReturn("Unsupported custom command: %1\$s") + whenever(rh.gs(R.string.omnipod_5_error_no_active_profile)).thenReturn("No active profile") + whenever(rh.gs(R.string.omnipod_5_error_no_active_alerts)).thenReturn("No active alerts") + whenever(rh.gs(R.string.omnipod_5_error_unresolved_dose_pending)).thenReturn("Earlier dose unconfirmed") + whenever(rh.gs(R.string.omnipod_5_error_cancel_temp_basal_result_is_uncertain)).thenReturn("Temp basal cancellation is uncertain") + whenever(rh.gs(R.string.omnipod_5_error_bolus_delivery_status_uncertain)).thenReturn("Bolus delivery is uncertain") + whenever(rh.gs(R.string.omnipod_5_error_setting_basal_profile_might_have_failed)).thenReturn("Basal profile update is uncertain") + whenever(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description)).thenReturn("Pod Fault: %1\$03d %2\$s") + whenever(rh.gs(R.string.omnipod_common_pdm_ref)).thenReturn("Ref: %1\$s") + whenever(history.createRecord(any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(Single.just(1L)) + whenever(history.markSent(any())).thenReturn(Completable.complete()) + whenever(history.markSuccess(any())).thenReturn(Completable.complete()) + whenever(history.markSendingFailure(any())).thenReturn(Completable.complete()) + whenever(history.markFailure(any())).thenReturn(Completable.complete()) + whenever(history.setTotalAmountDelivered(any(), anyOrNull())).thenReturn(Completable.complete()) + } + + + @Test + fun `isBusy is false when no activation is running or started`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.NOT_STARTED) + whenever(bleManager.isActivationRunning).thenReturn(false) + + assertThat(plugin.isBusy()).isFalse() + } + + /** + * Pairing runs while the progress is still NOT_STARTED. If the pump was not busy then, the queue + * ran its commands and disconnected the pod in the middle of the pairing (Dash #5219). + */ + @Test + fun `isBusy is true while an activation step is running, even before any progress`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.NOT_STARTED) + whenever(bleManager.isActivationRunning).thenReturn(true) + + assertThat(plugin.isBusy()).isTrue() + } + + @Test + fun `disconnect does not close the link while an activation step is running`() { + whenever(bleManager.isActivationRunning).thenReturn(true) + + plugin.disconnect("Queue empty") + + verify(bleManager, never()).disconnect(any()) + } + + @Test + fun `disconnect closes the link when no activation is running`() { + whenever(bleManager.isActivationRunning).thenReturn(false) + + plugin.disconnect("Queue empty") + + verify(bleManager).disconnect(false) + } + + @Test + fun `isBusy is true while activation is in progress`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.GOT_POD_VERSION) + + assertThat(plugin.isBusy()).isTrue() + } + + @Test + fun `isBusy is false once activation is completed`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + + assertThat(plugin.isBusy()).isFalse() + } + + @Test + fun `isInitialized is true only when activation is fully completed`() { + whenever(podStateManager.isPodRunning).thenReturn(true) + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + assertThat(plugin.isInitialized()).isTrue() + + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.PRIME_COMPLETED) + assertThat(plugin.isInitialized()).isFalse() + } + + @Test + fun `isInitialized is false once an activated pod stops running - faulted or deactivated`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.isPodRunning).thenReturn(false) + + assertThat(plugin.isInitialized()).isFalse() + } + + @Test + fun `isConnected is true when unpaired - nothing to connect to yet`() { + whenever(podStateManager.ltk).thenReturn(null) + + assertThat(plugin.isConnected()).isTrue() + } + + @Test + fun `isConnected reflects bluetoothConnectionState once paired`() { + whenever(podStateManager.ltk).thenReturn(byteArrayOf(1)) + whenever(podStateManager.bluetoothConnectionState).thenReturn(O5PodStateManager.BluetoothConnectionState.CONNECTED) + assertThat(plugin.isConnected()).isTrue() + + whenever(podStateManager.bluetoothConnectionState).thenReturn(O5PodStateManager.BluetoothConnectionState.DISCONNECTED) + assertThat(plugin.isConnected()).isFalse() + } + + + @Test + fun `deliverTreatment rejects carbs`() { + assertThrows(IllegalArgumentException::class.java) { + runBlocking { plugin.deliverTreatment(DetailedBolusInfo().also { it.carbs = 5.0; it.insulin = 1.0 }) } + } + } + + @Test + fun `deliverTreatment rejects non-positive insulin`() { + assertThrows(IllegalArgumentException::class.java) { + runBlocking { plugin.deliverTreatment(DetailedBolusInfo().also { it.carbs = 0.0; it.insulin = 0.0 }) } + } + } + + @Test + fun `deliverTreatment rejects a bolus larger than the reservoir without sending any command`() { + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(20) + whenever(podStateManager.lastStatusResponseReceived).thenReturn(System.currentTimeMillis()) + whenever(podStateManager.lastBolusStartTime).thenReturn(null) + whenever(podStateManager.lastBolusRequestedUnits).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + + val result = runBlocking { + plugin.deliverTreatment(DetailedBolusInfo().also { it.carbs = 0.0; it.insulin = 5.0 }) + } + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + assertThat(result.bolusDelivered).isEqualTo(0.0) + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `deliverTreatment rejects when a bolus is already delivering without sending any command`() { + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(2000) + whenever(podStateManager.lastStatusResponseReceived).thenReturn(System.currentTimeMillis()) + whenever(podStateManager.lastBolusStartTime).thenReturn(null) + whenever(podStateManager.lastBolusRequestedUnits).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BOLUS_AND_BASAL_ACTIVE) + + val result = runBlocking { + plugin.deliverTreatment(DetailedBolusInfo().also { it.carbs = 0.0; it.insulin = 1.0 }) + } + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + + @Test + fun `setTempBasalPercent is unsupported`() { + assertThrows(IllegalStateException::class.java) { + runBlocking { plugin.setTempBasalPercent(80, 30, false, PumpSync.TemporaryBasalType.NORMAL) } + } + } + + @Test + fun `cancelTempBasal is a no-op when nothing is running - never touches the pod`() { + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + + val result = runBlocking { + whenever(pumpSync.expectedPumpState()).thenReturn( + PumpSync.PumpState(temporaryBasal = null, extendedBolus = null, bolus = null, profile = null, serialNumber = "") + ) + plugin.cancelTempBasal(false) + } + + assertThat(result.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + + @Test + fun `executeCustomCommand pairs a new pod for CommandPairNewPod`() { + whenever(bleManager.pairNewPod()).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandPairNewPod()) + + assertThat(result).isNotNull() + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).pairNewPod() + } + + @Test + fun `executeCustomCommand rejects an unrecognized custom command`() { + val unknown = object : CustomCommand { + override val statusDescription = "UNKNOWN" + } + + val result = plugin.executeCustomCommand(unknown) + + assertThat(result).isNotNull() + assertThat(result!!.success).isFalse() + assertThat(result.enacted).isFalse() + } + + @Test + fun `executeCustomCommand deactivates the pod for CommandDeactivatePod`() { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandDeactivatePod()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).sendCommand(any(), any()) + verify(bleManager).removeBond() + verify(podStateManager).reset() + } + + @Test + fun `executeCustomCommand silences alerts for CommandSilenceAlerts when there are active alerts`() { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.activeAlerts).thenReturn(java.util.EnumSet.of(AlertType.LOW_RESERVOIR)) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandSilenceAlerts()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).sendCommand(any(), any()) + } + + @Test + fun `executeCustomCommand rejects CommandSilenceAlerts when there are no active alerts`() { + whenever(podStateManager.activeAlerts).thenReturn(null) + + val result = plugin.executeCustomCommand(CommandSilenceAlerts()) + + assertThat(result!!.success).isFalse() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `executeCustomCommand suspends delivery for CommandSuspendDelivery`() { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandSuspendDelivery()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).sendCommand(any(), any()) + verify(podStateManager).deliverySuspended = true + } + + @Test + fun `executeCustomCommand plays a test beep for CommandPlayTestBeep`() { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandPlayTestBeep()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).sendCommand(any(), any()) + } + + @Test + fun `executeCustomCommand for CommandResumeDelivery fails cleanly when there is no active profile`() { + runBlocking { + whenever(pumpSync.expectedPumpState()).thenReturn( + PumpSync.PumpState(temporaryBasal = null, extendedBolus = null, bolus = null, profile = null, serialNumber = "") + ) + + val result = plugin.executeCustomCommand(CommandResumeDelivery()) + + assertThat(result!!.success).isFalse() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + } + + @Test + fun `executeCustomCommand for CommandHandleTimeChange fails cleanly when there is no active profile`() { + runBlocking { + whenever(pumpSync.expectedPumpState()).thenReturn( + PumpSync.PumpState(temporaryBasal = null, extendedBolus = null, bolus = null, profile = null, serialNumber = "") + ) + + val result = plugin.executeCustomCommand(CommandHandleTimeChange(true)) + + assertThat(result!!.success).isFalse() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + } + + + @Test + fun `manufacturer and model are fixed and time handling supports an inactive pod`() { + assertThat(plugin.manufacturer()).isEqualTo(ManufacturerType.Insulet) + assertThat(plugin.model()).isEqualTo(PumpType.OMNIPOD_5) + assertThat(plugin.canHandleDST()).isTrue() + assertThat(plugin.isFakingTempsByExtendedBoluses).isFalse() + } + + @Test + fun `an active pod needs a known offset before disabling the old DST guard`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.isPodRunning).thenReturn(true) + whenever(podStateManager.timeZoneOffset).thenReturn(null) + assertThat(plugin.canHandleDST()).isFalse() + whenever(podStateManager.timeZoneOffset).thenReturn(3600000) + assertThat(plugin.canHandleDST()).isTrue() + } + + @Test + fun `serialNumber falls back to a placeholder before pairing`() { + whenever(podStateManager.podId).thenReturn(null) + assertThat(plugin.serialNumber()).isEqualTo("O5-unpaired") + + whenever(podStateManager.podId).thenReturn(4242L) + assertThat(plugin.serialNumber()).isEqualTo("4242") + } + + @Test + fun `extended bolus is unsupported`() { + val deliver = runBlocking { plugin.setExtendedBolus(1.0, 60) } + assertThat(deliver.success).isFalse() + + val cancel = runBlocking { plugin.cancelExtendedBolus() } + assertThat(cancel.success).isFalse() + } + + + @Test + fun `isThisProfileSet is true before pairing - prevents premature basal-set attempts`() { + whenever(podStateManager.ltk).thenReturn(null) + + assertThat(plugin.isThisProfileSet(mock())).isTrue() + } + + @Test + fun `isThisProfileSet is false while delivery is suspended - a set is genuinely needed`() { + whenever(podStateManager.ltk).thenReturn(byteArrayOf(1)) + whenever(podStateManager.deliverySuspended).thenReturn(true) + + assertThat(plugin.isThisProfileSet(mock())).isFalse() + } + + @Test + fun `delivered basal reports the confirmed rounded program hour by hour`() { + val profile = mock() + whenever(profile.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 0.42), Profile.ProfileValue(6 * 3600, 0.43))) + val program = mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5) + whenever(podStateManager.isActivationCompleted).thenReturn(true) + whenever(podStateManager.basalProgram).thenReturn(program) + + val delivered = plugin.deliveredBasal()!! + + assertThat(delivered.map { it.timeAsSeconds }).containsExactlyElementsIn((0..23).map { it * 3600 }).inOrder() + assertThat(delivered.map { it.value }).containsExactlyElementsIn((0..23).map { if (it < 6) 0.40 else 0.45 }).inOrder() + } + + @Test + fun `delivered basal averages half hour rates within each hour`() { + val profile = mock() + whenever(profile.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 0.40), Profile.ProfileValue(1800, 0.45))) + val program = mapProfileToBasalProgram(profile, PumpType.OMNIPOD_5) + whenever(podStateManager.isActivationCompleted).thenReturn(true) + whenever(podStateManager.basalProgram).thenReturn(program) + + assertThat(plugin.deliveredBasal()!!.map { it.value }) + .containsExactlyElementsIn(listOf(0.425) + List(23) { 0.45 }).inOrder() + } + + @Test + fun `delivered basal is unknown before activation completes`() { + whenever(podStateManager.isActivationCompleted).thenReturn(false) + whenever(podStateManager.basalProgram).thenReturn(BasalProgram(listOf(BasalProgram.Segment(0, 48, 100)))) + + assertThat(plugin.deliveredBasal()).isNull() + } + + @Test + fun `delivered basal is unknown before a program is confirmed`() { + whenever(podStateManager.isActivationCompleted).thenReturn(true) + whenever(podStateManager.basalProgram).thenReturn(null) + + assertThat(plugin.deliveredBasal()).isNull() + } + + @Test + fun `database reset clears the O5 history through OwnDatabasePlugin`() { + val databasePlugin: OwnDatabasePlugin = plugin + + databasePlugin.clearAllTables() + + verify(historyDatabase).clearAllTables() + } + + + @Test + fun `executeCustomCommand rejects CommandUpdateAlertConfiguration when settings already match`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.syncedAlertSettings).thenReturn( + O5PodStateManager.SyncedAlertSettings( + expirationReminderEnabled = false, expirationReminderHours = 0, + expirationAlarmEnabled = false, expirationAlarmHours = 0, + lowReservoirAlertEnabled = false, lowReservoirAlertUnits = 0 + ) + ) + + val result = plugin.executeCustomCommand(CommandUpdateAlertConfiguration()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `executeCustomCommand rejects CommandUpdateAlertConfiguration before activation completes`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.PRIME_COMPLETED) + + val result = plugin.executeCustomCommand(CommandUpdateAlertConfiguration()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `executeCustomCommand pushes CommandUpdateAlertConfiguration when settings changed and records the sync`() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.syncedAlertSettings).thenReturn(null) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.podLifeInHours).thenReturn(80.toShort()) + whenever(podStateManager.minutesSinceActivation).thenReturn(60.toShort()) + whenever(podStateManager.lastStatusResponseReceived).thenReturn(System.currentTimeMillis()) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandUpdateAlertConfiguration()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).sendCommand(any(), any()) + verify(podStateManager).syncedAlertSettings = any() + } + + @Test + fun `executeCustomCommand rejects CommandDisableSuspendAlerts when nothing is armed`() { + whenever(podStateManager.suspendAlertsEnabled).thenReturn(false) + + val result = plugin.executeCustomCommand(CommandDisableSuspendAlerts(rh)) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `executeCustomCommand silences the pod for CommandDisableSuspendAlerts when armed`() { + whenever(podStateManager.suspendAlertsEnabled).thenReturn(true) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.executeCustomCommand(CommandDisableSuspendAlerts(rh)) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isTrue() + verify(bleManager).sendCommand(any(), any()) + verify(podStateManager).suspendAlertsEnabled = false + } + + @Test + fun `executeCustomCommand rejects CommandDeliverBasalCorrection when drift compensation is disabled - the default`() { + val result = plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `zero temp basal allows a correction within 5 minutes of a bolus - same as Dash`() { + stubBasalCorrectionDrift(0.0) + whenever(podStateManager.lastBolusStartTime).thenReturn(System.currentTimeMillis()) + whenever(bleManager.sendCommand(argThat { this is ProgramBolusCommand }, any())) + .thenReturn(Observable.error(IllegalStateException("Correction command not sent"))) + + plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + + verify(bleManager).sendCommand(argThat { this is ProgramBolusCommand }, any()) + } + + @Test + fun `zero temp basal blocks a correction more than 5 minutes after a bolus`() { + stubBasalCorrectionDrift(0.0) + whenever(podStateManager.lastBolusStartTime).thenReturn(System.currentTimeMillis() - 6 * 60 * 1000L) + + val result = plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + + assertThat(result!!.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + verify(podStateManager, never()).lastBasalCorrectionTime = anyOrNull() + } + + @Test + fun `zero temp basal blocks a correction without a recent bolus`() { + stubBasalCorrectionDrift(0.0) + + val result = plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + + assertThat(result!!.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + @Test + fun `replacing a temp basal with zero queues no correction before or after the replacement`() = runBlocking { + stubBasalCorrectionDrift(0.55) + stubStopTempBasal() + + val result = plugin.setTempBasalAbsolute(0.0, 30, false, PumpSync.TemporaryBasalType.NORMAL) + + assertThat(result.success).isTrue() + assertThat(result.enacted).isTrue() + val commands = inOrder(bleManager) + commands.verify(bleManager).sendCommand(argThat { this is StopDeliveryCommand }, any()) + commands.verify(bleManager).sendCommand(argThat { this is ProgramTempBasalCommand }, any()) + commands.verifyNoMoreInteractions() + verify(commandQueue, after(500).never()).customCommand(any()) + verify(podStateManager, never()).lastBasalCorrectionTime = anyOrNull() + } + + @Test + fun `replacing a temp basal queues a correction only after the positive replacement`() = runBlocking { + stubBasalCorrectionDrift(0.55) + stubStopTempBasal() + + val result = plugin.setTempBasalAbsolute(0.4, 30, false, PumpSync.TemporaryBasalType.NORMAL) + + assertThat(result.success).isTrue() + // The correction is queued from pluginScope, so wait for it before checking the order + verify(commandQueue, timeout(2_000)).customCommand(argThat { this is CommandDeliverBasalCorrection }) + val commands = inOrder(bleManager, commandQueue) + commands.verify(bleManager).sendCommand(argThat { this is StopDeliveryCommand }, any()) + commands.verify(bleManager).sendCommand(argThat { this is ProgramTempBasalCommand }, any()) + commands.verify(commandQueue).customCommand(argThat { this is CommandDeliverBasalCorrection }) + verify(bleManager, never()).sendCommand(argThat { this is ProgramBolusCommand }, any()) + verify(podStateManager, never()).lastBasalCorrectionTime = anyOrNull() + } + + @Test + fun `a correction is not queued twice`() = runBlocking { + stubBasalCorrectionDrift(0.55) + stubStopTempBasal() + whenever(commandQueue.isCustomCommandInQueue(CommandDeliverBasalCorrection::class)).thenReturn(true) + + val result = plugin.setTempBasalAbsolute(0.4, 30, false, PumpSync.TemporaryBasalType.NORMAL) + + assertThat(result.success).isTrue() + verify(commandQueue, after(500).never()).customCommand(any()) + } + + @Test + fun `a failed zero temp basal replacement does not queue a correction`() = runBlocking { + stubBasalCorrectionDrift(0.55) + stubStopTempBasal() + whenever(bleManager.sendCommand(argThat { this is ProgramTempBasalCommand }, any())) + .thenReturn(Observable.error(IllegalStateException("Temp basal command not sent"))) + whenever(rh.gs(R.string.omnipod_5_error_setting_temp_basal_might_have_failed)).thenReturn("Temp basal failed") + + val result = plugin.setTempBasalAbsolute(0.0, 30, false, PumpSync.TemporaryBasalType.NORMAL) + + assertThat(result.success).isFalse() + verify(bleManager, never()).sendCommand(argThat { this is ProgramBolusCommand }, any()) + verify(commandQueue, after(500).never()).customCommand(any()) + verify(podStateManager, never()).lastBasalCorrectionTime = anyOrNull() + } + + @Test + fun `a standalone temp basal cancel queues a correction after the cancel`() = runBlocking { + stubBasalCorrectionDrift(0.0) + stubStopTempBasal() + + val result = plugin.cancelTempBasal(false) + + assertThat(result.success).isTrue() + // The correction is queued from pluginScope, so wait for it before checking the order + verify(commandQueue, timeout(2_000)).customCommand(argThat { this is CommandDeliverBasalCorrection }) + val commands = inOrder(bleManager, commandQueue) + commands.verify(bleManager).sendCommand(argThat { this is StopDeliveryCommand }, any()) + commands.verify(commandQueue).customCommand(argThat { this is CommandDeliverBasalCorrection }) + verify(bleManager, never()).sendCommand(argThat { this is ProgramBolusCommand }, any()) + } + + @Test + fun `a pending dose blocks the drift reset and the correction`() { + stubBasalCorrectionDrift(0.55) + // 3 bolus pulses are not counted yet, so basal looks 0.15 U too high + whenever(podStateManager.totalPulsesDelivered).thenReturn(23) + whenever(podStateManager.basalExpected).thenReturn(0.0) + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 4)) + + val result = plugin.executeCustomCommand(CommandDeliverBasalCorrection()) + + assertThat(result!!.success).isFalse() + assertThat(result.enacted).isFalse() + verify(podStateManager, never()).basalExpected = any() + verify(bleManager, never()).sendCommand(any(), any()) + verify(podStateManager, never()).lastBasalCorrectionTime = anyOrNull() + } + + private fun stubBasalCorrectionDrift(initialRate: Double) { + plugin.scope = CoroutineScope(Dispatchers.Unconfined) + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.totalPulsesDelivered).thenReturn(20) + whenever(podStateManager.cumulativeBolusPulsesDelivered).thenReturn(20) + whenever(podStateManager.basalExpected).thenReturn(0.05) + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(1000) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.TEMP_BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + var activeRate: Double? = initialRate + whenever(podStateManager.activeTempBasalRate).thenAnswer { activeRate } + doAnswer { + activeRate = it.getArgument(0) + null + }.whenever(podStateManager).activeTempBasalRate = anyOrNull() + stubAcceptedDoseCommands() + } + + private fun stubAcceptedDoseCommands() { + var pending: O5PodStateManager.PendingDoseCommand? = null + whenever(podStateManager.pendingDoseCommand).thenAnswer { pending } + doAnswer { + pending = it.getArgument(0) + null + }.whenever(podStateManager).pendingDoseCommand = anyOrNull() + whenever(bleManager.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + if (command is ProgramBasalCommand || command is ProgramTempBasalCommand) { + pending = pending?.copy(confirmedByStatus = true) + whenever(podStateManager.deliveryStatus).thenReturn( + if (command is ProgramBasalCommand) DeliveryStatus.BASAL_ACTIVE else DeliveryStatus.TEMP_BASAL_ACTIVE + ) + } + Observable.empty() + } + } + + + @Test + fun `an unread fault warns the user but leaves the announcement pending`() { + whenever(podStateManager.alarmSynced).thenReturn(false) + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.alarmType).thenReturn(null) + whenever(podStateManager.podStatus).thenReturn(PodStatus.ALARM) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(commandQueue.isCustomCommandInQueue(CommandDeactivatePod::class)).thenReturn(false) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.error(RuntimeException("pod unreachable"))) + + runBlocking { + plugin.checkPodFault() + + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_POD_FAULT), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + verify(pumpSync, never()).insertAnnouncement(any(), anyOrNull(), any(), any()) + } + verify(podStateManager, never()).alarmSynced = true + } + + @Test + fun `an unread fault is saved with its code and reference on a later status check`() = runBlocking { + val alarm = AlarmType.ALARM_OCCLUDED + val fault = "Pod Fault: 020 $alarm" + val ref = "17-00003-02251-020" + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.podStatus).thenReturn(PodStatus.ALARM) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState()) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.error(RuntimeException("pod unreachable"))) + + plugin.checkPodKaput() + + verify(pumpSync, never()).insertAnnouncement(any(), anyOrNull(), any(), any()) + verify(podStateManager, never()).alarmSynced = true + + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(podStateManager.pdmRef).thenReturn(ref) + whenever(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, alarm.code, alarm.toString())).thenReturn(fault) + whenever(rh.gs(R.string.omnipod_common_pdm_ref, ref)).thenReturn("Ref: $ref") + + plugin.checkPodKaput() + + verify(pumpSync).insertAnnouncement(eq("$fault\nRef: $ref"), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + verify(podStateManager).alarmSynced = true + } + + @Test + fun `status polling saves a stopped pod fault once through stopped-pod handling`() = runBlocking { + val alarm = AlarmType.ALARM_OCCLUDED + val fault = "Pod Fault: 020 $alarm" + var alarmSynced = false + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(podStateManager.podActivatedAt).thenReturn(1L) + whenever(podStateManager.alarmSynced).thenAnswer { alarmSynced } + doAnswer { + alarmSynced = it.getArgument(0) + null + }.whenever(podStateManager).alarmSynced = any() + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState()) + whenever(bleManager.connect()).thenReturn(Observable.empty()) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + whenever(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, alarm.code, alarm.toString())).thenReturn(fault) + + plugin.getPumpStatus("Fault") + plugin.getPumpStatus("Fault") + + val order = inOrder(pumpSync, podStateManager) + order.verify(pumpSync).insertAnnouncement(eq(fault), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + order.verify(podStateManager).alarmSynced = true + verify(pumpSync, times(1)).insertAnnouncement(any(), anyOrNull(), any(), any()) + } + + @Test + fun `a rejected temp basal cancel returns the fault and reference without throwing`() = runBlocking { + val description = stubExpiredPodResponse() + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.TEMP_BASAL_ACTIVE) + + val result = plugin.cancelTempBasal(false) + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + assertThat(result.comment).isEqualTo(description) + verify(pumpSync).insertAnnouncement(eq(description), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + verify(podStateManager).alarmSynced = true + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_POD_FAULT), eq(description), level = any(), validMinutes = any(), + sound = eq(AlarmSound.BOLUS_ERROR), actions = any(), validityCheck = anyOrNull() + ) + } + + @Test + fun `a rejected temp basal start returns and saves the fault details`() = runBlocking { + val description = stubExpiredPodResponse() + + val result = plugin.setTempBasalAbsolute(0.2, 30, false, PumpSync.TemporaryBasalType.NORMAL) + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + assertThat(result.comment).isEqualTo(description) + verify(pumpSync).insertAnnouncement(eq(description), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + } + + @Test + fun `a failed status poll still saves the returned alarm and records zero delivery`() = runBlocking { + val description = stubExpiredPodResponse() + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(bleManager.connect()).thenReturn(Observable.empty()) + + plugin.getPumpStatus("Fault") + plugin.getPumpStatus("Fault") + + verify(pumpSync, times(1)).insertAnnouncement(eq(description), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + verify(podStateManager, times(1)).alarmSynced = true + verify(pumpSync, times(2)).syncTemporaryBasalWithPumpId( + any(), argThat { cU == 0.0 }, any(), eq(true), eq(PumpSync.TemporaryBasalType.PUMP_SUSPEND), + any(), eq(PumpType.OMNIPOD_5), eq("9999") + ) + } + + @ParameterizedTest + @ValueSource(strings = ["deactivate", "suspend", "silence", "beep"]) + fun `a rejected custom command returns and saves the fault details`(command: String) = runBlocking { + val description = stubExpiredPodResponse() + whenever(podStateManager.activeAlerts).thenReturn(EnumSet.of(AlertType.LOW_RESERVOIR)) + val customCommand = when (command) { + "deactivate" -> CommandDeactivatePod() + "suspend" -> CommandSuspendDelivery() + "silence" -> CommandSilenceAlerts() + "beep" -> CommandPlayTestBeep() + else -> error("Unknown test command: $command") + } + + val result = plugin.executeCustomCommand(customCommand) + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + assertThat(result.comment).isEqualTo(description) + verify(pumpSync).insertAnnouncement(eq(description), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + verify(podStateManager, never()).reset() + verify(bleManager, never()).removeBond() + } + + @Test + fun `a failed fault write does not escape the command error handler or lose its description`() = runBlocking { + val description = stubExpiredPodResponse() + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.TEMP_BASAL_ACTIVE) + whenever(pumpSync.insertAnnouncement(any(), anyOrNull(), any(), any())) + .thenThrow(IllegalStateException("Database unavailable")) + .thenAnswer { Unit } + + val first = plugin.cancelTempBasal(false) + + assertThat(first.success).isFalse() + assertThat(first.comment).isEqualTo(description) + verify(podStateManager, never()).alarmSynced = true + + val retry = plugin.cancelTempBasal(false) + + assertThat(retry.success).isFalse() + assertThat(retry.comment).isEqualTo(description) + verify(pumpSync, times(2)).insertAnnouncement(eq(description), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + verify(podStateManager).alarmSynced = true + } + + @Test + fun `a connection error without a pod fault returns a nonempty cancellation message`() = runBlocking { + whenever(podStateManager.podId).thenReturn(9999L) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.TEMP_BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.error(MessageIOException("No response"))) + + val result = plugin.cancelTempBasal(false) + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + assertThat(result.comment).isEqualTo("Temp basal cancellation is uncertain") + verify(pumpSync, never()).insertAnnouncement(any(), anyOrNull(), any(), any()) + verify(podStateManager, never()).alarmSynced = true + } + + private suspend fun stubExpiredPodResponse(): String { + val alarm = AlarmType.ALARM_PUMP_EXPIRED + val fault = "Pod Fault: 028 $alarm" + val ref = "16-00000-00000-028" + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState()) + whenever(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, alarm.code, alarm.toString())).thenReturn(fault) + whenever(rh.gs(R.string.omnipod_common_pdm_ref, ref)).thenReturn("Ref: $ref") + var alarmSynced = false + whenever(podStateManager.alarmSynced).thenAnswer { alarmSynced } + doAnswer { + alarmSynced = it.getArgument(0) + null + }.whenever(podStateManager).alarmSynced = any() + whenever(bleManager.sendCommand(any(), any())).thenAnswer { + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(podStateManager.pdmRef).thenReturn(ref) + whenever(podStateManager.podStatus).thenReturn(PodStatus.ALARM) + whenever(podStateManager.isPodKaput).thenReturn(true) + Observable.error(MessageIOException("Pod reported a fault")) + } + return "$fault\nRef: $ref" + } + + @Test + fun `a failed announcement write leaves the fault pending for retry`() = runBlocking { + whenever(podStateManager.alarmType).thenReturn(AlarmType.ALARM_OCCLUDED) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.insertAnnouncement(any(), anyOrNull(), any(), any())) + .thenThrow(IllegalStateException("Database unavailable")) + .thenAnswer { Unit } + + assertThrows(IllegalStateException::class.java) { + runBlocking { plugin.checkPodFault() } + } + + verify(podStateManager, never()).alarmSynced = true + + plugin.checkPodFault() + + verify(pumpSync, times(2)).insertAnnouncement(any(), anyOrNull(), any(), any()) + verify(podStateManager).alarmSynced = true + } + + @Test + fun `activation timeout is saved without a fault code`() = runBlocking { + val description = "Pod activation time exceeded" + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.isPodActivationTimeExceeded).thenReturn(true) + whenever(podStateManager.podStatus).thenReturn(PodStatus.LUMP_OF_COAL) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState()) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + whenever(rh.gs(R.string.omnipod_common_error_pod_fault_activation_time_exceeded)).thenReturn(description) + + plugin.checkPodKaput() + + verify(pumpSync).insertAnnouncement(eq(description), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + verify(podStateManager).alarmSynced = true + } + + @Test + fun `a healthy pod is not reported`() { + whenever(podStateManager.alarmSynced).thenReturn(false) + whenever(podStateManager.isPodKaput).thenReturn(false) + whenever(podStateManager.alarmType).thenReturn(null) + + runBlocking { plugin.checkPodFault() } + + verify(notificationManager, never()).post( + any(), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + verify(podStateManager, never()).alarmSynced = true + } + + @Test + fun `checkPodFault posts a notification and records an announcement on a new alarm`() { + whenever(podStateManager.alarmSynced).thenReturn(false) + whenever(podStateManager.alarmType).thenReturn(AlarmType.ALARM_OCCLUDED) + whenever(commandQueue.isCustomCommandInQueue(CommandDeactivatePod::class)).thenReturn(false) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.checkPodFault() + + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_POD_FAULT), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + verify(pumpSync).insertAnnouncement(any(), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + } + verify(podStateManager).alarmSynced = true + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `fault notification and announcement include the unsigned code and available reference`(hasRef: Boolean) = runBlocking { + val alarm = AlarmType.ALARM_SYNC_WITHOUT_CLOSED_LOOP + val fault = "Pod Fault: 152 $alarm" + val ref = "19-00006-02251-152" + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(podStateManager.pdmRef).thenReturn(ref.takeIf { hasRef }) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, 152, alarm.toString())).thenReturn(fault) + whenever(rh.gs(R.string.omnipod_common_pdm_ref, ref)).thenReturn("Ref: $ref") + + plugin.checkPodFault() + + val expected = if (hasRef) "$fault\nRef: $ref" else fault + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_POD_FAULT), eq(expected), level = any(), validMinutes = any(), + sound = eq(AlarmSound.BOLUS_ERROR), actions = any(), validityCheck = anyOrNull() + ) + verify(pumpSync).insertAnnouncement(eq(expected), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + } + + @Test + fun `checkPodFault is a no-op once the current alarm is already synced - not re-posted on every poll`() { + whenever(podStateManager.alarmSynced).thenReturn(true) + + runBlocking { plugin.checkPodFault() } + + verify(notificationManager, never()).post( + any(), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + } + + @Test + fun `checkPodFault is a no-op when there is no alarm`() { + whenever(podStateManager.alarmSynced).thenReturn(false) + whenever(podStateManager.alarmType).thenReturn(null) + + runBlocking { plugin.checkPodFault() } + + verify(notificationManager, never()).post( + any(), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + verify(podStateManager, never()).alarmSynced = any() + } + + @Test + fun `checkPodFault skips the notification but still records the announcement when deactivation is already queued`() { + whenever(podStateManager.alarmSynced).thenReturn(false) + whenever(podStateManager.alarmType).thenReturn(AlarmType.ALARM_OCCLUDED) + whenever(commandQueue.isCustomCommandInQueue(CommandDeactivatePod::class)).thenReturn(true) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.checkPodFault() + + verify(notificationManager, never()).post( + any(), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + verify(pumpSync).insertAnnouncement(any(), any(), eq(PumpType.OMNIPOD_5), eq("9999")) + } + verify(podStateManager).alarmSynced = true + } + + + private fun pendingBolus(sequenceNumber: Short?) = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 3.0, + bolusType = BS.Type.NORMAL, + startedAt = 1_000L, + sequenceNumber = sequenceNumber + ) + + @Test + fun `an uncertain bolus the pod never received records no insulin`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 4)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync, never()).syncBolusWithPumpId( + any(), any(), any(), any(), any(), any() + ) + } + verify(podStateManager).pendingDoseCommand = null + } + + @Test + fun `an uncertain bolus the pod never received corrects conservative accounting to zero`() { + whenever(podStateManager.pendingDoseCommand).thenReturn( + pendingBolus(sequenceNumber = 4).copy(bolusRecordExpected = true) + ) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync).syncBolusWithPumpId( + eq(1_000L), + argThat { cU == 0.0 }, + eq(BS.Type.NORMAL), + eq(1_000L), + eq(PumpType.OMNIPOD_5), + eq("9999") + ) + } + verify(podStateManager).pendingDoseCommand = null + } + + @Test + fun `an uncertain bolus the pod did receive is finalized`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 9)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(0) + whenever(podStateManager.lastBolusDeliveredUnits).thenReturn(null) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync).syncBolusWithPumpId( + any(), any(), any(), any(), eq(PumpType.OMNIPOD_5), eq("9999") + ) + } + verify(podStateManager).completeBolus(1_000L, 3.0, 3.0, 60) + } + + @Test + fun `a confirmed partial bolus updates accounting and cumulative pulses`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 9)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(40) + whenever(podStateManager.lastBolusDeliveredUnits).thenReturn(null) + whenever(podStateManager.cumulativeBolusPulsesDelivered).thenReturn(10) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync).syncBolusWithPumpId( + eq(1_000L), + argThat { cU == 1.0 }, + eq(BS.Type.NORMAL), + eq(1_000L), + eq(PumpType.OMNIPOD_5), + eq("9999") + ) + } + verify(podStateManager).completeBolus(1_000L, 3.0, 1.0, 20) + } + + @Test + fun `a confirmed bolus remains unresolved when remaining pulses are unavailable`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 9)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(null) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync, never()).syncBolusWithPumpId( + any(), any(), any(), any(), any(), any() + ) + } + verify(podStateManager, never()).pendingDoseCommand = null + } + + @Test + fun `a still-running bolus is confirmed by delivery status even when the sequence disagrees`() { + val pending = pendingBolus(sequenceNumber = 4) + whenever(podStateManager.pendingDoseCommand).thenReturn(pending) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BOLUS_AND_BASAL_ACTIVE) + + runBlocking { plugin.reconcilePendingDose() } + + verify(podStateManager).pendingDoseCommand = pending.copy(confirmedByStatus = true) + } + + @Test + fun `sequence numbers are compared as 4 bits so a wrapped counter still matches`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 0x1F)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(0x0F) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(0) + whenever(podStateManager.lastBolusDeliveredUnits).thenReturn(null) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync).syncBolusWithPumpId( + any(), any(), any(), any(), eq(PumpType.OMNIPOD_5), eq("9999") + ) + } + } + + @Test + fun `a pending dose restored without a sequence number stays unknown when inactive`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = null)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(0) + whenever(podStateManager.lastBolusDeliveredUnits).thenReturn(null) + whenever(podStateManager.podId).thenReturn(9999L) + + runBlocking { + plugin.reconcilePendingDose() + + verify(pumpSync, never()).syncBolusWithPumpId( + any(), any(), any(), any(), eq(PumpType.OMNIPOD_5), eq("9999") + ) + } + verify(podStateManager, never()).pendingDoseCommand = null + } + + @Test + fun `an uncertain temp basal the pod never received is dropped without activating one`() { + whenever(podStateManager.pendingDoseCommand).thenReturn( + O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_START, + requestedRate = 0.5, + requestedDurationMinutes = 30, + startedAt = 1_000L, + sequenceNumber = 4 + ) + ) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + + runBlocking { plugin.reconcilePendingDose() } + + verify(podStateManager).pendingDoseCommand = null + } + + @Test + fun `reconcile is a no-op when nothing is pending`() { + whenever(podStateManager.pendingDoseCommand).thenReturn(null) + + runBlocking { plugin.reconcilePendingDose() } + + verify(podStateManager, never()).pendingDoseCommand = anyOrNull() + } + + + @Test + fun `a temp basal is refused while an earlier dose stays unresolved`() { + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 4)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BOLUS_AND_BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = runBlocking { + plugin.setTempBasalAbsolute(1.0, 30, false, PumpSync.TemporaryBasalType.NORMAL) + } + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + } + + @Test + fun `a bolus is refused while an earlier dose stays unresolved and no insulin is reported`() { + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(pendingBolus(sequenceNumber = 4)) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BOLUS_AND_BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = runBlocking { + plugin.deliverTreatment(DetailedBolusInfo().also { it.insulin = 2.0; it.carbs = 0.0 }) + } + + assertThat(result.success).isFalse() + assertThat(result.enacted).isFalse() + assertThat(result.bolusDelivered).isEqualTo(0.0) + } + + @Test + fun `the guard lets a command through once the status read settles the earlier dose`() { + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand) + .thenReturn(pendingBolus(sequenceNumber = 9)) + .thenReturn(null) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(9) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BOLUS_AND_BASAL_ACTIVE) + whenever(bleManager.connect()).thenReturn(Observable.empty()) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + runBlocking { plugin.setTempBasalAbsolute(1.0, 30, false, PumpSync.TemporaryBasalType.NORMAL) } + + verify(bleManager, atLeast(2)).sendCommand(any(), any()) + } + + @Test + fun `nothing pending means no extra status read before a dose`() { + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + runBlocking { plugin.setTempBasalAbsolute(1.0, 30, false, PumpSync.TemporaryBasalType.NORMAL) } + + verify(bleManager, times(1)).sendCommand(any(), any()) + } + + @Test + fun `a canceled bolus reconnects and re-sends the stop command when the link dropped mid-delivery`() { + var pending: O5PodStateManager.PendingDoseCommand? = null + whenever(podStateManager.pendingDoseCommand).thenAnswer { pending } + doAnswer { + pending = it.getArgument(0) + null + }.whenever(podStateManager).pendingDoseCommand = anyOrNull() + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(0) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(0) + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(2000) + whenever(podStateManager.lastStatusResponseReceived).thenReturn(System.currentTimeMillis()) + whenever(podStateManager.lastBolusStartTime).thenReturn(null) + whenever(podStateManager.lastBolusRequestedUnits).thenReturn(null) + whenever(podStateManager.podId).thenReturn(12345L) + // Not bolus-active: lets the initial gate pass and the retry loop settle after one cancel. + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + // Reconnect is a no-op success - simulates the link being brought back up before the stop. + whenever(bleManager.connect()).thenReturn(Observable.empty()) + // The user presses cancel while the bolus program command is in flight. + whenever(bleManager.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + if (command is ProgramBolusCommand) { + pending = pending?.copy(confirmedByStatus = true) + } + plugin.stopBolusDelivering() + Observable.just(PodEvent.CommandSent(command)) + } + + val result = runBlocking { + plugin.deliverTreatment(DetailedBolusInfo().also { it.carbs = 0.0; it.insulin = 0.5 }) + } + + assertThat(result.success).isTrue() + // The stop must reach the pod, and only after a (re)connect. + verify(bleManager).connect() + verify(bleManager).sendCommand(argThat { this is StopDeliveryCommand }, any()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `bolus status and cancellation checks save a newly reported fault`(cancel: Boolean) = runBlocking { + var pending: O5PodStateManager.PendingDoseCommand? = null + var faulted = false + var alarm: AlarmType? = null + val fault = "Pod Fault: 020 ALARM_OCCLUDED" + val ref = "17-00003-02251-020" + whenever(podStateManager.pendingDoseCommand).thenAnswer { pending } + doAnswer { + pending = it.getArgument(0) + null + }.whenever(podStateManager).pendingDoseCommand = anyOrNull() + whenever(podStateManager.isPodKaput).thenAnswer { faulted } + whenever(podStateManager.alarmType).thenAnswer { alarm } + whenever(podStateManager.pdmRef).thenAnswer { ref.takeIf { alarm != null } } + whenever(podStateManager.podStatus).thenAnswer { if (faulted) PodStatus.ALARM else PodStatus.RUNNING_ABOVE_MIN_VOLUME } + whenever(podStateManager.deliveryStatus).thenAnswer { if (faulted) DeliveryStatus.SUSPENDED else DeliveryStatus.BASAL_ACTIVE } + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(0) + whenever(podStateManager.bolusPulsesRemaining).thenReturn(0) + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(2000) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState()) + whenever(bleManager.connect()).thenReturn(Observable.empty()) + whenever(rh.gs(R.string.omnipod_common_pod_status_pod_fault_description, AlarmType.ALARM_OCCLUDED.code, AlarmType.ALARM_OCCLUDED.toString())) + .thenReturn(fault) + whenever(rh.gs(R.string.omnipod_common_pdm_ref, ref)).thenReturn("Ref: $ref") + whenever(bleManager.sendCommand(any(), any())).thenAnswer { + val command = it.getArgument(0) + val alarmResponse = it.arguments[1] == AlarmStatusResponse::class + Observable.defer { + when { + command is ProgramBolusCommand -> { + pending = pending?.copy(confirmedByStatus = true) + if (cancel) plugin.stopBolusDelivering() + } + alarmResponse -> alarm = AlarmType.ALARM_OCCLUDED + command is GetStatusCommand || command is StopDeliveryCommand -> faulted = true + } + if (command is ProgramBolusCommand) Observable.just(PodEvent.CommandSent(command)) + else Observable.empty() + } + } + + val result = plugin.deliverTreatment(DetailedBolusInfo().also { it.carbs = 0.0; it.insulin = 0.05 }) + + assertThat(result.success).isTrue() + assertThat(result.bolusDelivered).isEqualTo(0.05) + verifyZeroTempBasalSynced("12345") + verify(pumpSync).insertAnnouncement(eq("$fault\nRef: $ref"), any(), eq(PumpType.OMNIPOD_5), eq("12345")) + verify(podStateManager).alarmSynced = true + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_POD_FAULT), eq("$fault\nRef: $ref"), level = any(), validMinutes = any(), + sound = eq(AlarmSound.BOLUS_ERROR), actions = any(), validityCheck = anyOrNull() + ) + if (cancel) verify(bleManager).sendCommand(argThat { this is StopDeliveryCommand }, any()) + } + + private fun pumpState(temporaryBasal: PumpSync.PumpState.TemporaryBasal? = null, serial: String = "", profile: PumpProfile? = null) = + PumpSync.PumpState(temporaryBasal = temporaryBasal, extendedBolus = null, bolus = null, profile = profile, serialNumber = serial) + + private fun zeroTempBasal(type: PumpSync.TemporaryBasalType) = PumpSync.PumpState.TemporaryBasal( + timestamp = 1_000L, duration = 60_000L, rate = 0.0, isAbsolute = true, type = type, id = 1L, pumpId = 1L + ) + + private suspend fun verifyZeroTempBasalSynced(serial: String) { + verify(pumpSync).syncTemporaryBasalWithPumpId( + any(), argThat { this.cU == 0.0 }, any(), eq(true), eq(PumpSync.TemporaryBasalType.PUMP_SUSPEND), + any(), eq(PumpType.OMNIPOD_5), eq(serial) + ) + } + + private suspend fun stubStopTempBasal() { + whenever(pumpSync.syncStopTemporaryBasalWithPumpId(any(), any(), any(), any(), any())).thenReturn(true) + whenever(pumpSync.syncTemporaryBasalWithPumpId(any(), any(), any(), any(), anyOrNull(), any(), any(), any())).thenReturn(true) + } + + private suspend fun verifyNoTempBasalSynced() { + verify(pumpSync, never()).syncTemporaryBasalWithPumpId(any(), any(), any(), any(), anyOrNull(), any(), any(), any()) + } + + @Test + fun `a faulted pod records a zero temp basal under the pod serial`() = runBlocking { + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState()) + + plugin.checkPodKaput() + + verifyZeroTempBasalSynced("9999") + } + + @Test + fun `a faulted pod does not record a second zero temp basal when one is already running`() = runBlocking { + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(zeroTempBasal(PumpSync.TemporaryBasalType.PUMP_SUSPEND))) + + plugin.checkPodKaput() + + verifyNoTempBasalSynced() + } + + @Test + fun `a faulted pod replaces a short zero temp basal from the loop`() = runBlocking { + whenever(podStateManager.isPodKaput).thenReturn(true) + whenever(podStateManager.podId).thenReturn(9999L) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(zeroTempBasal(PumpSync.TemporaryBasalType.NORMAL))) + + plugin.checkPodKaput() + + verifyZeroTempBasalSynced("9999") + } + + @Test + fun `a healthy pod records no zero temp basal`() = runBlocking { + whenever(podStateManager.isPodKaput).thenReturn(false) + + plugin.checkPodKaput() + + verifyNoTempBasalSynced() + } + + @Test + fun `no running pod records a zero temp basal under the serial AAPS has registered`() = runBlocking { + whenever(podStateManager.isPodRunning).thenReturn(false) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(serial = "4242")) + + plugin.createFakeTBRWhenNoActivePod() + + verifyZeroTempBasalSynced("4242") + } + + @Test + fun `no running pod and no registered pump records the zero temp basal under the unpaired serial`() = runBlocking { + whenever(podStateManager.isPodRunning).thenReturn(false) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(serial = "")) + + plugin.createFakeTBRWhenNoActivePod() + + verifyZeroTempBasalSynced(O5PumpPlugin.UNPAIRED_SERIAL) + } + + @Test + fun `a running pod gets no fake zero temp basal`() = runBlocking { + whenever(podStateManager.isPodRunning).thenReturn(true) + + plugin.createFakeTBRWhenNoActivePod() + + verifyNoTempBasalSynced() + verify(pumpSync, never()).expectedPumpState() + } + + @Test + fun `deactivation records a zero temp basal under the old pod serial`() = runBlocking { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(serial = "12345")) + + plugin.executeCustomCommand(CommandDeactivatePod()) + + verifyZeroTempBasalSynced("12345") + } + + @Test + fun `suspending delivery records a zero temp basal`() = runBlocking { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + plugin.executeCustomCommand(CommandSuspendDelivery()) + + verifyZeroTempBasalSynced("12345") + } + + @Test + fun `a confirmed temp basal cancel tells AAPS the temp basal ended`() = runBlocking { + stubStopTempBasal() + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.TEMP_BASAL_ACTIVE, DeliveryStatus.BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + val result = plugin.cancelTempBasal(false) + + assertThat(result.enacted).isTrue() + verify(pumpSync).syncStopTemporaryBasalWithPumpId(any(), any(), eq(PumpType.OMNIPOD_5), eq("12345"), any()) + } + + @Test + fun `a temp basal cancel while delivery is suspended keeps the zero temp basal`() = runBlocking { + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.SUSPENDED) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(zeroTempBasal(PumpSync.TemporaryBasalType.PUMP_SUSPEND))) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + plugin.cancelTempBasal(false) + + verify(pumpSync, never()).syncStopTemporaryBasalWithPumpId(any(), any(), any(), any(), any()) + verify(podStateManager, never()).activeTempBasalRate = null + } + + @Test + fun `a reconciled temp basal cancel tells AAPS the temp basal ended`() = runBlocking { + stubStopTempBasal() + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn( + O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_CANCEL, startedAt = 5_000L, sequenceNumber = 4, historyId = 7L + ) + ) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(4) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + + plugin.reconcilePendingDose() + + verify(pumpSync).syncStopTemporaryBasalWithPumpId(eq(5_000L), eq(7L), eq(PumpType.OMNIPOD_5), eq("12345"), any()) + } + + @Test + fun `a reconciled basal program ends the temp basal and stores the pod time zone`() = runBlocking { + stubStopTempBasal() + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn( + O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BASAL_PROGRAM, startedAt = 5_000L, sequenceNumber = 4, historyId = 7L, + requestedBasalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + ) + ) + whenever(podStateManager.sequenceNumberOfLastProgrammingCommand).thenReturn(4) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + + plugin.reconcilePendingDose() + + verify(pumpSync).syncStopTemporaryBasalWithPumpId(eq(5_000L), eq(7L), eq(PumpType.OMNIPOD_5), eq("12345"), any()) + verify(podStateManager).updateTimeZone() + verify(podStateManager).deliverySuspended = false + } + + private fun flatProfile(): PumpProfile = mock().also { + whenever(it.getBasalValues()).thenReturn(arrayOf(Profile.ProfileValue(0, 1.0))) + } + + @Test + fun `profile change disables the suspend alert even when it was previously disabled`() = runBlocking { + stubStopTempBasal() + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + var suspendAlertsEnabled = false + whenever(podStateManager.suspendAlertsEnabled).thenAnswer { suspendAlertsEnabled } + doAnswer { + suspendAlertsEnabled = it.getArgument(0) + null + }.whenever(podStateManager).suspendAlertsEnabled = any() + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + stubAcceptedDoseCommands() + val result = plugin.setNewBasalProfile(flatProfile()) + + assertThat(result.success).isTrue() + assertThat(result.enacted).isTrue() + inOrder(bleManager, podStateManager) { + verify(bleManager).sendCommand(argThat { this is SuspendDeliveryCommand }, any()) + verify(podStateManager).suspendAlertsEnabled = true + verify(bleManager).sendCommand(argThat { this is ProgramBasalCommand }, any()) + verify(bleManager).sendCommand(argThat { this is ProgramAlertsCommand }, any()) + verify(podStateManager).suspendAlertsEnabled = false + } + assertThat(suspendAlertsEnabled).isFalse() + } + + @Test + fun `failed profile write keeps the suspend alert armed`() = runBlocking { + stubStopTempBasal() + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + whenever(bleManager.sendCommand(argThat { this is ProgramBasalCommand }, any())) + .thenReturn(Observable.error(IllegalStateException("Profile write failed"))) + + val result = plugin.setNewBasalProfile(flatProfile()) + + assertThat(result.success).isFalse() + verify(podStateManager).suspendAlertsEnabled = true + verify(podStateManager, never()).suspendAlertsEnabled = false + verify(bleManager, never()).sendCommand(argThat { this is ProgramAlertsCommand }, any()) + } + + @Test + fun `setting a basal profile records the suspend, then ends it, and posts no PROFILE_SET_OK itself`() = runBlocking { + stubStopTempBasal() + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.BASAL_ACTIVE) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + stubAcceptedDoseCommands() + val result = plugin.setNewBasalProfile(flatProfile()) + + assertThat(result.success).isTrue() + assertThat(result.enacted).isTrue() + verifyZeroTempBasalSynced("12345") + verify(pumpSync).syncStopTemporaryBasalWithPumpId(any(), any(), eq(PumpType.OMNIPOD_5), eq("12345"), any()) + verify(podStateManager).confirmTimeZone(any()) + verify(notificationManager, never()).post(eq(NotificationId.PROFILE_SET_OK), any(), any(), any(), any(), any(), anyOrNull(), any(), anyOrNull()) + } + + @Test + fun `resuming delivery ends the zero temp basal`() = runBlocking { + stubStopTempBasal() + val profile = flatProfile() + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.podId).thenReturn(12345L) + whenever(podStateManager.pendingDoseCommand).thenReturn(null) + whenever(podStateManager.deliveryStatus).thenReturn(DeliveryStatus.SUSPENDED) + whenever(pumpSync.expectedPumpState()).thenReturn(pumpState(zeroTempBasal(PumpSync.TemporaryBasalType.PUMP_SUSPEND), profile = profile)) + whenever(bleManager.sendCommand(any(), any())).thenReturn(Observable.empty()) + + stubAcceptedDoseCommands() + val result = plugin.executeCustomCommand(CommandResumeDelivery()) + + assertThat(result!!.success).isTrue() + verify(pumpSync).syncStopTemporaryBasalWithPumpId(any(), any(), eq(PumpType.OMNIPOD_5), eq("12345"), any()) + } + + @Test + fun `setting a basal profile before pairing is deferred, not reported as a write`() = runBlocking { + whenever(podStateManager.ltk).thenReturn(null) + + val result = plugin.setNewBasalProfile(flatProfile()) + + assertThat(result.success).isTrue() + assertThat(result.enacted).isFalse() + verify(bleManager, never()).sendCommand(any(), any()) + } + + private fun verifyTextRefPosted(id: NotificationId, mode: VerificationMode = times(1)) { + verify(notificationManager, mode).post(eq(id), any(), any(), any(), any(), any(), anyOrNull(), any(), anyOrNull()) + } + + @Test + fun `pod warnings report a missing pod, but only once per 15 minutes`() { + whenever(podStateManager.isPodRunning).thenReturn(false) + + plugin.updatePodWarnings() + plugin.updatePodWarnings() + + verifyTextRefPosted(NotificationId.OMNIPOD_POD_NOT_ATTACHED) + } + + @Test + fun `pod warnings report suspended delivery with sound`() { + whenever(podStateManager.isPodRunning).thenReturn(true) + whenever(podStateManager.isSuspended).thenReturn(true) + whenever(preferences.get(DashBooleanPreferenceKey.SoundDeliverySuspendedNotification)).thenReturn(true) + whenever(rh.gs(R.string.omnipod_common_alert_delivery_suspended)).thenReturn("Insulin delivery is suspended") + + plugin.updatePodWarnings() + + verify(notificationManager).dismiss(NotificationId.OMNIPOD_POD_NOT_ATTACHED) + verify(notificationManager).post( + eq(NotificationId.OMNIPOD_POD_SUSPENDED), eq("Insulin delivery is suspended"), level = any(), validMinutes = any(), + sound = eq(AlarmSound.BOLUS_ERROR), actions = any(), validityCheck = anyOrNull() + ) + } + + @Test + fun `pod warnings report a pod time zone that differs from the phone`() { + whenever(podStateManager.isPodRunning).thenReturn(true) + whenever(podStateManager.isSuspended).thenReturn(false) + whenever(podStateManager.sameTimeZone).thenReturn(false) + + plugin.updatePodWarnings() + + verify(notificationManager).dismiss(NotificationId.OMNIPOD_POD_SUSPENDED) + verifyTextRefPosted(NotificationId.OMNIPOD_TIME_OUT_OF_SYNC) + } + + @Test + fun `pod warnings stay quiet for a healthy running pod`() { + whenever(podStateManager.isPodRunning).thenReturn(true) + whenever(podStateManager.isSuspended).thenReturn(false) + whenever(podStateManager.sameTimeZone).thenReturn(true) + + plugin.updatePodWarnings() + + verify(notificationManager, never()).post(any(), any(), any(), any(), any(), any(), anyOrNull(), any(), anyOrNull()) + verify(notificationManager, never()).post( + any(), any(), level = any(), validMinutes = any(), + sound = anyOrNull(), actions = any(), validityCheck = anyOrNull() + ) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManagerImplTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManagerImplTest.kt new file mode 100644 index 000000000000..e2a6b7650d53 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5BleManagerImplTest.kt @@ -0,0 +1,140 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm + +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.FailedToConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.device.BleDeviceManager +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.O5BleConnectionFactory +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.common.bledriver.comm.session.NotConnected +import app.aaps.pump.omnipod.common.bledriver.pod.command.base.Command +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.security.SecureO5RegistrationStorage +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.shared.tests.AAPSLoggerTest +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.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +/** + * [O5BleManagerImpl] - covers the guard/validation paths reachable without a live BLE + * connection (missing pairing state, no connection established yet, the "already paired" + * short-circuit). Deep BLE session establishment ([O5BleManagerImpl.establishSession] and + * everything downstream of a real [app.aaps.pump.omnipod.common.bledriver.comm.interfaces + * .session.BleConnection]) is out of scope for this pass - it would need mocking the whole + * connection/session stack, not just this class's direct dependencies. + */ +class O5BleManagerImplTest { + + private val aapsLogger = AAPSLoggerTest() + private val podState = mock() + private val config = mock() + private val context = mock() + private val bleConnectionFactory = mock() + private val bleDeviceManager = mock() + private val secureO5RegistrationStorage = mock() + private val p256KeyGenerator = P256KeyGenerator() + + private fun newManager() = O5BleManagerImpl( + aapsLogger, podState, config, context, bleConnectionFactory, + bleDeviceManager, secureO5RegistrationStorage, p256KeyGenerator + ) + + @BeforeEach + fun clearRegistrationData() { + O5RegistrationData.allValues.forEach { O5RegistrationData.remove(it.controllerId) } + } + + @AfterEach + fun tearDown() { + O5RegistrationData.allValues.forEach { O5RegistrationData.remove(it.controllerId) } + } + + @Test + fun `getStatus returns NotConnected before any connection has been established`() { + val manager = newManager() + + assertThat(manager.getStatus()).isEqualTo(NotConnected) + } + + @Test + fun `constructor loads previously-imported credentials via SecureO5RegistrationStorage`() { + newManager() + + verify(secureO5RegistrationStorage).loadAndInstallAll() + } + + @Test + fun `sendCommand fails with FailedToConnectException when there is no established connection`() { + val manager = newManager() + + val observer = manager.sendCommand(mock(), DefaultStatusResponse::class).test() + + observer.assertError(FailedToConnectException::class.java) + } + + @Test + fun `connect fails with FailedToConnectException when the pod has no known bluetoothAddress`() { + whenever(podState.bluetoothAddress).thenReturn(null) + val manager = newManager() + + val observer = manager.connect(timeoutMs = 1000).test() + + observer.assertError(FailedToConnectException::class.java) + } + + @Test + fun `pairNewPod requires a known address when an LTK is already present`() { + whenever(podState.ltk).thenReturn(byteArrayOf(1, 2, 3)) + whenever(podState.bluetoothAddress).thenReturn(null) + val manager = newManager() + + val observer = manager.pairNewPod().test() + + observer.assertError(FailedToConnectException::class.java) + } + + @Test + fun `pairNewPod fails with PairingException when no O5 registration data is installed`() { + whenever(podState.ltk).thenReturn(null) + val manager = newManager() + + val observer = manager.pairNewPod().test() + + observer.assertError(PairingException::class.java) + } + + @Test + fun `removeBond does nothing and does not call the device manager when bluetoothAddress is unknown`() { + whenever(podState.bluetoothAddress).thenReturn(null) + val manager = newManager() + + manager.removeBond() + + verify(bleDeviceManager, never()).removeBond(org.mockito.kotlin.any()) + } + + @Test + fun `removeBond delegates to the device manager with the pod's bluetoothAddress`() { + whenever(podState.bluetoothAddress).thenReturn("AA:BB:CC:DD:EE:FF") + val manager = newManager() + + manager.removeBond() + + verify(bleDeviceManager).removeBond("AA:BB:CC:DD:EE:FF") + } + + @Test + fun `disconnect does not throw when there is no active connection`() { + val manager = newManager() + + manager.disconnect(closeGatt = false) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5IdRotationTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5IdRotationTest.kt new file mode 100644 index 000000000000..1301c34fa0d7 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5IdRotationTest.kt @@ -0,0 +1,63 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class O5IdRotationTest { + + @Test + fun `controllerIdForPodId clears the low 2 bits`() { + assertThat(O5IdRotation.controllerIdForPodId(0b1100L)).isEqualTo(0b1100L) + assertThat(O5IdRotation.controllerIdForPodId(0b1101L)).isEqualTo(0b1100L) + assertThat(O5IdRotation.controllerIdForPodId(0b1110L)).isEqualTo(0b1100L) + assertThat(O5IdRotation.controllerIdForPodId(0b1111L)).isEqualTo(0b1100L) + } + + @Test + fun `firstPodId normalizes every controller id suffix`() { + val base = 0xAABBCC00L + + assertThat(O5IdRotation.firstPodId(base)).isEqualTo(base + 1) + assertThat(O5IdRotation.firstPodId(base + 1)).isEqualTo(base + 1) + assertThat(O5IdRotation.firstPodId(base + 2)).isEqualTo(base + 1) + assertThat(O5IdRotation.firstPodId(base + 3)).isEqualTo(base + 1) + } + + @Test + fun `nextPodId advances to the identity for the next pod`() { + val base = 0b1000L + + assertThat(O5IdRotation.nextPodId(base + 1)).isEqualTo(base + 2) + assertThat(O5IdRotation.nextPodId(base + 2)).isEqualTo(base + 3) + } + + @Test + fun `nextPodId wraps back to base plus 1 after the third pod`() { + val base = 0b10000L + + assertThat(O5IdRotation.nextPodId(base + 3)).isEqualTo(base + 1) + } + + @Test + fun `nextPodId preserves the controllerId bits across a wrap`() { + val base = 0xAABBCC00L + + val wrapped = O5IdRotation.nextPodId(base + 3) + + assertThat(O5IdRotation.controllerIdForPodId(wrapped)).isEqualTo(base) + } + + @Test + fun `full rotation cycle visits exactly base+1, base+2, base+3, then repeats`() { + val base = 0b100L + var podId = base + 1 + + val visited = mutableListOf(podId) + repeat(3) { + podId = O5IdRotation.nextPodId(podId) + visited.add(podId) + } + + assertThat(visited).containsExactly(base + 1, base + 2, base + 3, base + 1).inOrder() + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5PairingCoordinatorTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5PairingCoordinatorTest.kt new file mode 100644 index 000000000000..7ddab4a9fea9 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/O5PairingCoordinatorTest.kt @@ -0,0 +1,70 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.O5BleConnectionFactory +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.shared.tests.AAPSLoggerTest +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * [O5PairingCoordinator] - covers the two guard checks that run before any real BLE + * scanning/connection attempt. The rest of [O5PairingCoordinator.pairNewPod] (scan, connect, + * negotiate LTK, establish session) needs a live or deeply-mocked BLE stack and is out of + * scope for this pass - same boundary as [O5BleManagerImplTest]. + */ +class O5PairingCoordinatorTest { + + private val aapsLogger = AAPSLoggerTest() + private val config = mock() + private val context = mock() + private val podState = mock() + private val bleConnectionFactory = mock() + private val p256KeyGenerator = P256KeyGenerator() + + private fun newCoordinator() = O5PairingCoordinator( + aapsLogger, config, context, podState, bleConnectionFactory, p256KeyGenerator + ) + + @BeforeEach + fun clearRegistrationData() { + O5RegistrationData.allValues.forEach { O5RegistrationData.remove(it.controllerId) } + } + + @AfterEach + fun tearDown() { + O5RegistrationData.allValues.forEach { O5RegistrationData.remove(it.controllerId) } + } + + @Test + fun `pairNewPod throws ConnectException when Bluetooth is unavailable`() { + whenever(context.getSystemService(Context.BLUETOOTH_SERVICE)).thenReturn(null) + + assertThrows(ConnectException::class.java) { + newCoordinator().pairNewPod() + } + } + + @Test + fun `pairNewPod throws PairingException when no O5 registration data is installed`() { + val bluetoothManager = mock() + val bluetoothAdapter = mock() + whenever(context.getSystemService(Context.BLUETOOTH_SERVICE)).thenReturn(bluetoothManager) + whenever(bluetoothManager.adapter).thenReturn(bluetoothAdapter) + + assertThrows(PairingException::class.java) { + newCoordinator().pairNewPod() + } + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/session/O5ConnectionTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/session/O5ConnectionTest.kt new file mode 100644 index 000000000000..7e64c69de25d --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/legacy/session/O5ConnectionTest.kt @@ -0,0 +1,219 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.legacy.session + +import android.bluetooth.BluetoothDevice +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothGattService +import android.bluetooth.BluetoothManager +import android.bluetooth.BluetoothProfile +import android.content.Context +import app.aaps.core.interfaces.configuration.Config +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.ConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.FailedToConnectException +import app.aaps.pump.omnipod.common.bledriver.comm.interfaces.io.CharacteristicType +import app.aaps.pump.omnipod.common.bledriver.comm.legacy.callbacks.BleCommCallbacks +import app.aaps.pump.omnipod.common.bledriver.comm.session.Connected +import app.aaps.pump.omnipod.common.bledriver.comm.session.ConnectionWaitCondition +import app.aaps.pump.omnipod.common.bledriver.comm.session.NotConnected +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +/** + * [O5Connection]'s GATT lifecycle. Unlike [app.aaps.pump.omnipod.common.bledriver.comm + * .O5PairingCoordinatorTest], which stopped at the two guard checks before any BLE work, + * this suite drives the real [connect] path through GATT connect, service discovery and + * the hello() handshake by mocking the Android BLE framework classes directly + * (already-proven-safe technique this session: Mockito's inline mock maker mocks these + * final/framework classes fine). It stops short of `readyToRead()` - see the comment above + * the happy-path test for why that step is a genuine environment boundary, not a gap in + * this suite's mocking. + * + * The key simplification: [BleCommCallbacks]'s blocking waits ([BleCommCallbacks + * .waitForConnection]/[waitForServiceDiscovery]/[confirmWrite]) are backed by a + * [java.util.concurrent.CountDownLatch]/[java.util.concurrent.BlockingQueue] that don't + * care *which thread* counts them down - so the real [BleCommCallbacks] instance + * [O5Connection] constructs internally (captured here via the [BluetoothDevice.connectGatt] + * argument) can have its callback methods invoked *synchronously inside* the `thenAnswer` + * for the GATT call that would normally trigger them (`connectGatt`, `discoverServices`, + * `writeCharacteristic`), so every blocking wait finds its latch/queue already satisfied + * and returns immediately - no real waiting, no background thread, no flaky timing. + */ +class O5ConnectionTest { + + private val aapsLogger = AAPSLoggerTest() + private val config = mock() + private val context = mock() + private val podState = mock() + private val podDevice = mock() + private val bluetoothManager = mock() + private val p256KeyGenerator = mock() + + private fun newConnection(bluetoothServiceAvailable: Boolean = true): O5Connection { + whenever(context.getSystemService(Context.BLUETOOTH_SERVICE)) + .thenReturn(if (bluetoothServiceAvailable) bluetoothManager else null) + return O5Connection(podDevice, aapsLogger, config, context, podState, p256KeyGenerator) + } + + + @Test fun `connectionState reports Connected when the GATT profile is connected`() { + whenever(bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT)) + .thenReturn(BluetoothProfile.STATE_CONNECTED) + + assertThat(newConnection().connectionState()).isInstanceOf(Connected::class.java) + } + + @Test fun `connectionState reports NotConnected when the GATT profile is not connected`() { + whenever(bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT)) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED) + + assertThat(newConnection().connectionState()).isInstanceOf(NotConnected::class.java) + } + + @Test fun `connectionState reports NotConnected when the BluetoothManager system service is unavailable`() { + assertThat(newConnection(bluetoothServiceAvailable = false).connectionState()) + .isInstanceOf(NotConnected::class.java) + } + + + @Test fun `establishSession throws ConnectException when there is no active BLE connection`() { + val ids = Ids.forController(Id.fromInt(1), Id.fromInt(2)) + + assertThrows(ConnectException::class.java) { + newConnection().establishSession(ByteArray(16), 0, ids, ByteArray(6)) + } + } + + + @Test fun `disconnect is a no-op when there is no GATT connection yet`() { + newConnection().disconnect(closeGatt = true) + newConnection().disconnect(closeGatt = false) + } + + @Test fun `disconnect(closeGatt=false) disconnects the GATT object but keeps it for reuse`() { + val gatt = mock() + val connection = connectionWithGattConnectionEstablished(gatt) + + connection.disconnect(closeGatt = false) + + verify(gatt).disconnect() + verify(gatt, never()).close() + } + + @Test fun `disconnect(closeGatt=true) closes and clears the GATT object and resets the session`() { + val gatt = mock() + val connection = connectionWithGattConnectionEstablished(gatt) + + connection.disconnect(closeGatt = true) + + verify(gatt).close() + connection.disconnect(closeGatt = true) + verify(gatt, times(1)).close() + } + + /** Drives [O5Connection.connect] just far enough to populate its internal + * `gattConnection` (set immediately after a successful [BluetoothDevice.connectGatt]) + * then lets it fail at the connection-wait step, so [O5Connection.disconnect] has a + * real (mocked) GATT object to act on without needing the full handshake below. */ + private fun connectionWithGattConnectionEstablished(gatt: BluetoothGatt): O5Connection { + whenever( + podDevice.connectGatt(eq(context), eq(false), any(), eq(BluetoothDevice.TRANSPORT_LE)) + ).thenReturn(gatt) + whenever(bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT)) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED) + val connection = newConnection() + assertThrows(FailedToConnectException::class.java) { + connection.connect(ConnectionWaitCondition(timeoutMs = 10L)) + } + return connection + } + + + @Test fun `connect throws FailedToConnectException when the connection wait times out`() { + val gatt = mock() + whenever( + podDevice.connectGatt(eq(context), eq(false), any(), eq(BluetoothDevice.TRANSPORT_LE)) + ).thenReturn(gatt) + whenever(bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT)) + .thenReturn(BluetoothProfile.STATE_DISCONNECTED) + + assertThrows(FailedToConnectException::class.java) { + newConnection().connect(ConnectionWaitCondition(timeoutMs = 10L)) + } + } + + + @Test fun `connect completes GATT connection, service discovery and hello() before hitting the readyToRead() environment boundary`() { + val gatt = mock() + val service = mock() + val cmdChar = mock() + val dataChar = mock() + val cmdDescriptor = mock() + val dataDescriptor = mock() + var bleCommCallbacks: BleCommCallbacks? = null + + whenever(bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT)) + .thenReturn(BluetoothProfile.STATE_CONNECTED) + + whenever( + podDevice.connectGatt(eq(context), eq(false), any(), eq(BluetoothDevice.TRANSPORT_LE)) + ).thenAnswer { invocation -> + val callbacks = invocation.getArgument(2) + bleCommCallbacks = callbacks + callbacks.onConnectionStateChange(gatt, BluetoothGatt.GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED) + gatt + } + + + whenever(gatt.discoverServices()).thenAnswer { + bleCommCallbacks!!.onServicesDiscovered(gatt, BluetoothGatt.GATT_SUCCESS) + true + } + whenever(gatt.getService(any())).thenReturn(service) + whenever(service.getCharacteristic(CharacteristicType.CMD.uuid)).thenReturn(cmdChar) + whenever(service.getCharacteristic(CharacteristicType.DATA_O5.uuid)).thenReturn(dataChar) + + var cmdCharValue: ByteArray? = null + whenever(cmdChar.uuid).thenReturn(CharacteristicType.CMD.uuid) + whenever(cmdChar.setValue(any())).thenAnswer { invocation -> + cmdCharValue = invocation.getArgument(0) + true + } + whenever(cmdChar.value).thenAnswer { cmdCharValue } + whenever(cmdChar.descriptors).thenReturn(listOf(cmdDescriptor)) + whenever(gatt.writeCharacteristic(cmdChar)).thenAnswer { + bleCommCallbacks!!.onCharacteristicWrite(gatt, cmdChar, BluetoothGatt.GATT_SUCCESS) + true + } + + whenever(gatt.setCharacteristicNotification(any(), any())).thenReturn(true) + whenever(cmdChar.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_INDICATE) + whenever(dataChar.descriptors).thenReturn(listOf(dataDescriptor)) + whenever(dataChar.properties).thenReturn(BluetoothGattCharacteristic.PROPERTY_INDICATE) + whenever(gatt.writeDescriptor(any())).thenReturn(true) + + val connection = newConnection() + assertThrows(NullPointerException::class.java) { + connection.connect(ConnectionWaitCondition(timeoutMs = 50L)) + } + + verify(gatt).discoverServices() + verify(gatt).writeCharacteristic(cmdChar) + assertThat(cmdCharValue).isNotNull() + assertThat(cmdCharValue).isNotEmpty() + assertThat(connection.msgIO).isNotNull() + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5CertificateStoreTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5CertificateStoreTest.kt new file mode 100644 index 000000000000..f12a2e76a970 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5CertificateStoreTest.kt @@ -0,0 +1,251 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair + +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import java.math.BigInteger +import java.security.KeyPairGenerator +import java.security.Signature +import java.security.spec.ECGenParameterSpec +import java.util.Base64 + +/** + * [O5CertificateStore] - pure crypto/DER logic, no BLE involved, so tested directly against + * real P-256 key material rather than mocks. [O5RegistrationData] is a process-wide registry + * keyed by controllerId, so every test uses its own controllerId and cleans up afterward to + * avoid cross-test pollution. + */ +class O5CertificateStoreTest { + + private val aapsLogger = AAPSLoggerTest() + private val keyGenerator = P256KeyGenerator() + private val usedControllerIds = mutableListOf() + + @AfterEach + fun tearDown() { + usedControllerIds.forEach { O5RegistrationData.remove(it) } + usedControllerIds.clear() + } + + private fun installValidRegistration(controllerId: Long): O5RegistrationData { + usedControllerIds.add(controllerId) + val privateKey = keyGenerator.generatePrivateKey() + val publicKey = keyGenerator.publicFromPrivate(privateKey) + val data = O5RegistrationData( + controllerId = controllerId, + privateKeyHex = privateKey.toHex(), + publicKeyHex = publicKey.toHex(), + intermediateCABase64 = "", + tlsCertificateBase64 = "" + ) + O5RegistrationData.install(data, O5RegistrationData.O5RegistrationSource.DOWNLOADED) + return data + } + + private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) } + + @Test + fun `constructor throws when no registration data is installed`() { + assertThrows(PairingException::class.java) { + O5CertificateStore(aapsLogger, keyGenerator, 0x11223344L) + } + } + + @Test + fun `constructor succeeds and exposes registration fields when a matching keypair is installed`() { + val controllerId = 0xAABBCCDDL + val data = installValidRegistration(controllerId) + + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + + assertThat(store.controllerId).isEqualTo(controllerId) + assertThat(store.signingPublicKeyRaw).isEqualTo(data.publicKey) + } + + @Test + fun `controllerIdData is the big-endian 4-byte representation`() { + val controllerId = 0x01020304L + installValidRegistration(controllerId) + + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + + assertThat(store.controllerIdData).isEqualTo(byteArrayOf(0x01, 0x02, 0x03, 0x04)) + } + + @Test + fun `constructor throws when the stored public key does not match the private key`() { + val controllerId = 0x99887766L + usedControllerIds.add(controllerId) + val privateKey = keyGenerator.generatePrivateKey() + val unrelatedPublicKey = keyGenerator.publicFromPrivate(keyGenerator.generatePrivateKey()) + O5RegistrationData.install( + O5RegistrationData( + controllerId = controllerId, + privateKeyHex = privateKey.toHex(), + publicKeyHex = unrelatedPublicKey.toHex(), + intermediateCABase64 = "", + tlsCertificateBase64 = "" + ), + source = O5RegistrationData.O5RegistrationSource.DOWNLOADED, + ) + + assertThrows(PairingException::class.java) { + O5CertificateStore(aapsLogger, keyGenerator, controllerId) + } + } + + @Test + fun `signRaw produces a signature verifySignature accepts against the matching public key`() { + val controllerId = 0x12345678L + val data = installValidRegistration(controllerId) + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + val message = "the quick brown fox".toByteArray() + + val signature = store.signRaw(message) + + assertThat(signature).hasLength(64) + assertThat(O5CertificateStore.verifySignature(signature, message, data.publicKey)).isTrue() + } + + @Test + fun `verifySignature rejects a signature checked against the wrong public key`() { + val controllerId = 0x22334455L + installValidRegistration(controllerId) + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + val message = "the quick brown fox".toByteArray() + val signature = store.signRaw(message) + val wrongPublicKey = keyGenerator.publicFromPrivate(keyGenerator.generatePrivateKey()) + + assertThat(O5CertificateStore.verifySignature(signature, message, wrongPublicKey)).isFalse() + } + + @Test + fun `verifySignature rejects a signature over different data`() { + val controllerId = 0x33445566L + val data = installValidRegistration(controllerId) + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + val signature = store.signRaw("original message".toByteArray()) + + assertThat(O5CertificateStore.verifySignature(signature, "tampered message".toByteArray(), data.publicKey)).isFalse() + } + + @Test + fun `derSignatureToRaw and rawSignatureToDer round-trip a real ECDSA signature`() { + val keyPairGenerator = KeyPairGenerator.getInstance("EC") + keyPairGenerator.initialize(ECGenParameterSpec("secp256r1")) + val keyPair = keyPairGenerator.generateKeyPair() + val message = "round trip me".toByteArray() + + val signature = Signature.getInstance("SHA256withECDSA") + signature.initSign(keyPair.private) + signature.update(message) + val der = signature.sign() + + val raw = O5CertificateStore.derSignatureToRaw(der) + assertThat(raw).hasLength(64) + + val reDer = O5CertificateStore.rawSignatureToDer(raw) + + val verify = Signature.getInstance("SHA256withECDSA") + verify.initVerify(keyPair.public) + verify.update(message) + assertThat(verify.verify(reDer)).isTrue() + } + + @Test + fun `verifySignature accepts a raw 64-byte signature directly, not just DER`() { + val controllerId = 0x44556677L + val data = installValidRegistration(controllerId) + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + val message = "raw format check".toByteArray() + + val rawSignature = store.signRaw(message) + + assertThat(rawSignature).hasLength(64) + assertThat(O5CertificateStore.verifySignature(rawSignature, message, data.publicKey)).isTrue() + } + + @Test + fun `verifySignature returns false for a garbage public key rather than throwing`() { + val garbagePublicKey = ByteArray(64) { 0x42 } + val garbageSignature = ByteArray(64) { 0x01 } + + assertThat(O5CertificateStore.verifySignature(garbageSignature, "data".toByteArray(), garbagePublicKey)).isFalse() + } + + + private val p256SpkiHeader = byteArrayOf( + 0x30, 0x59.toByte(), + 0x30, 0x13, + 0x06, 0x07, 0x2a, 0x86.toByte(), 0x48, 0xce.toByte(), 0x3d, 0x02, 0x01, + 0x06, 0x08, 0x2a, 0x86.toByte(), 0x48, 0xce.toByte(), 0x3d, 0x03, 0x01, 0x07, + 0x03, 0x42, + 0x00, + 0x04 + ) + + @Test + fun `extractP256PublicKey finds the 64-byte key following the SPKI header`() { + val expectedKey = ByteArray(64) { (it + 1).toByte() } + val certDER = byteArrayOf(0x11, 0x22, 0x33) + p256SpkiHeader + expectedKey + byteArrayOf(0x44, 0x55) + + val extracted = O5CertificateStore.extractP256PublicKey(certDER) + + assertThat(extracted).isEqualTo(expectedKey) + } + + @Test + fun `extractP256PublicKey returns null when the SPKI header is absent`() { + val certDER = ByteArray(100) { it.toByte() } + + assertThat(O5CertificateStore.extractP256PublicKey(certDER)).isNull() + } + + @Test + fun `extractP256PublicKey returns null when there is not enough trailing data for a full key`() { + val certDER = p256SpkiHeader + ByteArray(10) + + assertThat(O5CertificateStore.extractP256PublicKey(certDER)).isNull() + } + + @Test + fun `extractP256PublicKey base64 overload decodes then extracts`() { + val expectedKey = ByteArray(64) { (it * 3).toByte() } + val certDER = p256SpkiHeader + expectedKey + val certDERBase64 = Base64.getEncoder().encodeToString(certDER) + + assertThat(O5CertificateStore.extractP256PublicKey(certDERBase64)).isEqualTo(expectedKey) + } + + @Test + fun `extractP256PublicKey base64 overload returns null for invalid base64`() { + assertThat(O5CertificateStore.extractP256PublicKey("not valid base64!!")).isNull() + } + + + @Test + fun `extractSerialNumber handles the v3 explicit-version-tag pattern`() { + val serial = byteArrayOf(0x01, 0x02, 0x03) + val v3Pattern = byteArrayOf(0xa0.toByte(), 0x03, 0x02, 0x01, 0x02, 0x02) + val certDER = byteArrayOf(0x30, 0x10) + v3Pattern + byteArrayOf(serial.size.toByte()) + serial + byteArrayOf(0x00, 0x00) + + assertThat(O5CertificateStore.extractSerialNumber(certDER)).isEqualTo(serial) + } + + @Test + fun `extractSerialNumber falls back to v1 parsing when there is no version tag`() { + val serial = byteArrayOf(0x0A, 0x0B) + val certDER = byteArrayOf(0x30, 0x06, 0x30, 0x04, 0x02, 0x02) + serial + + assertThat(O5CertificateStore.extractSerialNumber(certDER)).isEqualTo(serial) + } + + @Test + fun `extractSerialNumber returns null for malformed input`() { + assertThat(O5CertificateStore.extractSerialNumber(byteArrayOf(0x01, 0x02))).isNull() + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5KeyExchangeTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5KeyExchangeTest.kt new file mode 100644 index 000000000000..99fc850378ae --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5KeyExchangeTest.kt @@ -0,0 +1,170 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair + +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.MessageIOException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.pump.omnipod.common.bledriver.pod.util.RandomByteGenerator +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.spy +import org.mockito.kotlin.whenever + +/** + * [O5KeyExchange] - real P-256/SHA-256 crypto is exercised via real generators (not hand- + * verified against an external test vector, unlike [O5CertificateStoreTest]'s DER round-trip + * or [PulseLogEntryTest]'s openomni golden value - no equivalent published vector was found + * for this KDF). Tests instead check structural properties: sizes, byte-layout composition, + * and round-trip behavior (e.g. increment-then-check-against-original), which don't depend on + * knowing the "correct" hash output in advance. + */ +class O5KeyExchangeTest { + + private val aapsLogger = AAPSLoggerTest() + private val controllerIdData = byteArrayOf(0x01, 0x02, 0x03, 0x04) + + private fun newExchange( + keyGenerator: P256KeyGenerator = P256KeyGenerator(), + randomByteGenerator: RandomByteGenerator = RandomByteGenerator() + ) = O5KeyExchange(aapsLogger, keyGenerator, randomByteGenerator, controllerIdData) + + /** ECDH requires a genuine point on the curve - a real generated public key, standing in + * for the pod's, unlike an arbitrary byte array which fails curve validation. */ + private fun realPublicKey(): ByteArray { + val kg = P256KeyGenerator() + return kg.publicFromPrivate(kg.generatePrivateKey()) + } + + @Test + fun `constructor generates a correctly-sized nonce and public key`() { + val ke = newExchange() + + assertThat(ke.pdmNonce).hasLength(O5KeyExchange.NONCE_SIZE) + assertThat(ke.pdmPublic).hasLength(O5KeyExchange.PUBLIC_KEY_SIZE) + } + + @Test + fun `constructor throws when the random nonce generator returns the wrong size`() { + val randomByteGenerator = spy(RandomByteGenerator()) + doReturn(ByteArray(4)).whenever(randomByteGenerator).nextBytes(org.mockito.kotlin.any()) + + assertThrows(PairingException::class.java) { + newExchange(randomByteGenerator = randomByteGenerator) + } + } + + @Test + fun `constructor throws when the key generator returns a wrong-size public key`() { + val keyGenerator = spy(P256KeyGenerator()) + doReturn(ByteArray(10)).whenever(keyGenerator).publicFromPrivate(org.mockito.kotlin.any()) + + assertThrows(PairingException::class.java) { + newExchange(keyGenerator = keyGenerator) + } + } + + @Test + fun `o5UpdatePodPublicData throws for a wrong-size payload`() { + val ke = newExchange() + + assertThrows(MessageIOException::class.java) { + ke.o5UpdatePodPublicData(ByteArray(10)) + } + } + + @Test + fun `o5UpdatePodPublicData splits the payload and derives 16-byte conf and ltk`() { + val ke = newExchange() + val podPublic = realPublicKey() + val podNonce = ByteArray(O5KeyExchange.NONCE_SIZE) { (it + 100).toByte() } + + ke.o5UpdatePodPublicData(podPublic + podNonce) + + assertThat(ke.podPublic).isEqualTo(podPublic) + assertThat(ke.podNonce).isEqualTo(podNonce) + assertThat(ke.conf).hasLength(O5KeyExchange.CMAC_SIZE) + assertThat(ke.ltk).hasLength(O5KeyExchange.CMAC_SIZE) + assertThat(ke.conf).isNotEqualTo(ke.ltk) + } + + @Test + fun `getSPSNonce builds the direction-prefixed 13-byte nonce from both parties' first 6 bytes`() { + val ke = newExchange() + ke.o5UpdatePodPublicData(realPublicKey() + ByteArray(O5KeyExchange.NONCE_SIZE) { (it + 1).toByte() }) + + val writeNonce = ke.getSPSNonce(O5KeyExchange.Direction.WRITE) + val readNonce = ke.getSPSNonce(O5KeyExchange.Direction.READ) + + assertThat(writeNonce).hasLength(13) + assertThat(writeNonce[0]).isEqualTo(0x01.toByte()) + assertThat(writeNonce.copyOfRange(1, 7)).isEqualTo(ke.pdmNonce.copyOfRange(0, 6)) + assertThat(writeNonce.copyOfRange(7, 13)).isEqualTo(ke.podNonce.copyOfRange(0, 6)) + + assertThat(readNonce).hasLength(13) + assertThat(readNonce[0]).isEqualTo(0x02.toByte()) + assertThat(readNonce.copyOfRange(1, 7)).isEqualTo(ke.podNonce.copyOfRange(0, 6)) + assertThat(readNonce.copyOfRange(7, 13)).isEqualTo(ke.pdmNonce.copyOfRange(0, 6)) + } + + @Test + fun `incrementNonce increments the first 8 bytes as a little-endian counter and leaves the rest untouched`() { + val ke = newExchange() + val originalPdmNonce = ke.pdmNonce.copyOf() + + ke.incrementNonce(O5KeyExchange.Direction.WRITE) + + assertThat(ke.pdmNonce.copyOfRange(8, 16)).isEqualTo(originalPdmNonce.copyOfRange(8, 16)) + assertThat(ke.pdmNonce).isNotEqualTo(originalPdmNonce) + + val afterFirstIncrement = ke.pdmNonce.copyOf() + ke.incrementNonce(O5KeyExchange.Direction.WRITE) + assertThat(ke.pdmNonce).isNotEqualTo(afterFirstIncrement) + } + + @Test + fun `incrementNonce wraps a little-endian counter of all-0xFF bytes to zero`() { + val randomByteGenerator = spy(RandomByteGenerator()) + val allFF = ByteArray(O5KeyExchange.NONCE_SIZE) { 0xFF.toByte() } + doReturn(allFF).whenever(randomByteGenerator).nextBytes(org.mockito.kotlin.any()) + val ke = newExchange(randomByteGenerator = randomByteGenerator) + + ke.incrementNonce(O5KeyExchange.Direction.WRITE) + + assertThat(ke.pdmNonce.copyOfRange(0, 8)).isEqualTo(ByteArray(8)) + assertThat(ke.pdmNonce.copyOfRange(8, 16)).isEqualTo(ByteArray(8) { 0xFF.toByte() }) + } + + @Test + fun `buildChannelBindingTranscript is 171 bytes composed of the documented fields in order`() { + val ke = newExchange() + ke.o5UpdatePodPublicData(realPublicKey() + ByteArray(O5KeyExchange.NONCE_SIZE) { (it + 1).toByte() }) + + val transcript = ke.buildChannelBindingTranscript() + + assertThat(transcript).hasLength(171) + assertThat(transcript[0]).isEqualTo(0x01.toByte()) + assertThat(transcript.copyOfRange(1, 7)).isEqualTo(O5KeyExchange.FIRMWARE_ID) + assertThat(transcript.copyOfRange(7, 11)).isEqualTo(ByteArray(4)) + assertThat(transcript.copyOfRange(11, 75)).isEqualTo(ke.pdmPublic) + assertThat(transcript.copyOfRange(75, 139)).isEqualTo(ke.podPublic) + assertThat(transcript.copyOfRange(139, 155)).isEqualTo(ke.pdmNonce) + assertThat(transcript.copyOfRange(155, 171)).isEqualTo(ke.podNonce) + } + + @Test + fun `buildPodChannelBindingTranscript uses a podNonce decremented by one relative to the current value`() { + val ke = newExchange() + ke.o5UpdatePodPublicData(realPublicKey() + ByteArray(O5KeyExchange.NONCE_SIZE) { (it + 1).toByte() }) + val originalPodNonce = ke.podNonce.copyOf() + + ke.incrementNonce(O5KeyExchange.Direction.READ) + val transcript = ke.buildPodChannelBindingTranscript() + + assertThat(transcript).hasLength(171) + assertThat(transcript[0]).isEqualTo(0x02.toByte()) + val podNonceAdjustedInTranscript = transcript.copyOfRange(139, 155) + assertThat(podNonceAdjustedInTranscript).isEqualTo(originalPodNonce) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5LTKExchangerTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5LTKExchangerTest.kt new file mode 100644 index 000000000000..1408591df4e0 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/pair/O5LTKExchangerTest.kt @@ -0,0 +1,298 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair + +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.MessageIOException +import app.aaps.pump.omnipod.common.bledriver.comm.exceptions.PairingException +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessagePacket +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendErrorSending +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendSuccess +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageType +import app.aaps.pump.omnipod.common.bledriver.comm.message.StringLengthPrefixEncoding +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.spongycastle.crypto.engines.AESEngine +import org.spongycastle.crypto.modes.CCMBlockCipher +import org.spongycastle.crypto.params.AEADParameters +import org.spongycastle.crypto.params.KeyParameter +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.security.MessageDigest +import java.util.Base64 + +/** + * [O5LTKExchanger] - the two CRC-16 companion functions (pure, no mocking needed), the + * `o5NegotiateLTK()` orchestration's failure paths (send/receive failures, malformed + * responses - reachable without simulating real crypto), and one full happy-path test that + * *does* simulate a well-behaved pod's crypto responses (real ECDH + the same SHA-256 KDF + * and AES-CCM the production code uses), to verify the handshake's sequencing/nonce + * bookkeeping produces a correct, matching LTK end to end at the software layer. + * + * This does NOT verify the wire-format assumptions themselves are correct against a real + * pod (nothing here can, without hardware) - see [O5CertificateStore]'s doc comment and + * this project's own notes on `o5ValidatePodSps2`'s "transcript format may differ" comment + * for that caveat. + */ +class O5LTKExchangerTest { + + @Test + fun `crc16XMODEM matches the standard CRC-16-XMODEM check value`() { + assertThat(O5LTKExchanger.crc16XMODEM("123456789".toByteArray())).isEqualTo(0x31C3) + } + + @Test + fun `crc16XMODEM of empty input is zero`() { + assertThat(O5LTKExchanger.crc16XMODEM(ByteArray(0))).isEqualTo(0) + } + + @Test + fun `classicCrc16 is deterministic and sensitive to every input byte`() { + val a = O5LTKExchanger.classicCrc16(byteArrayOf(0x01, 0x02, 0x03)) + val aAgain = O5LTKExchanger.classicCrc16(byteArrayOf(0x01, 0x02, 0x03)) + val b = O5LTKExchanger.classicCrc16(byteArrayOf(0x01, 0x02, 0x04)) + + assertThat(a).isEqualTo(aAgain) + assertThat(a).isNotEqualTo(b) + } + + @Test + fun `classicCrc16 and crc16XMODEM are different algorithms, not accidentally identical`() { + val data = "regression guard".toByteArray() + + assertThat(O5LTKExchanger.classicCrc16(data)).isNotEqualTo(O5LTKExchanger.crc16XMODEM(data)) + } + + @Test + fun `classicCrc16 of empty input is zero`() { + assertThat(O5LTKExchanger.classicCrc16(ByteArray(0))).isEqualTo(0) + } + + + private val aapsLogger = AAPSLoggerTest() + private val p256KeyGenerator = P256KeyGenerator() + private val usedControllerIds = mutableListOf() + private val dummyId = Id.fromLong(0xDEADBEEFL and 0xFFFFFFFFL) + + @AfterEach + fun tearDownRegistrations() { + usedControllerIds.forEach { O5RegistrationData.remove(it) } + usedControllerIds.clear() + } + + private fun newCertStore(controllerId: Long, withIntermediateCA: Boolean = true, withTlsCertificate: Boolean = true): O5CertificateStore { + usedControllerIds.add(controllerId) + val privateKey = p256KeyGenerator.generatePrivateKey() + val publicKey = p256KeyGenerator.publicFromPrivate(privateKey) + O5RegistrationData.install( + O5RegistrationData( + controllerId = controllerId, + privateKeyHex = privateKey.joinToString("") { "%02x".format(it) }, + publicKeyHex = publicKey.joinToString("") { "%02x".format(it) }, + intermediateCABase64 = if (withIntermediateCA) Base64.getEncoder().encodeToString(byteArrayOf(1, 2, 3, 4)) else "", + tlsCertificateBase64 = if (withTlsCertificate) Base64.getEncoder().encodeToString(byteArrayOf(5, 6, 7, 8)) else "" + ), + source = O5RegistrationData.O5RegistrationSource.DOWNLOADED, + ) + return O5CertificateStore(aapsLogger, p256KeyGenerator, controllerId) + } + + private fun pairingPacket(key: String, payload: ByteArray, sequenceNumber: Byte): MessagePacket = + MessagePacket( + type = MessageType.PAIRING, + source = dummyId, + destination = dummyId, + payload = StringLengthPrefixEncoding.formatKeys(arrayOf(key), arrayOf(payload)), + sequenceNumber = sequenceNumber + ) + + private fun incrementNonce(nonce: ByteArray): ByteArray { + val counter = ByteBuffer.wrap(nonce, 0, 8).order(ByteOrder.LITTLE_ENDIAN).long + val result = nonce.copyOf() + ByteBuffer.wrap(result, 0, 8).order(ByteOrder.LITTLE_ENDIAN).putLong(counter + 1) + return result + } + + /** Replicates O5KeyExchange's private o5GenerateKeys() KDF exactly, so the test can + * independently derive what conf/ltk the code under test will arrive at. */ + private fun deriveConfAndLtk(pdmPublic: ByteArray, podPublic: ByteArray, sharedSecret: ByteArray): Pair { + fun lengthPrefixed(value: Int): ByteArray = ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN).putLong(value.toLong()).array() + val firmwareId = O5KeyExchange.FIRMWARE_ID + val data = lengthPrefixed(firmwareId.size) + firmwareId + + lengthPrefixed(4) + byteArrayOf(0, 0, 0, 0) + + lengthPrefixed(pdmPublic.size) + pdmPublic + + lengthPrefixed(podPublic.size) + podPublic + + lengthPrefixed(sharedSecret.size) + sharedSecret + val digest = MessageDigest.getInstance("SHA-256").digest(data) + return digest.copyOfRange(0, 16) to digest.copyOfRange(16, 32) + } + + private fun aesCcmEncrypt(key: ByteArray, nonce: ByteArray, plaintext: ByteArray): ByteArray { + val cipher = CCMBlockCipher(AESEngine()) + cipher.init(true, AEADParameters(KeyParameter(key), 64, nonce, ByteArray(0))) + val output = ByteArray(plaintext.size + 8) + cipher.processPacket(plaintext, 0, plaintext.size, output, 0) + return output + } + + @Test + fun `o5NegotiateLTK throws when the SP1+SP2 send fails`() { + val certStore = newCertStore(0x10000001L) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendErrorSending("boom")) + + assertThrows(PairingException::class.java) { + O5LTKExchanger(aapsLogger, msgIO, certStore, dummyId, dummyId.increment()).o5NegotiateLTK() + } + } + + @Test + fun `o5NegotiateLTK throws when SPS0 is never received`() { + val certStore = newCertStore(0x10000002L) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + whenever(msgIO.receiveMessage()).thenReturn(null) + + val exception = assertThrows(PairingException::class.java) { + O5LTKExchanger(aapsLogger, msgIO, certStore, dummyId, dummyId.increment()).o5NegotiateLTK() + } + assertThat(exception.message).contains("SPS0") + } + + @Test + fun `o5NegotiateLTK throws when the pod's SPS0 CRC does not match`() { + val certStore = newCertStore(0x10000003L) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + whenever(msgIO.receiveMessage()).thenReturn(pairingPacket("SPS0=", byteArrayOf(0x00, 0x00, 0x09, 0x00, 0x00), sequenceNumber = 2)) + + assertThrows(PairingException::class.java) { + O5LTKExchanger(aapsLogger, msgIO, certStore, dummyId, dummyId.increment()).o5NegotiateLTK() + } + } + + @Test + fun `o5NegotiateLTK throws when SPS1 is never received`() { + val certStore = newCertStore(0x10000004L) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + var callIndex = 0 + whenever(msgIO.receiveMessage()).thenAnswer { + callIndex++ + if (callIndex == 1) { + val header = byteArrayOf(0x00, 0x00, 0x09) + val crc = O5LTKExchanger.crc16XMODEM(header) + pairingPacket("SPS0=", header + byteArrayOf((crc ushr 8).toByte(), (crc and 0xFF).toByte()), sequenceNumber = 2) + } else { + null + } + } + + val exception = assertThrows(PairingException::class.java) { + O5LTKExchanger(aapsLogger, msgIO, certStore, dummyId, dummyId.increment()).o5NegotiateLTK() + } + assertThat(exception.message).contains("SPS1") + } + + @Test + fun `o5NegotiateLTK throws MessageIOException when the pod's SPS1 payload is the wrong size`() { + val certStore = newCertStore(0x10000005L) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + var callIndex = 0 + whenever(msgIO.receiveMessage()).thenAnswer { + callIndex++ + when (callIndex) { + 1 -> { + val header = byteArrayOf(0x00, 0x00, 0x09) + val crc = O5LTKExchanger.crc16XMODEM(header) + pairingPacket("SPS0=", header + byteArrayOf((crc ushr 8).toByte(), (crc and 0xFF).toByte()), sequenceNumber = 2) + } + + 2 -> pairingPacket("SPS1=", ByteArray(10), sequenceNumber = 3) + else -> null + } + } + + assertThrows(MessageIOException::class.java) { + O5LTKExchanger(aapsLogger, msgIO, certStore, dummyId, dummyId.increment()).o5NegotiateLTK() + } + } + + @Test + fun `o5NegotiateLTK completes the full handshake and derives a matching LTK`() { + val certStore = newCertStore(0x10000006L) + val myId = Id.fromLong(certStore.controllerId) + val podId = myId.increment() + + val podPrivate = p256KeyGenerator.generatePrivateKey() + val podPublic = p256KeyGenerator.publicFromPrivate(podPrivate) + val podNonceP0 = ByteArray(16) { (it + 1).toByte() } + + var capturedPdmPublic: ByteArray? = null + var capturedPdmNonceN0: ByteArray? = null + + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenAnswer { invocation -> + val msg = invocation.getArgument(0) + runCatching { StringLengthPrefixEncoding.parseKeys(arrayOf("SPS1="), msg.payload) } + .getOrNull() + ?.takeIf { it[0].size == 80 } + ?.let { parsed -> + capturedPdmPublic = parsed[0].copyOfRange(0, 64) + capturedPdmNonceN0 = parsed[0].copyOfRange(64, 80) + } + MessageSendSuccess + } + + var callIndex = 0 + whenever(msgIO.receiveMessage()).thenAnswer { + callIndex++ + when (callIndex) { + 1 -> { + val header = byteArrayOf(0x00, 0x00, 0x09) + val crc = O5LTKExchanger.crc16XMODEM(header) + pairingPacket("SPS0=", header + byteArrayOf((crc ushr 8).toByte(), (crc and 0xFF).toByte()), sequenceNumber = 2) + } + + 2 -> { + pairingPacket("SPS1=", podPublic + podNonceP0, sequenceNumber = 3) + } + + 3 -> { + val n1 = incrementNonce(requireNotNull(capturedPdmNonceN0)) + val nonce = byteArrayOf(0x02) + podNonceP0.copyOfRange(0, 6) + n1.copyOfRange(0, 6) + val sharedSecret = p256KeyGenerator.computeSharedSecret(podPrivate, requireNotNull(capturedPdmPublic)) + val (conf, _) = deriveConfAndLtk(requireNotNull(capturedPdmPublic), podPublic, sharedSecret) + pairingPacket("SPS2.1=", aesCcmEncrypt(conf, nonce, ByteArray(20)), sequenceNumber = 4) + } + + 4 -> { + val n1 = incrementNonce(requireNotNull(capturedPdmNonceN0)) + val n2 = incrementNonce(n1) + val p1 = incrementNonce(podNonceP0) + val nonce = byteArrayOf(0x02) + p1.copyOfRange(0, 6) + n2.copyOfRange(0, 6) + val sharedSecret = p256KeyGenerator.computeSharedSecret(podPrivate, requireNotNull(capturedPdmPublic)) + val (conf, _) = deriveConfAndLtk(requireNotNull(capturedPdmPublic), podPublic, sharedSecret) + pairingPacket("SPS2=", aesCcmEncrypt(conf, nonce, ByteArray(70)), sequenceNumber = 5) + } + + 5 -> pairingPacket("P0=", byteArrayOf(0xa5.toByte()), sequenceNumber = 6) + else -> null + } + } + + val result = O5LTKExchanger(aapsLogger, msgIO, certStore, myId, podId).o5NegotiateLTK() + + val sharedSecret = p256KeyGenerator.computeSharedSecret(podPrivate, requireNotNull(capturedPdmPublic)) + val (_, expectedLtk) = deriveConfAndLtk(requireNotNull(capturedPdmPublic), podPublic, sharedSecret) + assertThat(result.ltk).isEqualTo(expectedLtk) + assertThat(result.msgSeq).isEqualTo(6.toByte()) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/session/SessionSigningTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/session/SessionSigningTest.kt new file mode 100644 index 000000000000..cdd8e8906c34 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/comm/session/SessionSigningTest.kt @@ -0,0 +1,138 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.comm.session +import app.aaps.pump.omnipod.common.bledriver.comm.session.Session +import app.aaps.pump.omnipod.common.bledriver.comm.session.SessionKeys + +import app.aaps.pump.omnipod.common.bledriver.comm.Id +import app.aaps.pump.omnipod.common.bledriver.comm.Ids +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.EnDecrypt +import app.aaps.pump.omnipod.common.bledriver.comm.endecrypt.Nonce +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessagePacket +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageSendSuccess +import app.aaps.pump.omnipod.common.bledriver.comm.message.MessageType +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5CertificateStore +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.common.bledriver.pod.command.DeactivateCommand +import app.aaps.pump.omnipod.common.bledriver.pod.command.GetStatusCommand +import app.aaps.pump.omnipod.common.bledriver.pod.response.ResponseType +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.util.P256KeyGenerator +import app.aaps.shared.tests.AAPSLoggerTest +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +/** + * Covers [Session]'s O5-only Type-4 (ENCRYPTED_SIGNED) command signing - the fix for real + * O5 pod firmware rejecting insulin-schedule/deactivate/cancel-delivery commands sent as + * plain ENCRYPTED (confirmed against OmnipodKit's BleMessageTransport.swift, see + * `Session.sign()`'s doc comment). Uses a mocked [MessageIO] (the actual BLE I/O boundary, + * same approach as [app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5LTKExchangerTest]) + * plus a real [O5CertificateStore] built from generated P-256 test key material, so the + * signature produced is independently re-verifiable rather than just "some bytes got + * appended". + */ +class SessionSigningTest { + + private val aapsLogger = AAPSLoggerTest() + private val keyGenerator = P256KeyGenerator() + private val usedControllerIds = mutableListOf() + + @AfterEach + fun tearDown() { + usedControllerIds.forEach { O5RegistrationData.remove(it) } + usedControllerIds.clear() + } + + private fun installValidRegistration(controllerId: Long) { + usedControllerIds.add(controllerId) + val privateKey = keyGenerator.generatePrivateKey() + val publicKey = keyGenerator.publicFromPrivate(privateKey) + O5RegistrationData.install( + O5RegistrationData( + controllerId = controllerId, + privateKeyHex = privateKey.toHex(), + publicKeyHex = publicKey.toHex(), + intermediateCABase64 = "", + tlsCertificateBase64 = "" + ), + source = O5RegistrationData.O5RegistrationSource.DOWNLOADED, + ) + } + + private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) } + + private fun buildSession(msgIO: MessageIO, commandSigner: O5CertificateStore?): Session { + val ids = Ids.forController(Id.fromInt(1), Id.fromInt(2)) + val nonce = Nonce(ByteArray(8), 0) + val sessionKeys = SessionKeys(ck = ByteArray(16), nonce = nonce, msgSequenceNumber = 1) + val enDecrypt = EnDecrypt(aapsLogger, nonce, sessionKeys.ck) + return Session(aapsLogger, msgIO, ids, sessionKeys, enDecrypt, commandSigner) + } + + private fun sentPacket(msgIO: MessageIO): MessagePacket { + val captor = argumentCaptor() + verify(msgIO).sendMessage(captor.capture()) + return captor.firstValue + } + + @Test + fun `deactivate command is sent Type-4 signed, with a signature that verifies, when a signer is present`() { + val controllerId = 0x11112222L + installValidRegistration(controllerId) + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + val session = buildSession(msgIO, commandSigner = store) + val cmd = DeactivateCommand.Builder().setUniqueId(1).setSequenceNumber(1).setNonce(0).build() + + session.sendCommand(cmd) + + val sent = sentPacket(msgIO) + assertThat(sent.type).isEqualTo(MessageType.ENCRYPTED_SIGNED) + assertThat(sent.signatureData).isNotNull() + assertThat(sent.signatureData!!.size).isEqualTo(64) + val aad = sent.asByteArray(forEncryption = false).copyOfRange(0, 16) + assertThat( + O5CertificateStore.verifySignature(sent.signatureData!!, aad + sent.payload, store.signingPublicKeyRaw) + ).isTrue() + } + + @Test + fun `a command outside the signed set is sent plain ENCRYPTED even when a signer is present`() { + val controllerId = 0x33334444L + installValidRegistration(controllerId) + val store = O5CertificateStore(aapsLogger, keyGenerator, controllerId) + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + val session = buildSession(msgIO, commandSigner = store) + val cmd = GetStatusCommand.Builder() + .setUniqueId(1).setSequenceNumber(1) + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) + .build() + + session.sendCommand(cmd) + + val sent = sentPacket(msgIO) + assertThat(sent.type).isEqualTo(MessageType.ENCRYPTED) + assertThat(sent.signatureData).isNull() + } + + @Test + fun `a deactivate command is never signed without a commandSigner - matches Dash, which has none`() { + val msgIO = mock() + whenever(msgIO.sendMessage(any())).thenReturn(MessageSendSuccess) + val session = buildSession(msgIO, commandSigner = null) + val cmd = DeactivateCommand.Builder().setUniqueId(1).setSequenceNumber(1).setNonce(0).build() + + session.sendCommand(cmd) + + val sent = sentPacket(msgIO) + assertThat(sent.type).isEqualTo(MessageType.ENCRYPTED) + assertThat(sent.signatureData).isNull() + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/command/aid/O5AidSetupCommandsTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/command/aid/O5AidSetupCommandsTest.kt new file mode 100644 index 000000000000..f97daf408557 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/command/aid/O5AidSetupCommandsTest.kt @@ -0,0 +1,82 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.command.aid + +import app.aaps.pump.omnipod.common.bledriver.comm.session.Session +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.nio.charset.StandardCharsets + +/** + * Verifies the exact byte-for-byte wire format of the 8 O5 AID setup commands (see + * [O5AidSetupCommands]'s class doc) against the values OmnipodKit's own O5AidCommands.swift + * sends - cross-checked there against a real captured O5 pairing's comm log, not just + * protocol documentation. [Session] is mocked directly (a plain, non-open Kotlin class, + * mockable via this project's inline mock maker - same approach already used for + * [app.aaps.pump.omnipod.common.bledriver.comm.message.MessageIO] elsewhere) so this stays + * a pure wire-format test with no AES-CCM/nonce simulation involved. + */ +class O5AidSetupCommandsTest { + + @Test + fun `sends all 8 AID setup commands in order with the exact OmnipodKit wire format`() { + val session = mock() + whenever(session.sendAidSetupCommand(any(), any())).thenReturn(ByteArray(0)) + val before = System.currentTimeMillis() / 1000 + + O5AidSetupCommands.send(session) + + val payloads = argumentCaptor() + val prefixes = argumentCaptor() + verify(session, times(8)).sendAidSetupCommand(payloads.capture(), prefixes.capture()) + val after = System.currentTimeMillis() / 1000 + + val utc = payloads.allValues[0].toString(StandardCharsets.US_ASCII) + assertThat(utc).startsWith("SE255.2=") + val utcSeconds = utc.removePrefix("SE255.2=").toLong() + assertThat(utcSeconds).isAtLeast(before) + assertThat(utcSeconds).isAtMost(after) + assertThat(prefixes.allValues[0]).isEqualTo("ES255.2=") + + assertThat(payloads.allValues[1]).isEqualTo( + "S3.2=".toByteArray(StandardCharsets.US_ASCII) + + byteArrayOf(0x00, 0x03, 0x00, 0x0E, 0x00) + + ",G3.2".toByteArray(StandardCharsets.US_ASCII) + ) + assertThat(prefixes.allValues[1]).isEqualTo("3.2=") + + val expectedTargets = ByteArray(2 + 48 * 4) + expectedTargets[0] = 0x00 + expectedTargets[1] = 0xC0.toByte() + for (slot in 0 until 48) { + val offset = 2 + slot * 4 + expectedTargets[offset] = 0x00 + expectedTargets[offset + 1] = 0x00 + expectedTargets[offset + 2] = 0x00 + expectedTargets[offset + 3] = 0x6E + } + assertThat(payloads.allValues[2]).isEqualTo( + "S3.1=".toByteArray(StandardCharsets.US_ASCII) + expectedTargets + ",G3.1".toByteArray(StandardCharsets.US_ASCII) + ) + assertThat(payloads.allValues[2].size).isEqualTo(204) + assertThat(prefixes.allValues[2]).isEqualTo("3.1=") + + assertThat(payloads.allValues[3]).isEqualTo("S3.9=8,G3.9".toByteArray(StandardCharsets.US_ASCII)) + assertThat(prefixes.allValues[3]).isEqualTo("3.9=") + + assertThat(payloads.allValues[4]).isEqualTo("S3.7=3670015,G3.7".toByteArray(StandardCharsets.US_ASCII)) + assertThat(prefixes.allValues[4]).isEqualTo("3.7=") + + val expectedHistory = "SE2.1=".toByteArray(StandardCharsets.US_ASCII) + + byteArrayOf(0x00, 0xA8.toByte()) + ByteArray(24 * 7) + assertThat(expectedHistory.size).isEqualTo(176) + for (i in 5..7) { + assertThat(payloads.allValues[i]).isEqualTo(expectedHistory) + assertThat(prefixes.allValues[i]).isEqualTo("ES2.1=") + } + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/InMemoryO5PodStateManagerTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/InMemoryO5PodStateManagerTest.kt new file mode 100644 index 000000000000..f8c82d183bd7 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/InMemoryO5PodStateManagerTest.kt @@ -0,0 +1,154 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import java.util.Calendar +import java.util.TimeZone + +/** + * [O5PodStateManager.updateFromActivationTimeResponse]/[O5PodStateManager + * .updateFromTriggeredAlertsResponse] - status pages 5/1's update methods, fetched + * on-demand by [app.aaps.pump.omnipod.omnipod5.O5PumpPlugin] (see its + * `fetchActivationTimeIfNeeded`/`fetchTriggeredAlertsIfNeeded`). + */ +class InMemoryO5PodStateManagerTest { + + @Test + fun `a matching response saves acceptance before a stop changes the sequence`() { + val state = InMemoryO5PodStateManager() + val response = DefaultStatusResponse(hexToBytes("1D1800A02800000463E8")) + state.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 3.0, startedAt = 1000L, + sequenceNumber = response.sequenceNumberOfLastProgrammingCommand + ) + state.updateFromDefaultStatusResponse(response) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + state.pendingDoseCommand = state.pendingDoseCommand!!.copy(bolusCancelRequested = true, bolusCancelSequenceNumber = 6) + state.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A03000000463E8"))) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + } + + @Test + fun `a stop response cannot prove acceptance of an unknown bolus`() { + val state = InMemoryO5PodStateManager() + state.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, requestedUnits = 3.0, + startedAt = 1000L, sequenceNumber = 5, + bolusCancelRequested = true, bolusCancelSequenceNumber = 6 + ) + state.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A03000000463E8"))) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + } + + @Test + fun `above 50 reservoir response does not replace a measured value`() { + val measured = DefaultStatusResponse(hexToBytes("1D1800A02800000463E8")) + val above50 = DefaultStatusResponse(hexToBytes("1D1800A02800000463FF")) + val state = InMemoryO5PodStateManager() + + state.updateFromDefaultStatusResponse(above50) + assertThat(state.reservoirPulsesRemaining).isNull() + + state.updateFromDefaultStatusResponse(measured) + assertThat(state.reservoirPulsesRemaining).isEqualTo(1000.toShort()) + + state.updateFromDefaultStatusResponse(above50) + assertThat(state.reservoirPulsesRemaining).isEqualTo(1000.toShort()) + + state.updateFromAlarmStatusResponse(AlarmStatusResponse(hexToBytes("021602080100000501BD00000003FF01950000000000670A"))) + assertThat(state.reservoirPulsesRemaining).isEqualTo(1000.toShort()) + } + + private fun hexToBytes(hex: String): ByteArray = + ByteArray(hex.length / 2) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() } + + @Test + fun `updateFromActivationTimeResponse sets podActivatedAt and reuses alarmType-alarmTime`() { + val bytes = byteArrayOf( + 0x02, 0x11, 0x05, + 0x14, + 0x00, 0x7D, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, + 0x0F, + 0x1A, + 0x09, + 0x1E + ) + val state = InMemoryO5PodStateManager() + + state.updateFromActivationTimeResponse(PodInfoActivationTimeResponse(bytes)) + + assertThat(state.alarmType).isEqualTo(AlarmType.ALARM_OCCLUDED) + assertThat(state.alarmTime).isEqualTo(125.toShort()) + val activatedAt = requireNotNull(state.podActivatedAt) + val calendar = Calendar.getInstance() + calendar.timeInMillis = activatedAt + assertThat(calendar[Calendar.YEAR]).isEqualTo(2026) + assertThat(calendar[Calendar.MONTH]).isEqualTo(Calendar.JULY) + assertThat(calendar[Calendar.DAY_OF_MONTH]).isEqualTo(15) + assertThat(calendar[Calendar.HOUR_OF_DAY]).isEqualTo(9) + assertThat(calendar[Calendar.MINUTE]).isEqualTo(30) + } + + @Test + fun `updateFromTriggeredAlertsResponse keeps only non-zero slots`() { + val bytes = byteArrayOf( + 0x02, 0x13, 0x01, + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x0A, + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x78, + 0x00, 0x00, + 0x00, 0x00, + 0x01, 0x2C + ) + val state = InMemoryO5PodStateManager() + + state.updateFromTriggeredAlertsResponse(PodInfoTriggeredAlertsResponse(bytes)) + + val triggered = requireNotNull(state.triggeredAlertTimes) + assertThat(triggered).containsExactly( + AlertType.MULTI_COMMAND, 10.toShort(), + AlertType.LOW_RESERVOIR, 120.toShort(), + AlertType.EXPIRATION, 300.toShort() + ) + } + + @Test + fun `sameTimeZone is true while the pod time zone is unknown`() { + val state = InMemoryO5PodStateManager() + + assertThat(state.timeZoneOffset).isNull() + assertThat(state.sameTimeZone).isTrue() + } + + @Test + fun `sameTimeZone follows the phone time zone after the pod time zone is stored`() { + val original = TimeZone.getDefault() + try { + TimeZone.setDefault(TimeZone.getTimeZone("GMT+02:00")) + val state = InMemoryO5PodStateManager() + state.updateTimeZone() + assertThat(state.sameTimeZone).isTrue() + + TimeZone.setDefault(TimeZone.getTimeZone("GMT-05:00")) + assertThat(state.sameTimeZone).isFalse() + + state.reset() + assertThat(state.timeZoneOffset).isNull() + assertThat(state.sameTimeZone).isTrue() + } finally { + TimeZone.setDefault(original) + } + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5BolusAccountingTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5BolusAccountingTest.kt new file mode 100644 index 000000000000..e6d797c41368 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5BolusAccountingTest.kt @@ -0,0 +1,247 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.DeliveryStatus +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +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.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.ValueSource +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.whenever +import java.nio.ByteBuffer + +class O5BolusAccountingTest : TestBase() { + + @Mock lateinit var storage: Preferences + private var savedState: String? = null + + @BeforeEach + fun setup() { + whenever(storage.put(eq(O5StringNonPreferenceKey.PodState), any())).thenAnswer { + savedState = it.getArgument(1) + Unit + } + whenever(storage.getIfExists(O5StringNonPreferenceKey.PodState)).thenAnswer { savedState } + whenever(storage.get(O5StringNonPreferenceKey.PodState)).thenAnswer { savedState ?: "" } + } + + private fun manager(persisted: Boolean): O5PodStateManager = + if (persisted) PersistedO5PodStateManager(aapsLogger, storage) else InMemoryO5PodStateManager() + + private fun status(total: Int, remaining: Int, sequence: Int = 4, delivery: DeliveryStatus = DeliveryStatus.BOLUS_AND_BASAL_ACTIVE) = + DefaultStatusResponse( + ByteBuffer.allocate(10) + .put(0x1d.toByte()) + .put(((delivery.value.toInt() shl 4) or 8).toByte()) + .putInt((total shl 15) or (sequence shl 11) or remaining) + .putInt(1000) + .array() + ) + + private fun pending() = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 1.0, + startedAt = 1000L, + sequenceNumber = 4 + ) + + private fun started(persisted: Boolean) = manager(persisted).also { + it.activationProgress = ActivationProgress.COMPLETED + it.cumulativeBolusPulsesDelivered = 10 + it.updateFromDefaultStatusResponse(status(110, 0, delivery = DeliveryStatus.BASAL_ACTIVE)) + it.pendingDoseCommand = pending() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `active and repeated status add only bolus progress and leave concurrent basal in basal`(persisted: Boolean) { + val state = started(persisted) + state.updateFromDefaultStatusResponse(status(116, 16)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(4) + assertThat(state.basalPulsesDelivered).isEqualTo(102.toShort()) + assertThat(state.basalDrift).isWithin(1e-9).of(0.1) + assertThat(state.lastBolusDeliveredUnits).isNull() + + state.updateFromDefaultStatusResponse(status(116, 16)) + state.updateFromDefaultStatusResponse(status(119, 16)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + assertThat(state.basalPulsesDelivered).isEqualTo(105.toShort()) + + state.updateFromDefaultStatusResponse(status(126, 10)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(20.toShort()) + assertThat(state.basalPulsesDelivered).isEqualTo(106.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `completion status accounts before finalization and remains idempotent after restart`(persisted: Boolean) { + var state = started(persisted) + state.updateFromDefaultStatusResponse(status(114, 16)) + if (persisted) state = manager(true) + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(4) + state.updateFromDefaultStatusResponse(status(114, 16)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + + state.updateFromDefaultStatusResponse(status(130, 0, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(30.toShort()) + assertThat(state.basalPulsesDelivered).isEqualTo(100.toShort()) + assertThat(state.basalDrift).isWithin(1e-9).of(0.0) + if (persisted) state = manager(true) + state.completeBolus(1000L, 1.0, 1.0, 20) + if (persisted) state = manager(true) + state.completeBolus(1000L, 1.0, 1.0, 20) + state.updateFromDefaultStatusResponse(status(130, 0, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(30.toShort()) + assertThat(state.pendingDoseCommand).isNull() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `finalization adds only progress not yet accounted`(persisted: Boolean) { + var state = started(persisted) + state.updateFromDefaultStatusResponse(status(114, 16)) + if (persisted) state = manager(true) + state.completeBolus(1000L, 1.0, 0.4, 8) + state.completeBolus(1000L, 1.0, 0.4, 8) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(18.toShort()) + assertThat(state.lastBolusDeliveredUnits).isEqualTo(0.4) + assertThat(state.pendingDoseCommand).isNull() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `partial cancellation keeps progress through stop retries and restart`(persisted: Boolean) { + var state = started(persisted) + state.updateFromDefaultStatusResponse(status(114, 16)) + state.pendingDoseCommand = state.pendingDoseCommand!!.copy(bolusCancelRequested = true, bolusCancelSequenceNumber = 6) + if (persisted) state = manager(true) + state.updateFromDefaultStatusResponse(status(118, 12, sequence = 6, delivery = DeliveryStatus.BASAL_ACTIVE)) + state.pendingDoseCommand = state.pendingDoseCommand!!.copy(bolusCancelSequenceNumber = 7) + state.updateFromDefaultStatusResponse(status(118, 12, sequence = 7, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(18.toShort()) + assertThat(state.basalPulsesDelivered).isEqualTo(100.toShort()) + if (persisted) state = manager(true) + state.completeBolus(1000L, 1.0, 0.4, 8) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(18.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `lost response can be accounted from matching completion status`(persisted: Boolean) { + val state = started(persisted) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + state.updateFromDefaultStatusResponse(status(130, 0, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(30.toShort()) + assertThat(state.basalPulsesDelivered).isEqualTo(100.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `active delivery is positive evidence even without a matching sequence`(persisted: Boolean) { + val state = started(persisted) + state.updateFromDefaultStatusResponse(status(114, 16, sequence = 9)) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `unmatched inactive and unknown statuses cannot account requested insulin`(persisted: Boolean) { + val state = started(persisted) + state.updateFromDefaultStatusResponse(status(110, 0, sequence = 9, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(10.toShort()) + + state.updateFromDefaultStatusResponse(status(110, 0, delivery = DeliveryStatus.UNKNOWN)) + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(0) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(10.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `stop sequence alone does not prove unknown bolus delivery`(persisted: Boolean) { + var state = started(persisted) + state.pendingDoseCommand = pending().copy(bolusCancelRequested = true, bolusCancelSequenceNumber = 6) + if (persisted) state = manager(true) + state.updateFromDefaultStatusResponse(status(110, 0, sequence = 6, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isFalse() + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(0) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(10.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `saved acceptance does not apply stale remaining pulses from unrelated status`(persisted: Boolean) { + var state = started(persisted) + state.updateFromDefaultStatusResponse(status(114, 16)) + if (persisted) state = manager(true) + state.updateFromDefaultStatusResponse(status(114, 0, sequence = 9, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.pendingDoseCommand!!.confirmedByStatus).isTrue() + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(4) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `remaining count cannot move progress backwards or beyond the requested bolus`(persisted: Boolean) { + val state = started(persisted) + state.updateFromDefaultStatusResponse(status(114, 16)) + state.updateFromDefaultStatusResponse(status(114, 18)) + state.updateFromDefaultStatusResponse(status(114, 21)) + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(4) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `basal correction pulses stay basal in status and finalization`(persisted: Boolean) { + val state = started(persisted) + state.pendingDoseCommand = pending().copy(isBasalCorrection = true) + state.updateFromDefaultStatusResponse(status(114, 16)) + state.updateFromDefaultStatusResponse(status(130, 0, delivery = DeliveryStatus.BASAL_ACTIVE)) + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(0) + state.completeBolus(1000L, 1.0, 1.0, null) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(10.toShort()) + assertThat(state.basalPulsesDelivered).isEqualTo(120.toShort()) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `alarm status shares the ordinary bolus progress accounting`(persisted: Boolean) { + val state = started(persisted) + val bytes = ByteArray(24) + bytes[0] = 2 + bytes[1] = 22 + bytes[3] = 13 + bytes[4] = DeliveryStatus.SUSPENDED.value + ByteBuffer.wrap(bytes).putShort(5, 12).put(7, 4).putShort(8, 118) + val response = AlarmStatusResponse(bytes) + state.updateFromAlarmStatusResponse(response) + state.updateFromAlarmStatusResponse(response) + assertThat(state.cumulativeBolusPulsesDelivered).isEqualTo(18.toShort()) + assertThat(state.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(8) + assertThat(state.basalPulsesDelivered).isEqualTo(100.toShort()) + } + + @Test + fun `older pending state without progress starts at zero and survives replay`() { + started(true) + savedState = requireNotNull(savedState).replace(",\"accountedBolusPulses\":0", "") + val restored = manager(true) + assertThat(restored.pendingDoseCommand!!.accountedBolusPulses).isEqualTo(0) + restored.updateFromDefaultStatusResponse(status(114, 16)) + val restarted = manager(true) + restarted.updateFromDefaultStatusResponse(status(114, 16)) + assertThat(restarted.cumulativeBolusPulsesDelivered).isEqualTo(14.toShort()) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManagerExtensionsTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManagerExtensionsTest.kt new file mode 100644 index 000000000000..21b51ccda4ab --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/O5PodStateManagerExtensionsTest.kt @@ -0,0 +1,359 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.shared.tests.TestBase +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import java.time.Duration +import java.time.ZonedDateTime +import java.util.TimeZone + +/** + * [expiry] reads wall-clock time directly ([ZonedDateTime.now]/[System.currentTimeMillis]) + * rather than an injectable clock, so these tests assert against a tolerance window instead + * of an exact instant - tight enough to catch a wrong formula (wrong sign, wrong field) but + * not flaky on slow CI. The `.minusHours(8)` term is copied verbatim from + * [app.aaps.pump.omnipod.common.bledriver.pod.state.OmnipodDashPodStateManagerImpl.expiry] + * with no explanation found anywhere in this codebase for why it's there - this test locks + * down the current (copied) behavior, it does not claim to justify the 8 hours. + */ +class O5PodStateManagerExtensionsTest : TestBase() { + + private fun mockState( + podLifeInHours: Short? = null, + minutesSinceActivation: Short? = null, + lastStatusResponseReceived: Long? = null + ): O5PodStateManager { + val state = mock() + whenever(state.podLifeInHours).thenReturn(podLifeInHours) + whenever(state.minutesSinceActivation).thenReturn(minutesSinceActivation) + whenever(state.lastStatusResponseReceived).thenReturn(lastStatusResponseReceived) + return state + } + + @Test + fun `expiry is null when podLifeInHours is unknown`() { + val state = mockState(minutesSinceActivation = 0, lastStatusResponseReceived = System.currentTimeMillis()) + + assertThat(state.expiry).isNull() + } + + @Test + fun `expiry is null when minutesSinceActivation is unknown`() { + val state = mockState(podLifeInHours = 72, lastStatusResponseReceived = System.currentTimeMillis()) + + assertThat(state.expiry).isNull() + } + + @Test + fun `expiry is null when no status response has ever been received`() { + val state = mockState(podLifeInHours = 72, minutesSinceActivation = 0) + + assertThat(state.expiry).isNull() + } + + @Test + fun `freshly activated pod expires close to podLifeInHours minus the 8h grace period from now`() { + val state = mockState(podLifeInHours = 72, minutesSinceActivation = 0, lastStatusResponseReceived = System.currentTimeMillis()) + + val expiresAt = requireNotNull(state.expiry) + + val expected = ZonedDateTime.now().plusHours(64) + val diffSeconds = Duration.between(expected, expiresAt).abs().seconds + assertThat(diffSeconds).isLessThan(10) + } + + @Test + fun `elapsed minutesSinceActivation shortens the remaining life`() { + val state = mockState(podLifeInHours = 72, minutesSinceActivation = 60, lastStatusResponseReceived = System.currentTimeMillis()) + + val expiresAt = requireNotNull(state.expiry) + + val expected = ZonedDateTime.now().plusHours(63) + val diffSeconds = Duration.between(expected, expiresAt).abs().seconds + assertThat(diffSeconds).isLessThan(10) + } + + @Test + fun `time elapsed since the last status response is also subtracted`() { + val state = mockState( + podLifeInHours = 72, + minutesSinceActivation = 0, + lastStatusResponseReceived = System.currentTimeMillis() - Duration.ofMinutes(30).toMillis() + ) + + val expiresAt = requireNotNull(state.expiry) + + val expected = ZonedDateTime.now().plusHours(63).plusMinutes(30) + val diffSeconds = Duration.between(expected, expiresAt).abs().seconds + assertThat(diffSeconds).isLessThan(10) + } + + + private fun mockTimeState( + podActivatedAt: Long? = null, + minutesSinceActivation: Short? = null, + timeZoneOffset: Int? = null, + lastStatusResponseReceived: Long? = null + ): O5PodStateManager { + val state = mock() + whenever(state.podActivatedAt).thenReturn(podActivatedAt) + whenever(state.minutesSinceActivation).thenReturn(minutesSinceActivation) + whenever(state.timeZoneOffset).thenReturn(timeZoneOffset) + whenever(state.lastStatusResponseReceived).thenReturn(lastStatusResponseReceived) + return state + } + + @Test + fun `activationTime prefers podActivatedAt when page 5 has been read`() { + val activatedAt = System.currentTimeMillis() - Duration.ofHours(5).toMillis() + val state = mockTimeState( + podActivatedAt = activatedAt, + minutesSinceActivation = 300, + lastStatusResponseReceived = System.currentTimeMillis() + ) + + assertThat(state.activationTime).isEqualTo(activatedAt) + } + + @Test + fun `activationTime falls back to the last status response minus the elapsed minutes`() { + val lastUpdated = System.currentTimeMillis() + val state = mockTimeState(minutesSinceActivation = 120, lastStatusResponseReceived = lastUpdated) + + assertThat(state.activationTime).isEqualTo(lastUpdated - Duration.ofMinutes(120).toMillis()) + } + + @Test + fun `activationTime is null when nothing is known`() { + assertThat(mockTimeState().activationTime).isNull() + assertThat(mockTimeState(minutesSinceActivation = 120).activationTime).isNull() + } + + @Test + fun `time is null until the pod clock time zone is known`() { + val state = mockTimeState( + podActivatedAt = System.currentTimeMillis(), + minutesSinceActivation = 0, + lastStatusResponseReceived = System.currentTimeMillis() + ) + + assertThat(state.time).isNull() + } + + @Test + fun `time on a pod set to the phone time zone matches the phone clock`() { + val now = System.currentTimeMillis() + val state = mockTimeState( + podActivatedAt = now - Duration.ofHours(10).toMillis(), + minutesSinceActivation = 600, + timeZoneOffset = TimeZone.getDefault().getOffset(now), + lastStatusResponseReceived = now + ) + + val podTime = requireNotNull(state.time) + + assertThat(Duration.between(ZonedDateTime.now(), podTime).abs().seconds).isLessThan(10) + assertThat(requireNotNull(state.timeDrift).abs().seconds).isLessThan(10) + } + + @Test + fun `time keeps running while no new status response arrives`() { + val now = System.currentTimeMillis() + val lastUpdated = now - Duration.ofMinutes(30).toMillis() + val state = mockTimeState( + podActivatedAt = lastUpdated - Duration.ofHours(10).toMillis(), + minutesSinceActivation = 600, + timeZoneOffset = TimeZone.getDefault().getOffset(now), + lastStatusResponseReceived = lastUpdated + ) + + val podTime = requireNotNull(state.time) + + assertThat(Duration.between(ZonedDateTime.now(), podTime).abs().seconds).isLessThan(10) + } + + @Test + fun `a pod counter running ahead of the activation anchor shows as drift`() { + val now = System.currentTimeMillis() + val state = mockTimeState( + podActivatedAt = now - Duration.ofHours(10).toMillis(), + minutesSinceActivation = 630, + timeZoneOffset = TimeZone.getDefault().getOffset(now), + lastStatusResponseReceived = now + ) + + val drift = requireNotNull(state.timeDrift) + + assertThat(drift.minusMinutes(30).abs().seconds).isLessThan(10) + } + + @Test + fun `the pod time zone only changes how the time is shown, not the instant`() { + val now = System.currentTimeMillis() + val phoneOffset = TimeZone.getDefault().getOffset(now) + val state = mockTimeState( + podActivatedAt = now - Duration.ofHours(10).toMillis(), + minutesSinceActivation = 600, + timeZoneOffset = phoneOffset - Duration.ofHours(2).toMillis().toInt(), + lastStatusResponseReceived = now + ) + + val podTime = requireNotNull(state.time) + + assertThat(podTime.offset.totalSeconds).isEqualTo(phoneOffset / 1000 - 2 * 3600) + assertThat(Duration.between(ZonedDateTime.now(), podTime).abs().seconds).isLessThan(10) + } + + private fun mockDriftState( + totalPulsesDelivered: Short? = null, + cumulativeBolusPulsesDelivered: Short? = null, + basalExpected: Double? = null + ): O5PodStateManager { + val state = mock() + whenever(state.totalPulsesDelivered).thenReturn(totalPulsesDelivered) + whenever(state.cumulativeBolusPulsesDelivered).thenReturn(cumulativeBolusPulsesDelivered) + whenever(state.basalExpected).thenReturn(basalExpected) + return state + } + + @Test + fun `basalPulsesDelivered is null when either input is unknown`() { + assertThat(mockDriftState(totalPulsesDelivered = 100).basalPulsesDelivered).isNull() + assertThat(mockDriftState(cumulativeBolusPulsesDelivered = 20).basalPulsesDelivered).isNull() + } + + @Test + fun `basalPulsesDelivered and basalDelivered subtract bolus pulses from the pod total`() { + val state = mockDriftState(totalPulsesDelivered = 100, cumulativeBolusPulsesDelivered = 20) + + assertThat(state.basalPulsesDelivered).isEqualTo(80.toShort()) + assertThat(state.basalDelivered).isWithin(1e-9).of(4.0) + } + + @Test + fun `basalDrift is zero when nothing is expected yet - falls back to basalDelivered itself`() { + val state = mockDriftState(totalPulsesDelivered = 100, cumulativeBolusPulsesDelivered = 20, basalExpected = null) + + assertThat(state.basalDrift).isWithin(1e-9).of(0.0) + } + + @Test + fun `basalDrift is positive when more basal was delivered than expected`() { + val state = mockDriftState(totalPulsesDelivered = 100, cumulativeBolusPulsesDelivered = 20, basalExpected = 3.0) + + assertThat(state.basalDrift).isWithin(1e-9).of(1.0) + } + + @Test + fun `basalDrift is negative when less basal was delivered than expected`() { + val state = mockDriftState(totalPulsesDelivered = 100, cumulativeBolusPulsesDelivered = 20, basalExpected = 5.0) + + assertThat(state.basalDrift).isWithin(1e-9).of(-1.0) + } + + + /** Full-day flat-rate program - sidesteps day-boundary/timezone edge cases entirely + * since the rate is constant across every slot the day-loop could add. */ + private fun flatRateProgram(unitsPerHour: Double) = + BasalProgram(listOf(BasalProgram.Segment(0, 48, (unitsPerHour * 100).toInt()))) + + @Test + fun `integrateO5ExpectedDelivery returns null when startTime is after endTime`() { + val now = System.currentTimeMillis() + assertThat( + integrateO5ExpectedDelivery(now, now - 1000, null, null, null, flatRateProgram(1.0)) + ).isNull() + } + + @Test + fun `integrateO5ExpectedDelivery returns null when there is no basal program and no temp basal`() { + val now = System.currentTimeMillis() + assertThat( + integrateO5ExpectedDelivery(now, now + 3600_000L, null, null, null, null) + ).isNull() + } + + @Test + fun `integrateO5ExpectedDelivery integrates a flat basal program over one hour`() { + val now = System.currentTimeMillis() + val result = integrateO5ExpectedDelivery(now, now + 3600_000L, null, null, null, flatRateProgram(1.0)) + + assertThat(requireNotNull(result)).isWithin(1e-6).of(1.0) + } + + @Test + fun `integrateO5ExpectedDelivery uses the temp basal rate for the whole window when it fully covers it`() { + val now = System.currentTimeMillis() + val result = integrateO5ExpectedDelivery( + now, now + 3600_000L, + activeTempBasalStartTime = now, activeTempBasalRate = 2.0, activeTempBasalDurationMinutes = 120, + basalProgram = flatRateProgram(1.0) + ) + + assertThat(requireNotNull(result)).isWithin(1e-6).of(2.0) + } + + @Test + fun `integrateO5ExpectedDelivery blends temp basal and scheduled basal across a boundary`() { + val now = System.currentTimeMillis() + val result = integrateO5ExpectedDelivery( + now, now + 3600_000L, + activeTempBasalStartTime = now, activeTempBasalRate = 2.0, activeTempBasalDurationMinutes = 30, + basalProgram = flatRateProgram(1.0) + ) + + assertThat(requireNotNull(result)).isWithin(1e-6).of(1.5) + } + + + @Test + fun `nextBasalExpected stays null before activation completes`() { + val state = mock() + whenever(state.basalExpected).thenReturn(null) + whenever(state.activationProgress).thenReturn(ActivationProgress.PRIME_COMPLETED) + + assertThat(state.nextBasalExpected(previousUpdate = null, now = System.currentTimeMillis())).isNull() + } + + @Test + fun `nextBasalExpected seeds itself from basalDelivered the first time activation is complete`() { + val state = mock() + whenever(state.basalExpected).thenReturn(null) + whenever(state.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(state.totalPulsesDelivered).thenReturn(100) + whenever(state.cumulativeBolusPulsesDelivered).thenReturn(0) + + val result = state.nextBasalExpected(previousUpdate = null, now = System.currentTimeMillis()) + + assertThat(requireNotNull(result)).isWithin(1e-9).of(5.0) + } + + @Test + fun `nextBasalExpected leaves the value unchanged when there is no previous update to integrate from`() { + val state = mock() + whenever(state.basalExpected).thenReturn(2.0) + + val result = state.nextBasalExpected(previousUpdate = null, now = System.currentTimeMillis()) + + assertThat(requireNotNull(result)).isWithin(1e-9).of(2.0) + } + + @Test + fun `nextBasalExpected integrates the elapsed period onto the existing value`() { + val state = mock() + whenever(state.basalExpected).thenReturn(2.0) + whenever(state.activeTempBasalStartTime).thenReturn(null) + whenever(state.activeTempBasalRate).thenReturn(null) + whenever(state.activeTempBasalDurationMinutes).thenReturn(null) + whenever(state.basalProgram).thenReturn(flatRateProgram(1.0)) + val now = System.currentTimeMillis() + + val result = state.nextBasalExpected(previousUpdate = now - 3600_000L, now = now) + + assertThat(requireNotNull(result)).isWithin(1e-6).of(3.0) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/PersistedO5PodStateManagerTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/PersistedO5PodStateManagerTest.kt new file mode 100644 index 000000000000..563b5cba8180 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/bledriver/pod/state/PersistedO5PodStateManagerTest.kt @@ -0,0 +1,665 @@ +package app.aaps.pump.omnipod.omnipod5.bledriver.pod.state + +import app.aaps.core.data.model.BS +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.logging.LTag +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlertType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BasalProgram +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodConstants +import app.aaps.pump.omnipod.common.bledriver.pod.response.AlarmStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.DefaultStatusResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoActivationTimeResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.PodInfoTriggeredAlertsResponse +import app.aaps.pump.omnipod.common.bledriver.pod.response.VersionResponse +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +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.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.ValueSource +import org.mockito.Mock +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.nio.ByteBuffer + +/** + * Gson+[Preferences] persistence round-trip for [PersistedO5PodStateManager], with a + * particular focus on [BasalProgram] - it has a custom `segments` property getter + * (`Collections.unmodifiableList` wrapper), and no other class in this file's persisted + * state had needed to serialize something with a custom getter before, so this is the + * check that resolves that open question rather than assuming it round-trips correctly. + * + * [Preferences] is backed here by a single in-memory [String] var rather than individual + * stubbed return values, so `store()` followed by a fresh manager's `load()` exercises the + * real Gson serialize/deserialize round trip, not just mock plumbing. + */ +class PersistedO5PodStateManagerTest : TestBase() { + + @Mock lateinit var preferences: Preferences + + private var backingStore: String? = null + + @BeforeEach + fun setUp() { + backingStore = null + whenever(preferences.put(eq(O5StringNonPreferenceKey.PodState), any())).thenAnswer { + backingStore = it.getArgument(1) + Unit + } + whenever(preferences.getIfExists(O5StringNonPreferenceKey.PodState)).thenAnswer { backingStore } + whenever(preferences.get(O5StringNonPreferenceKey.PodState)).thenAnswer { backingStore ?: "" } + } + + private fun newManager() = PersistedO5PodStateManager(aapsLogger, preferences) + + private fun hexToBytes(hex: String): ByteArray = + ByteArray(hex.length / 2) { i -> hex.substring(i * 2, i * 2 + 2).toInt(16).toByte() } + + @Test + fun `fresh manager with no stored state returns defaults`() { + val manager = newManager() + + assertThat(manager.activationProgress).isEqualTo(ActivationProgress.NOT_STARTED) + assertThat(manager.ltk).isNull() + assertThat(manager.basalProgram).isNull() + assertThat(manager.msgSequenceNumber).isEqualTo(1.toByte()) + } + + @Test + fun `basalProgram round-trips through Gson via a fresh manager instance`() { + val program = BasalProgram( + listOf( + BasalProgram.Segment(0, 24, 100), + BasalProgram.Segment(24, 48, 150) + ) + ) + val writer = newManager() + writer.basalProgram = program + + val reader = newManager() + + assertThat(reader.basalProgram).isEqualTo(program) + assertThat(reader.basalProgram!!.segments).hasSize(2) + assertThat(reader.basalProgram!!.segments[0].basalRateInHundredthUnitsPerHour).isEqualTo(100) + assertThat(reader.basalProgram!!.segments[1].basalRateInHundredthUnitsPerHour).isEqualTo(150) + } + + @Test + fun `activationProgress and prime parameters round-trip`() { + val writer = newManager() + writer.activationProgress = ActivationProgress.PRIME_COMPLETED + writer.primePulseRate = 20 + writer.firstPrimeBolusVolume = 52 + writer.secondPrimeBolusVolume = 10 + writer.podLifeInHours = 72 + + val reader = newManager() + + assertThat(reader.activationProgress).isEqualTo(ActivationProgress.PRIME_COMPLETED) + assertThat(reader.primePulseRate).isEqualTo(20.toShort()) + assertThat(reader.firstPrimeBolusVolume).isEqualTo(52.toShort()) + assertThat(reader.secondPrimeBolusVolume).isEqualTo(10.toShort()) + assertThat(reader.podLifeInHours).isEqualTo(72.toShort()) + } + + @Test + fun `pendingDoseCommand round-trips including nested bolusType enum`() { + val pending = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 1.25, + bolusType = BS.Type.SMB, + startedAt = 123456789L, + bolusRecordExpected = true + ) + val writer = newManager() + writer.pendingDoseCommand = pending + + val reader = newManager() + + assertThat(reader.pendingDoseCommand).isEqualTo(pending) + assertThat(reader.pendingDoseCommand!!.bolusType).isEqualTo(BS.Type.SMB) + assertThat(reader.pendingDoseCommand!!.bolusRecordExpected).isTrue() + } + + @Test + fun `pending temp type and exact basal program survive restart`() { + val writer = newManager() + val temp = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.TEMP_BASAL_START, + requestedRate = 0.7, requestedDurationMinutes = 30, startedAt = 1000L, + tempBasalType = PumpSync.TemporaryBasalType.SUPERBOLUS, historyId = 7L + ) + writer.pendingDoseCommand = temp + assertThat(newManager().pendingDoseCommand).isEqualTo(temp) + val program = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BASAL_PROGRAM, startedAt = 2000L, + requestedBasalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 24, 70), BasalProgram.Segment(24, 48, 120))) + ) + writer.pendingDoseCommand = program + assertThat(newManager().pendingDoseCommand).isEqualTo(program) + } + + @Test + fun `status acceptance survives restart and a later cancellation sequence`() { + val writer = newManager() + val response = DefaultStatusResponse(hexToBytes("1D1800A02800000463E8")) + writer.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, requestedUnits = 3.0, + startedAt = 1000L, sequenceNumber = response.sequenceNumberOfLastProgrammingCommand + ) + writer.updateFromDefaultStatusResponse(response) + val restarted = newManager() + assertThat(restarted.pendingDoseCommand!!.confirmedByStatus).isTrue() + restarted.pendingDoseCommand = restarted.pendingDoseCommand!!.copy( + bolusCancelRequested = true, bolusCancelSequenceNumber = 6, bolusCancelHistoryId = 8L + ) + restarted.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A03000000463E8"))) + val afterCancel = newManager() + assertThat(afterCancel.pendingDoseCommand!!.confirmedByStatus).isTrue() + assertThat(afterCancel.pendingDoseCommand!!.bolusCancelRequested).isTrue() + assertThat(afterCancel.pendingDoseCommand!!.bolusCancelSequenceNumber).isEqualTo(6.toShort()) + assertThat(afterCancel.pendingDoseCommand!!.bolusCancelHistoryId).isEqualTo(8L) + } + + @Test + fun `older state without cancel intent is loaded as unknown rather than not cancelled`() { + val writer = newManager() + writer.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, requestedUnits = 1.0, startedAt = 1000L + ) + backingStore = requireNotNull(backingStore).replace(",\"bolusCancelRequested\":false", "") + assertThat(newManager().pendingDoseCommand!!.bolusCancelRequested).isNull() + } + + @Test + fun `dosing state fields round-trip`() { + val writer = newManager() + writer.deliverySuspended = true + writer.lastBolusStartTime = 1_000L + writer.lastBolusRequestedUnits = 2.5 + writer.lastBolusDeliveredUnits = 2.5 + writer.activeTempBasalStartTime = 2_000L + writer.activeTempBasalRate = 0.5 + writer.activeTempBasalDurationMinutes = 30 + + val reader = newManager() + + assertThat(reader.deliverySuspended).isTrue() + assertThat(reader.lastBolusStartTime).isEqualTo(1_000L) + assertThat(reader.lastBolusRequestedUnits).isEqualTo(2.5) + assertThat(reader.lastBolusDeliveredUnits).isEqualTo(2.5) + assertThat(reader.activeTempBasalStartTime).isEqualTo(2_000L) + assertThat(reader.activeTempBasalRate).isEqualTo(0.5) + assertThat(reader.activeTempBasalDurationMinutes).isEqualTo(30.toShort()) + } + + @Test + fun `completeBolus persists accounting and clears pending in one state update`() { + val writer = newManager() + writer.cumulativeBolusPulsesDelivered = 10 + writer.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 1.0, + startedAt = 1_000L + ) + + writer.completeBolus(1_000L, 1.0, 0.75, 15) + + val reader = newManager() + assertThat(reader.cumulativeBolusPulsesDelivered).isEqualTo(25.toShort()) + assertThat(reader.lastBolusDeliveredUnits).isEqualTo(0.75) + assertThat(reader.pendingDoseCommand).isNull() + } + + @Test + fun `completeBolus does not add pulses twice`() { + val manager = newManager() + manager.cumulativeBolusPulsesDelivered = 10 + + manager.completeBolus(1_000L, 1.0, 0.75, 15) + manager.completeBolus(1_000L, 1.0, 0.75, 15) + + assertThat(manager.cumulativeBolusPulsesDelivered).isEqualTo(25.toShort()) + } + + @ParameterizedTest + @CsvSource("10, false", "5, false", "10, true", "5, true") + fun `basal log uses status bolus accounting before completion including after restart`(deliveredPulses: Short, restart: Boolean) { + val logger = mock() + val bytes = hexToBytes("1D1800A02800000463FF") + ByteBuffer.wrap(bytes).putInt(2, (320 shl 15) or (5 shl 11) or (10 - deliveredPulses)) + val response = DefaultStatusResponse(bytes) + var manager = PersistedO5PodStateManager(logger, preferences) + manager.activationProgress = ActivationProgress.COMPLETED + manager.cumulativeBolusPulsesDelivered = 10 + manager.basalExpected = (response.totalPulsesDelivered - 10 - deliveredPulses) * PodConstants.POD_PULSE_BOLUS_UNITS + manager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 0.5, + bolusType = BS.Type.SMB, + startedAt = 1_000L, + sequenceNumber = 5 + ) + + manager.updateFromDefaultStatusResponse(response) + if (restart) manager = PersistedO5PodStateManager(logger, preferences) + manager.updateFromDefaultStatusResponse(response) + + assertThat(manager.cumulativeBolusPulsesDelivered).isEqualTo((10 + deliveredPulses).toShort()) + assertThat(manager.basalDrift).isWithin(1e-9).of(0.0) + assertThat(manager.pendingDoseCommand).isNotNull() + val deliveredUnits = deliveredPulses * PodConstants.POD_PULSE_BOLUS_UNITS + manager.completeBolus(1_000L, 0.5, deliveredUnits, deliveredPulses) + + val message = argumentCaptor() + verify(logger, times(2)).info(eq(LTag.PUMP), message.capture()) + assertThat(message.firstValue).contains("act=%.2fU".format(manager.basalExpected)) + assertThat(message.firstValue).contains("err=%+.4fU".format(0.0)) + assertThat(manager.basalDrift).isWithin(1e-9).of(0.0) + assertThat(newManager().cumulativeBolusPulsesDelivered).isEqualTo((10 + deliveredPulses).toShort()) + assertThat(newManager().pendingDoseCommand).isNull() + } + + @Test + fun `alarm status accounts ordinary bolus pulses before basal logging`() { + val logger = mock() + val response = AlarmStatusResponse(hexToBytes("021602080100000501BD00000003FF01950000000000670A")) + val manager = PersistedO5PodStateManager(logger, preferences) + manager.activationProgress = ActivationProgress.COMPLETED + manager.cumulativeBolusPulsesDelivered = 10 + manager.basalExpected = (response.totalPulsesDelivered - 20) * PodConstants.POD_PULSE_BOLUS_UNITS + manager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, requestedUnits = 0.5, startedAt = 1_000L, + sequenceNumber = response.sequenceNumberOfLastProgrammingCommand + ) + + manager.updateFromAlarmStatusResponse(response) + + val message = argumentCaptor() + verify(logger).info(eq(LTag.PUMP), message.capture()) + assertThat(message.firstValue).contains("err=%+.4fU".format(0.0)) + assertThat(manager.basalDrift).isWithin(1e-9).of(0.0) + assertThat(newManager().cumulativeBolusPulsesDelivered).isEqualTo(20.toShort()) + assertThat(newManager().pendingDoseCommand).isNotNull() + } + + @Test + fun `basal correction pulses are still logged as basal before completion`() { + val logger = mock() + val response = DefaultStatusResponse(hexToBytes("1D1800A02800000463FF")) + val manager = PersistedO5PodStateManager(logger, preferences) + manager.activationProgress = ActivationProgress.COMPLETED + manager.cumulativeBolusPulsesDelivered = 10 + manager.basalExpected = (response.totalPulsesDelivered - 10) * PodConstants.POD_PULSE_BOLUS_UNITS + manager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BOLUS, + requestedUnits = 0.05, startedAt = 1_000L, isBasalCorrection = true + ) + + manager.updateFromDefaultStatusResponse(response) + + val message = argumentCaptor() + verify(logger).info(eq(LTag.PUMP), message.capture()) + assertThat(message.firstValue).startsWith("PUMP_BASAL ") + assertThat(manager.basalDrift).isWithin(1e-9).of(0.0) + assertThat(manager.cumulativeBolusPulsesDelivered).isEqualTo(10.toShort()) + } + + @Test + fun `completeBolus records a new bolus when an older bolus was already completed`() { + val manager = newManager() + manager.cumulativeBolusPulsesDelivered = 10 + manager.lastBolusStartTime = 500L + manager.lastBolusRequestedUnits = 2.0 + manager.lastBolusDeliveredUnits = 2.0 + + manager.completeBolus(1_000L, 1.0, 0.75, 15) + + assertThat(manager.cumulativeBolusPulsesDelivered).isEqualTo(25.toShort()) + assertThat(manager.lastBolusStartTime).isEqualTo(1_000L) + assertThat(manager.lastBolusRequestedUnits).isEqualTo(1.0) + assertThat(manager.lastBolusDeliveredUnits).isEqualTo(0.75) + } + + @Test + fun `store() persists ltk but the logged copy strips it`() { + val writer = newManager() + writer.ltk = byteArrayOf(1, 2, 3, 4) + + val reader = newManager() + assertThat(reader.ltk).isEqualTo(byteArrayOf(1, 2, 3, 4)) + } + + @Test + fun `increaseMessageSequenceNumber wraps at 4 bits`() { + val manager = newManager() + manager.msgSequenceNumber = 0x0e + + manager.increaseMessageSequenceNumber() + assertThat(manager.msgSequenceNumber).isEqualTo(0x0f.toByte()) + + manager.increaseMessageSequenceNumber() + assertThat(manager.msgSequenceNumber).isEqualTo(0x00.toByte()) + } + + @Test + fun `reset clears activation progress, prime parameters, and dosing state`() { + val manager = newManager() + manager.activationProgress = ActivationProgress.COMPLETED + manager.basalProgram = BasalProgram(listOf(BasalProgram.Segment(0, 48, 100))) + manager.primePulseRate = 20 + manager.pendingDoseCommand = O5PodStateManager.PendingDoseCommand( + type = O5PodStateManager.PendingDoseType.BASAL_PROGRAM, startedAt = 1L + ) + manager.controllerId = 0x11223340L + manager.podId = 0x11223341L + manager.ltk = byteArrayOf(9) + + manager.reset() + + assertThat(manager.activationProgress).isEqualTo(ActivationProgress.NOT_STARTED) + assertThat(manager.basalProgram).isNull() + assertThat(manager.primePulseRate).isNull() + assertThat(manager.pendingDoseCommand).isNull() + assertThat(manager.ltk).isNull() + assertThat(manager.controllerId).isEqualTo(0x11223340L) + assertThat(manager.podId).isNull() + assertThat(manager.nextPodId).isEqualTo(0x11223342L) + } + + @Test + fun `connection identity and counters round-trip`() { + val writer = newManager() + writer.bluetoothAddress = "AA:BB:CC:DD:EE:FF" + writer.controllerId = 0x11223344L + writer.podId = 0x55667788L + writer.nextPodId = 0x11223345L + writer.connectionAttempts = 3 + writer.successfulConnections = 2 + writer.eapAkaSequenceNumber = 42L + + val reader = newManager() + + assertThat(reader.bluetoothAddress).isEqualTo("AA:BB:CC:DD:EE:FF") + assertThat(reader.controllerId).isEqualTo(0x11223344L) + assertThat(reader.podId).isEqualTo(0x55667788L) + assertThat(reader.nextPodId).isEqualTo(0x11223345L) + assertThat(reader.connectionAttempts).isEqualTo(3) + assertThat(reader.successfulConnections).isEqualTo(2) + assertThat(reader.eapAkaSequenceNumber).isEqualTo(42L) + } + + @Test + fun `updateFromPairing sets controllerId, podId, ltk, and msgSequenceNumber together and persists`() { + val writer = newManager() + + val ltk = ByteArray(16) { it.toByte() } + writer.updateFromPairing( + controllerId = 0xAABBCCDDL, + podId = 0x11223344L, + pairResult = app.aaps.pump.omnipod.common.bledriver.comm.pair.PairResult(ltk = ltk, msgSeq = 7) + ) + + val reader = newManager() + assertThat(reader.controllerId).isEqualTo(0xAABBCCDDL) + assertThat(reader.podId).isEqualTo(0x11223344L) + assertThat(reader.ltk).isEqualTo(ltk) + assertThat(reader.msgSequenceNumber).isEqualTo(7.toByte()) + } + + @Test + fun `updateFromVersionResponse persists the parsed status-version fields`() { + val response = VersionResponse(hexToBytes("0115040A00010300040208146CC1000954D400FFFFFFFF")) + val writer = newManager() + + writer.updateFromVersionResponse(response) + + val reader = newManager() + assertThat(reader.podStatus).isEqualTo(response.podStatus) + assertThat(reader.firmwareVersion).isNotNull() + assertThat(reader.bleVersion).isNotNull() + assertThat(reader.lotNumber).isEqualTo(response.lotNumber) + assertThat(reader.podSequenceNumber).isEqualTo(response.podSequenceNumber) + assertThat(reader.lastStatusResponseReceived).isNotNull() + } + + @Test + fun `updateFromDefaultStatusResponse persists the parsed status fields`() { + val response = DefaultStatusResponse(hexToBytes("1D1800A02800000463FF")) + val writer = newManager() + + writer.updateFromDefaultStatusResponse(response) + + val reader = newManager() + assertThat(reader.podStatus).isEqualTo(response.podStatus) + assertThat(reader.deliveryStatus).isEqualTo(response.deliveryStatus) + assertThat(reader.totalPulsesDelivered).isEqualTo(response.totalPulsesDelivered) + assertThat(response.reservoirPulsesRemaining).isEqualTo(1023.toShort()) + assertThat(reader.reservoirPulsesRemaining).isNull() + assertThat(reader.minutesSinceActivation).isEqualTo(response.minutesSinceActivation) + } + + @Test + fun `reservoir retains a measured value when a later status reports above 50`() { + val writer = newManager() + writer.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A02800000463E8"))) + writer.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A02800000463FF"))) + writer.updateFromAlarmStatusResponse(AlarmStatusResponse(hexToBytes("021602080100000501BD00000003FF01950000000000670A"))) + + assertThat(newManager().reservoirPulsesRemaining).isEqualTo(1000.toShort()) + } + + @Test + fun `old saved above 50 reservoir reading is not treated as a measured value`() { + val writer = newManager() + writer.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A02800000463E8"))) + backingStore = requireNotNull(backingStore).replace( + "\"reservoirPulsesRemaining\":1000", "\"reservoirPulsesRemaining\":1023" + ) + + assertThat(newManager().reservoirPulsesRemaining).isNull() + } + + @Test + fun `updateFromDefaultStatusResponse seeds basal expected from the new pulse count`() { + val response = DefaultStatusResponse(hexToBytes("1D1800A02800000463FF")) + val manager = newManager() + manager.activationProgress = ActivationProgress.COMPLETED + manager.cumulativeBolusPulsesDelivered = 0 + + manager.updateFromDefaultStatusResponse(response) + + assertThat(manager.basalExpected).isEqualTo( + response.totalPulsesDelivered * PodConstants.POD_PULSE_BOLUS_UNITS + ) + } + + + @Test + fun `isPodKaput is true once a status response reports ALARM`() { + val response = DefaultStatusResponse(hexToBytes("1D1D00A02800000463FF")) + val manager = newManager() + assertThat(manager.isPodKaput).isFalse() + + manager.updateFromDefaultStatusResponse(response) + + assertThat(manager.podStatus).isEqualTo(PodStatus.ALARM) + assertThat(manager.isPodKaput).isTrue() + } + + @Test + fun `isPodKaput is true once a status response reports DEACTIVATED`() { + val manager = newManager() + + manager.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1F00A02800000463FF"))) + + assertThat(manager.podStatus).isEqualTo(PodStatus.DEACTIVATED) + assertThat(manager.isPodKaput).isTrue() + } + + @Test + fun `activation time exceeded is terminal`() { + val manager = newManager() + + manager.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1E00A02800000463FF"))) + + assertThat(manager.podStatus).isEqualTo(PodStatus.LUMP_OF_COAL) + assertThat(manager.isPodActivationTimeExceeded).isTrue() + assertThat(manager.isPodKaput).isTrue() + } + + @Test + fun `isPodKaput stays false for a normally running pod`() { + val manager = newManager() + + manager.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A02800000463FF"))) + + assertThat(manager.podStatus).isEqualTo(PodStatus.RUNNING_ABOVE_MIN_VOLUME) + assertThat(manager.isPodKaput).isFalse() + } + + @Test + fun `updateFromAlarmStatusResponse persists the parsed alarm fields`() { + val response = AlarmStatusResponse(hexToBytes("021602080100000501BD00000003FF01950000000000670A")) + val writer = newManager() + + writer.updateFromAlarmStatusResponse(response) + + val reader = newManager() + assertThat(reader.alarmType).isEqualTo(response.alarmType) + assertThat(reader.alarmTime).isEqualTo(response.alarmTime) + assertThat(reader.occlusionAlarm).isEqualTo(response.occlusionAlarm) + assertThat(reader.podStatusWhenAlarmOccurred).isEqualTo(response.podStatusWhenAlarmOccurred) + assertThat(reader.rssi).isEqualTo(response.rssi) + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `fault reference keeps the first snapshot until reset`(persisted: Boolean) { + var state: O5PodStateManager = if (persisted) newManager() else InMemoryO5PodStateManager() + val bytes = hexToBytes("021602080100000501BD00000003FF01950000000000670A") + state.updateFromAlarmStatusResponse(AlarmStatusResponse(bytes)) + assertThat(state.pdmRef).isNull() + + bytes[10] = AlarmType.ALARM_SYNC_WITHOUT_CLOSED_LOOP.value + state.updateFromAlarmStatusResponse(AlarmStatusResponse(bytes)) + assertThat(state.pdmRef).isEqualTo("19-00006-02251-152") + + if (persisted) state = newManager() + assertThat(state.pdmRef).isEqualTo("19-00006-02251-152") + + bytes[19] = 31 + state.updateFromAlarmStatusResponse(AlarmStatusResponse(bytes)) + state.updateFromDefaultStatusResponse(DefaultStatusResponse(hexToBytes("1D1800A02800000463FF"))) + assertThat(state.pdmRef).isEqualTo("19-00006-02251-152") + if (persisted) assertThat(newManager().pdmRef).isEqualTo("19-00006-02251-152") + + state.reset() + assertThat(state.pdmRef).isNull() + if (persisted) assertThat(newManager().pdmRef).isNull() + } + + @ParameterizedTest + @ValueSource(booleans = [false, true]) + fun `unknown faults do not create a reference`(persisted: Boolean) { + val state = if (persisted) newManager() else InMemoryO5PodStateManager() + val bytes = hexToBytes("021602080100000501BD00000003FF01950000000000670A") + bytes[10] = 0xb0.toByte() + + state.updateFromAlarmStatusResponse(AlarmStatusResponse(bytes)) + + assertThat(state.alarmType).isEqualTo(AlarmType.UNKNOWN) + assertThat(state.pdmRef).isNull() + if (persisted) assertThat(newManager().pdmRef).isNull() + } + + @Test + fun `old state without a fault reference still loads`() { + backingStore = """{"alarmType":"ALARM_OCCLUDED","alarmTime":125}""" + + val state = newManager() + + assertThat(state.alarmType).isEqualTo(AlarmType.ALARM_OCCLUDED) + assertThat(state.alarmTime).isEqualTo(125.toShort()) + assertThat(state.pdmRef).isNull() + } + + @Test + fun `updateFromActivationTimeResponse persists podActivatedAt as an epoch millis Long`() { + val bytes = byteArrayOf( + 0x02, 0x11, 0x05, + 0x14, + 0x00, 0x7D, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x07, + 0x0F, + 0x1A, + 0x09, + 0x1E + ) + val response = PodInfoActivationTimeResponse(bytes) + val writer = newManager() + + writer.updateFromActivationTimeResponse(response) + + val reader = newManager() + assertThat(reader.alarmType).isEqualTo(AlarmType.ALARM_OCCLUDED) + assertThat(reader.alarmTime).isEqualTo(125.toShort()) + val activatedAt = requireNotNull(reader.podActivatedAt) + val calendar = java.util.Calendar.getInstance() + calendar.timeInMillis = activatedAt + assertThat(calendar[java.util.Calendar.YEAR]).isEqualTo(2026) + assertThat(calendar[java.util.Calendar.MONTH]).isEqualTo(java.util.Calendar.JULY) + assertThat(calendar[java.util.Calendar.DAY_OF_MONTH]).isEqualTo(15) + } + + @Test + fun `updateFromTriggeredAlertsResponse persists the AlertType-to-Short map through Gson`() { + val bytes = byteArrayOf( + 0x02, 0x13, 0x01, + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x0A, + 0x00, 0x00, + 0x00, 0x00, + 0x00, 0x78, + 0x00, 0x00, + 0x00, 0x00, + 0x01, 0x2C + ) + val response = PodInfoTriggeredAlertsResponse(bytes) + val writer = newManager() + + writer.updateFromTriggeredAlertsResponse(response) + + val reader = newManager() + val triggered = requireNotNull(reader.triggeredAlertTimes) + assertThat(triggered).containsExactly( + AlertType.MULTI_COMMAND, 10.toShort(), + AlertType.LOW_RESERVOIR, 120.toShort(), + AlertType.EXPIRATION, 300.toShort() + ) + } + + @Test + fun `load() falls back to defaults when the stored JSON is corrupted`() { + backingStore = "{ not valid json" + + val manager = newManager() + + assertThat(manager.activationProgress).isEqualTo(ActivationProgress.NOT_STARTED) + assertThat(manager.ltk).isNull() + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/history/O5HistoryTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/history/O5HistoryTest.kt new file mode 100644 index 000000000000..b1f90b2608dc --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/history/O5HistoryTest.kt @@ -0,0 +1,139 @@ +package app.aaps.pump.omnipod.omnipod5.history + +import app.aaps.core.interfaces.profile.Profile +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BolusType +import app.aaps.pump.omnipod.common.definition.OmnipodCommandType +import app.aaps.pump.omnipod.common.history.data.BasalValuesRecord +import app.aaps.pump.omnipod.common.history.data.BolusRecord +import app.aaps.pump.omnipod.common.history.data.HistoryRecord +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.ResolvedResult +import app.aaps.pump.omnipod.common.history.data.TempBasalRecord +import app.aaps.pump.omnipod.omnipod5.history.database.HistoryRecordDao +import app.aaps.pump.omnipod.omnipod5.history.database.HistoryRecordEntity +import com.google.common.truth.Truth.assertThat +import io.reactivex.rxjava3.core.Completable +import io.reactivex.rxjava3.core.Single +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.mock +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever + +class O5HistoryTest { + + private val dao = mock() + private val mapper = HistoryMapper() + private val history = O5History(dao, mapper) + + private fun entity( + commandType: OmnipodCommandType = OmnipodCommandType.SET_BOLUS, + bolus: BolusRecord? = null, + tempBasal: TempBasalRecord? = null, + basal: BasalValuesRecord? = null + ) = HistoryRecordEntity( + id = 42L, + createdAt = 1_000L, + date = 900L, + commandType = commandType, + initialResult = InitialResult.SENT, + tempBasalRecord = tempBasal, + bolusRecord = bolus, + basalProfileRecord = basal, + totalAmountDelivered = 0.15, + resolvedResult = ResolvedResult.SUCCESS, + resolvedAt = 1_100L + ) + + @Test + fun `mapper preserves shared bolus records and history fields`() { + BolusType.entries.forEach { type -> + val bolus = BolusRecord(0.2, type) + val record = mapper.toDomain(entity(bolus = bolus)) + + assertThat(record).isEqualTo( + HistoryRecord( + id = 42L, + createdAt = 1_000L, + date = 900L, + commandType = OmnipodCommandType.SET_BOLUS, + initialResult = InitialResult.SENT, + record = bolus, + totalAmountDelivered = 0.15, + resolvedResult = ResolvedResult.SUCCESS, + resolvedAt = 1_100L + ) + ) + assertThat(record.pumpId()).isEqualTo(42L) + assertThat(record.displayTimestamp()).isEqualTo(900L) + assertThat(record.isSuccess()).isTrue() + } + } + + @Test + fun `mapper preserves shared temp basal and basal profile records`() { + val tempBasal = TempBasalRecord(30, 0.5) + val basal = BasalValuesRecord(listOf(Profile.ProfileValue(0, 0.8))) + + assertThat(mapper.toDomain(entity(tempBasal = tempBasal)).record).isEqualTo(tempBasal) + assertThat(mapper.toDomain(entity(basal = basal)).record).isEqualTo(basal) + assertThat(mapper.toDomain(entity()).record).isNull() + } + + @Test + fun `unresolved and failed records are not successful`() { + val source = entity() + assertThat(mapper.toDomain(source.copy(resolvedResult = null, resolvedAt = null)).isSuccess()).isFalse() + assertThat(mapper.toDomain(source.copy(resolvedResult = ResolvedResult.FAILURE)).isSuccess()).isFalse() + assertThat(mapper.toDomain(source.copy(initialResult = InitialResult.FAILURE_SENDING)).isSuccess()).isFalse() + } + + @Test + fun `history creates a record with the shared bolus type`() { + val bolus = BolusRecord(0.2, BolusType.BASAL_CORRECTION) + whenever(dao.save(any())).thenReturn(Single.just(42L)) + + val id = history.createRecord( + commandType = OmnipodCommandType.SET_BOLUS, + date = 900L, + bolusRecord = bolus + ).blockingGet() + + val saved = argumentCaptor() + verify(dao).save(saved.capture()) + assertThat(id).isEqualTo(42L) + assertThat(saved.firstValue.bolusRecord).isEqualTo(bolus) + assertThat(saved.firstValue.date).isEqualTo(900L) + assertThat(saved.firstValue.initialResult).isEqualTo(InitialResult.SENT) + assertThat(saved.firstValue.resolvedResult).isNull() + } + + @Test + fun `history reads shared records by id and in lists`() { + val source = entity(bolus = BolusRecord(0.2, BolusType.SMB)) + val expected = mapper.toDomain(source) + whenever(dao.byIdBlocking(42L)).thenReturn(source) + whenever(dao.all()).thenReturn(Single.just(listOf(source))) + whenever(dao.allSince(500L)).thenReturn(Single.just(listOf(source))) + + assertThat(history.getById(42L)).isEqualTo(expected) + assertThat(history.getRecords().blockingGet()).containsExactly(expected) + assertThat(history.getRecordsAfter(500L).blockingGet()).containsExactly(expected) + } + + @Test + fun `history deletes each shared record without changing the entity`() { + val sources = listOf( + entity(bolus = BolusRecord(0.2, BolusType.BASAL_CORRECTION)), + entity(OmnipodCommandType.SET_TEMPORARY_BASAL, tempBasal = TempBasalRecord(30, 0.5)), + entity(OmnipodCommandType.SET_BASAL_PROFILE, basal = BasalValuesRecord(listOf(Profile.ProfileValue(0, 0.8)))) + ) + whenever(dao.delete(any())).thenReturn(Completable.complete()) + + sources.forEach { source -> + history.delete(mapper.toDomain(source)).blockingAwait() + verify(dao).delete(source) + } + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/ConvertersTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/ConvertersTest.kt new file mode 100644 index 000000000000..098fbd87491d --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/history/database/ConvertersTest.kt @@ -0,0 +1,59 @@ +package app.aaps.pump.omnipod.omnipod5.history.database + +import app.aaps.pump.omnipod.common.bledriver.pod.definition.BolusType +import app.aaps.pump.omnipod.common.history.data.InitialResult +import app.aaps.pump.omnipod.common.history.data.ResolvedResult +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test + +class ConvertersTest { + + private val converters = Converters() + + @Test + fun `old basal drift history reads as a shared basal correction`() { + assertThat(converters.toBolusType("BASAL_DRIFT_COMPENSATION")).isEqualTo(BolusType.BASAL_CORRECTION) + assertThat(converters.toBolusType("BASAL_CORRECTION")).isEqualTo(BolusType.BASAL_CORRECTION) + } + + @Test + fun `basal corrections keep the old stored name`() { + assertThat(converters.fromBolusType(BolusType.BASAL_CORRECTION)).isEqualTo("BASAL_DRIFT_COMPENSATION") + } + + @Test + fun `every shared bolus type round trips`() { + BolusType.entries.forEach { type -> + assertThat(converters.toBolusType(converters.fromBolusType(type))).isEqualTo(type) + if (type != BolusType.BASAL_CORRECTION) { + assertThat(converters.fromBolusType(type)).isEqualTo(type.name) + } + } + } + + @Test + fun `null bolus types stay null`() { + assertThat(converters.toBolusType(null)).isNull() + assertThat(converters.fromBolusType(null)).isNull() + } + + @Test + fun `unknown bolus types are rejected`() { + assertThrows(IllegalArgumentException::class.java) { converters.toBolusType("UNKNOWN") } + } + + @Test + fun `shared result states keep their stored names`() { + InitialResult.entries.forEach { result -> + assertThat(converters.fromInitialResult(result)).isEqualTo(result.name) + assertThat(converters.toInitialResult(result.name)).isEqualTo(result) + } + ResolvedResult.entries.forEach { result -> + assertThat(converters.fromResolvedResult(result)).isEqualTo(result.name) + assertThat(converters.toResolvedResult(result.name)).isEqualTo(result) + } + assertThat(converters.toResolvedResult(null)).isNull() + assertThat(converters.fromResolvedResult(null)).isNull() + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportViewModelTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportViewModelTest.kt new file mode 100644 index 000000000000..5259e8a95e40 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialImportViewModelTest.kt @@ -0,0 +1,181 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.common.R +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5RegistrationData +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.security.SecureO5RegistrationStorage +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.InMemoryO5PodStateManager +import app.aaps.pump.omnipod.omnipod5.keys.O5StringNonPreferenceKey +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import java.util.Base64 + +/** + * [O5CredentialImportViewModel] - manipulates the process-wide [O5RegistrationData] registry, + * so every test cleans it up in @BeforeEach/@AfterEach to avoid cross-test pollution (same + * discipline as [app.aaps.pump.omnipod.omnipod5.bledriver.comm.pair.O5CertificateStoreTest] etc). + */ +class O5CredentialImportViewModelTest { + + private val secureO5RegistrationStorage = mock() + private val podStateManager = InMemoryO5PodStateManager() + private val preferences = mock() + private val rh = mock() + private val podStateUpdates = MutableStateFlow("") + + private fun newViewModel() = O5CredentialImportViewModel(secureO5RegistrationStorage, podStateManager, preferences, rh) + + private fun packedCredential(controllerId: Long): String { + val privB64 = Base64.getEncoder().encodeToString(byteArrayOf(1, 2, 3, 4)) + val pubB64 = Base64.getEncoder().encodeToString(byteArrayOf(5, 6, 7, 8)) + return "$controllerId|$privB64|$pubB64||" + } + + @BeforeEach + fun clearRegistrationData() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + O5RegistrationData.allValues.forEach { O5RegistrationData.remove(it.controllerId) } + podStateManager.reset() + podStateUpdates.value = "" + whenever(preferences.observe(O5StringNonPreferenceKey.PodState)).thenReturn(podStateUpdates) + whenever(rh.gs(R.string.omnipod_5_certificate_import_paste_first)).thenReturn("Paste a certificate string first") + whenever(rh.gs(R.string.omnipod_5_certificate_import_empty)).thenReturn("Empty certificate received") + whenever(rh.gs(R.string.omnipod_5_certificate_import_parse_error)).thenReturn("Could not parse that certificate") + whenever(rh.gs(R.string.omnipod_5_certificate_store_remove_blocked)).thenReturn("Certificate can only be removed when there is no active pod") + } + + @AfterEach + fun tearDown() { + O5RegistrationData.allValues.forEach { O5RegistrationData.remove(it.controllerId) } + podStateManager.reset() + Dispatchers.resetMain() + } + + @Test + fun `importCurrentInput fails with a helpful message when the input is blank`() { + val vm = newViewModel() + vm.onInputChanged(" ") + + vm.importCurrentInput() + + assertThat(vm.importResult.value).isInstanceOf(ImportResult.Failure::class.java) + } + + @Test + fun `importCurrentInput fails when the certificate string is malformed`() { + val vm = newViewModel() + vm.onInputChanged("not a valid certificate string") + + vm.importCurrentInput() + + assertThat(vm.importResult.value).isInstanceOf(ImportResult.Failure::class.java) + } + + @Test + fun `importCurrentInput fails when certificate JSON misses a required key`() { + val vm = newViewModel() + vm.onInputChanged("""{"controllerId":"1","privateKey":"a","publicKey":"b","intermediateCA":"c"}""") + + vm.importCurrentInput() + + assertThat(vm.importResult.value).isEqualTo(ImportResult.Failure("Could not parse that certificate")) + } + + @Test + fun `importCurrentInput fails when certificate JSON has a null required key`() { + val vm = newViewModel() + vm.onInputChanged("""{"controllerId":"1","privateKey":null,"publicKey":"b","intermediateCA":"c","tlsCertificate":"d"}""") + + vm.importCurrentInput() + + assertThat(vm.importResult.value).isEqualTo(ImportResult.Failure("Could not parse that certificate")) + } + + @Test + fun `importCurrentInput installs, persists, and reports success for a well-formed certificate`() { + val vm = newViewModel() + val controllerId = 99887766L + vm.onInputChanged(packedCredential(controllerId)) + + vm.importCurrentInput() + + assertThat(vm.importResult.value).isEqualTo(ImportResult.Success(controllerId)) + assertThat(vm.inputText.value).isEmpty() + assertThat(O5RegistrationData.contains(controllerId)).isTrue() + verify(secureO5RegistrationStorage).persistEntry( + O5RegistrationData.get(controllerId)!!, + O5RegistrationData.O5RegistrationSource.IMPORTED + ) + } + + @Test + fun `importCurrentInput updates installedCredentials after a successful import`() { + val vm = newViewModel() + val controllerId = 55443322L + vm.onInputChanged(packedCredential(controllerId)) + + vm.importCurrentInput() + + assertThat(vm.installedCredentials.value).hasSize(1) + assertThat(vm.installedCredentials.value[0].controllerId).isEqualTo(controllerId) + assertThat(vm.installedCredentials.value[0].source).isEqualTo(O5RegistrationData.O5RegistrationSource.IMPORTED) + } + + @Test + fun `onInputChanged updates inputText and clears a stale import result`() { + val vm = newViewModel() + vm.onInputChanged("not valid") + vm.importCurrentInput() + assertThat(vm.importResult.value).isNotEqualTo(ImportResult.None) + + vm.onInputChanged("something new") + + assertThat(vm.inputText.value).isEqualTo("something new") + assertThat(vm.importResult.value).isEqualTo(ImportResult.None) + } + + @Test + fun `removeCredential removes from the registry and persisted storage, then refreshes the list`() { + val vm = newViewModel() + val controllerId = 11223344L + vm.onInputChanged(packedCredential(controllerId)) + vm.importCurrentInput() + assertThat(vm.installedCredentials.value).hasSize(1) + + vm.removeCredential(controllerId) + + assertThat(O5RegistrationData.contains(controllerId)).isFalse() + assertThat(vm.installedCredentials.value).isEmpty() + verify(secureO5RegistrationStorage).removeEntry(controllerId) + } + + @Test + fun `removeCredential does not remove when there is an active pod`() { + val vm = newViewModel() + val controllerId = 11223344L + vm.onInputChanged(packedCredential(controllerId)) + vm.importCurrentInput() + podStateManager.activationProgress = ActivationProgress.COMPLETED + podStateUpdates.value = "active" + + vm.removeCredential(controllerId) + + assertThat(O5RegistrationData.contains(controllerId)).isTrue() + assertThat(vm.installedCredentials.value).hasSize(1) + assertThat(vm.importResult.value).isEqualTo(ImportResult.RemoveBlocked) + verify(secureO5RegistrationStorage, never()).removeEntry(controllerId) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialWebViewClientTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialWebViewClientTest.kt new file mode 100644 index 000000000000..a6c8edd438f7 --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/O5CredentialWebViewClientTest.kt @@ -0,0 +1,64 @@ +package app.aaps.pump.omnipod.omnipod5.ui + +import android.webkit.WebResourceError +import android.webkit.WebResourceRequest +import android.webkit.WebViewClient +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import java.io.IOException + +class O5CredentialWebViewClientTest { + + @Test + fun `main page network errors request the internet dialog`() { + val codes = listOf( + WebViewClient.ERROR_HOST_LOOKUP, + WebViewClient.ERROR_CONNECT, + WebViewClient.ERROR_IO, + WebViewClient.ERROR_TIMEOUT + ) + for (code in codes) { + val failures = mutableListOf() + val client = O5CredentialWebViewClient { failures.add(it) } + + client.onReceivedError(null, request(isMainFrame = true), error(code)) + + assertThat(failures).hasSize(1) + assertThat(failures.single()).isInstanceOf(O5CertificateNetworkException::class.java) + assertThat(failures.single().message).isEqualTo("Page load failed") + } + } + + @Test + fun `subresource errors do not interrupt the certificate page`() { + val failures = mutableListOf() + val client = O5CredentialWebViewClient { failures.add(it) } + + client.onReceivedError(null, request(isMainFrame = false), error(WebViewClient.ERROR_HOST_LOOKUP)) + + assertThat(failures).isEmpty() + } + + @Test + fun `other page errors keep the normal failure flow`() { + val failures = mutableListOf() + val client = O5CredentialWebViewClient { failures.add(it) } + + client.onReceivedError(null, request(isMainFrame = true), error(WebViewClient.ERROR_FAILED_SSL_HANDSHAKE)) + + assertThat(failures).hasSize(1) + assertThat(failures.single()).isInstanceOf(IOException::class.java) + assertThat(failures.single()).isNotInstanceOf(O5CertificateNetworkException::class.java) + } + + private fun request(isMainFrame: Boolean): WebResourceRequest = mock { + whenever(it.isForMainFrame).thenReturn(isMainFrame) + } + + private fun error(code: Int): WebResourceError = mock { + whenever(it.errorCode).thenReturn(code) + whenever(it.description).thenReturn("Page load failed") + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5OverviewViewModelTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5OverviewViewModelTest.kt new file mode 100644 index 000000000000..c834b805cbad --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/compose/O5OverviewViewModelTest.kt @@ -0,0 +1,326 @@ +package app.aaps.pump.omnipod.omnipod5.ui.compose + +import app.aaps.core.interfaces.configuration.Config +import app.aaps.core.interfaces.insulin.ConcentrationHelper +import app.aaps.core.interfaces.pump.PumpInsulin +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.bus.RxBus +import app.aaps.core.interfaces.rx.events.EventPumpStatusChanged +import app.aaps.core.interfaces.rx.events.EventQueueChanged +import app.aaps.core.interfaces.utils.DateUtil +import app.aaps.core.ui.compose.StatusLevel +import app.aaps.core.ui.compose.pump.PumpInfoRow +import app.aaps.pump.omnipod.common.bledriver.pod.definition.ActivationProgress +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.common.bledriver.pod.definition.PodStatus +import app.aaps.pump.omnipod.common.queue.command.CommandResumeDelivery +import app.aaps.pump.omnipod.omnipod5.R +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import com.google.common.truth.Truth.assertThat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource +import org.junit.jupiter.params.provider.EnumSource +import org.mockito.Mock +import org.mockito.MockitoAnnotations +import org.mockito.kotlin.any +import org.mockito.kotlin.eq +import org.mockito.kotlin.whenever +import java.time.Duration +import app.aaps.core.ui.R as CoreUiR +import app.aaps.pump.omnipod.common.R as CommonR + +/** + * Mirrors `DashOverviewViewModelTest`'s pattern for + * O5's [O5OverviewViewModel] - covers [app.aaps.core.ui.compose.pump.PumpOverviewUiState] + * assembly (the initial value produced by `buildUiState()`), including action visibility + * before activation and while delivery is running or suspended. + */ +@OptIn(ExperimentalCoroutinesApi::class) +internal class O5OverviewViewModelTest { + + @Mock private lateinit var rh: ResourceHelper + @Mock private lateinit var podStateManager: O5PodStateManager + @Mock private lateinit var commandQueue: CommandQueue + @Mock private lateinit var rxBus: RxBus + @Mock private lateinit var dateUtil: DateUtil + @Mock private lateinit var config: Config + @Mock private lateinit var ch: ConcentrationHelper + @BeforeEach + fun setUp() { + MockitoAnnotations.openMocks(this) + Dispatchers.setMain(UnconfinedTestDispatcher()) + + whenever(rxBus.toFlow(EventPumpStatusChanged::class)).thenReturn(emptyFlow()) + whenever(rxBus.toFlow(EventQueueChanged::class)).thenReturn(emptyFlow()) + + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.NOT_STARTED) + + whenever(rh.gs(any())).thenReturn("label") + whenever(rh.gs(any(), any(), any())).thenReturn("label") + whenever(dateUtil.dateAndTimeString(any())).thenReturn("date") + whenever(ch.insulinAmountString(any())).thenReturn("0 U") + } + + @AfterEach + fun tearDown() { + Dispatchers.resetMain() + } + + private fun createViewModel() = O5OverviewViewModel(rh, podStateManager, commandQueue, rxBus, dateUtil, config, ch) + + @ParameterizedTest + @CsvSource( + "ALARM_EMPTY_RESERVOIR, reservoir_empty", + "ALARM_ALERT0, auto_off", + "ALARM_PUMP_EXPIRED, pod_expired", + "ALARM_OCCLUDED, occluded", + "ALARM_SYNC_WITHOUT_CLOSED_LOOP, pod_error" + ) + fun faultCategory_showsPdmText_andOnlyExpectedCategoriesShowReference(alarm: AlarmType, resourceSuffix: String) { + val ref = "19-00006-02251-152" + val templateRes = when (resourceSuffix) { + "reservoir_empty" -> R.string.omnipod_o5_pdm_notification_reservoir_empty + "auto_off" -> R.string.omnipod_o5_pdm_notification_auto_off + "pod_expired" -> R.string.omnipod_o5_pdm_notification_pod_expired + "occluded" -> R.string.omnipod_o5_pdm_notification_occluded + "pod_error" -> R.string.omnipod_o5_pdm_notification_pod_error + else -> error("unexpected resourceSuffix $resourceSuffix") + } + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(podStateManager.pdmRef).thenReturn(ref) + whenever(rh.gs(any())).thenAnswer { invocation -> + if (invocation.getArgument(0) == CommonR.string.omnipod_common_pdm_notification_label) "PDM Notification" else "label" + } + whenever(rh.gs(templateRes)).thenReturn("templated $resourceSuffix") + whenever(rh.gs(CommonR.string.omnipod_common_pdm_ref, ref)).thenReturn("Ref: $ref") + + val row = createViewModel().uiState.value.infoRows.filterIsInstance().single { it.label == "PDM Notification" } + + val expected = if (resourceSuffix == "pod_expired" || resourceSuffix == "pod_error") { + "templated $resourceSuffix\n\nRef: $ref" + } else { + "templated $resourceSuffix" + } + assertThat(row.value).isEqualTo(expected) + } + + @ParameterizedTest + @EnumSource(AlarmType::class, names = ["NONE", "UNKNOWN", "ALARM_OCCLUDED"]) + fun missingReference_doesNotShowPdmRow(alarm: AlarmType) { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(rh.gs(CommonR.string.omnipod_common_pdm_notification_label)).thenReturn("PDM Notification") + + val rows = createViewModel().uiState.value.infoRows.filterIsInstance() + + assertThat(rows.none { it.label == "PDM Notification" }).isTrue() + } + + @Test + fun faultCode_usesUnsignedValue_andKeepsFaultTime() { + val alarm = AlarmType.ALARM_SYNC_WITHOUT_CLOSED_LOOP + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.alarmType).thenReturn(alarm) + whenever(podStateManager.alarmTime).thenReturn(100) + whenever(podStateManager.minutesSinceActivation).thenReturn(100) + whenever(rh.gs(CoreUiR.string.errors)).thenReturn("Errors") + whenever(rh.gs(CommonR.string.omnipod_common_pod_status_pod_fault_description, 152, alarm.toString())).thenReturn("Pod Fault: 152 $alarm") + whenever(rh.gs(CommonR.string.omnipod_common_moments_ago)).thenReturn("moments ago") + whenever(rh.gs(CommonR.string.omnipod_common_pod_fault_time_label)).thenReturn("Fault Occurred") + whenever(rh.gs(CommonR.string.omnipod_common_two_strings_concatenated_by_colon, "Fault Occurred", "moments ago")).thenReturn("Fault Occurred: moments ago") + + val row = createViewModel().uiState.value.infoRows.filterIsInstance().single { it.label == "Errors" } + + assertThat(row.value).isEqualTo("Pod Fault: 152 $alarm\nFault Occurred: moments ago") + assertThat(row.level).isEqualTo(StatusLevel.CRITICAL) + } + + @Test + fun preActivation_buildsPlaceholderRows_criticalPodStatus_andOffersActivate() { + whenever(rh.gs(CommonR.string.omnipod_common_overview_pod_status)).thenReturn("Pod status") + whenever(rh.gs(CommonR.string.omnipod_common_overview_pod_expiry_date)).thenReturn("Pod expires") + whenever(rh.gs(CommonR.string.omnipod_common_overview_pod_hard_end_date)).thenReturn("Pod hard end") + whenever(rh.gs(CommonR.string.omnipod_common_pod_management_button_activate_pod)).thenReturn("Activate pod") + whenever(rh.gs(CoreUiR.string.refresh)).thenReturn("Refresh") + + val state = createViewModel().uiState.value + + assertThat(state.infoRows).isNotEmpty() + assertThat(state.statusBanner).isNull() + assertThat(state.queueStatus).isNull() + + val podStatusRow = state.infoRows.filterIsInstance().first { it.label == "Pod status" } + assertThat(podStatusRow.level).isEqualTo(StatusLevel.CRITICAL) + + val podExpiresIndex = state.infoRows.indexOfFirst { it is PumpInfoRow && it.label == "Pod expires" } + val podHardEndRow = state.infoRows.filterIsInstance().first { it.label == "Pod hard end" } + assertThat(podHardEndRow.value).isEqualTo("-") + assertThat(state.infoRows.indexOf(podHardEndRow)).isEqualTo(podExpiresIndex + 1) + + val refresh = state.primaryActions.first { it.label == "Refresh" } + assertThat(refresh.enabled).isFalse() + val activate = state.managementActions.first { it.label == "Activate pod" } + assertThat(activate.visible).isTrue() + } + + @Test + fun activePod_hardEndIsEightHoursAfterExpiry() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.podLifeInHours).thenReturn(16.toShort()) + whenever(podStateManager.minutesSinceActivation).thenReturn(0.toShort()) + whenever(podStateManager.lastStatusResponseReceived).thenReturn(System.currentTimeMillis()) + whenever(rh.gs(CommonR.string.omnipod_common_overview_pod_expiry_date)).thenReturn("Pod expires") + whenever(rh.gs(CommonR.string.omnipod_common_overview_pod_hard_end_date)).thenReturn("Pod hard end") + whenever(dateUtil.dateAndTimeString(any())).thenAnswer { invocation -> invocation.getArgument(0).toString() } + + val rows = createViewModel().uiState.value.infoRows.filterIsInstance() + val expiryValue = rows.first { it.label == "Pod expires" }.value.toLong() + val hardEndValue = rows.first { it.label == "Pod hard end" }.value.toLong() + + assertThat(hardEndValue - expiryValue).isEqualTo(Duration.ofHours(8).toMillis()) + } + + @Test + fun noConnectionAttemptsYet_showsPlaceholderBluetoothQuality() { + whenever(rh.gs(CommonR.string.omnipod_common_overview_bluetooth_connection_quality)).thenReturn("BT quality") + whenever(podStateManager.connectionAttempts).thenReturn(0) + + val state = createViewModel().uiState.value + + val btQualityRow = state.infoRows.filterIsInstance().first { it.label == "BT quality" } + assertThat(btQualityRow.value).isEqualTo("-") + } + + @Test + fun connectionQuality_reportsSuccessfulOverAttemptedRatio() { + whenever(rh.gs(CommonR.string.omnipod_common_overview_bluetooth_connection_quality)).thenReturn("BT quality") + whenever(podStateManager.connectionAttempts).thenReturn(10) + whenever(podStateManager.successfulConnections).thenReturn(8) + + val state = createViewModel().uiState.value + + val btQualityRow = state.infoRows.filterIsInstance().first { it.label == "BT quality" } + assertThat(btQualityRow.value).contains("8/10") + } + + @Test + fun activatedPod_offersDeactivateNotActivate() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(rh.gs(CommonR.string.omnipod_common_pod_management_button_activate_pod)).thenReturn("Activate pod") + whenever(rh.gs(CommonR.string.omnipod_common_pod_management_button_deactivate_pod)).thenReturn("Deactivate pod") + + val state = createViewModel().uiState.value + + val activate = state.managementActions.first { it.label == "Activate pod" } + assertThat(activate.visible).isFalse() + val deactivate = state.managementActions.first { it.label == "Deactivate pod" } + assertThat(deactivate.visible).isTrue() + } + + @Test + fun suspendedActivePod_offersResumeNotSuspend() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.podStatus).thenReturn(PodStatus.RUNNING_ABOVE_MIN_VOLUME) + whenever(podStateManager.deliverySuspended).thenReturn(true) + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_resume_delivery)).thenReturn("Resume") + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_suspend_delivery)).thenReturn("Suspend") + + val state = createViewModel().uiState.value + + val resume = state.primaryActions.first { it.label == "Resume" } + assertThat(resume.visible).isTrue() + assertThat(resume.enabled).isTrue() + assertThat(state.primaryActions.none { it.label == "Suspend" }).isTrue() + } + + @Test + fun runningActivePod_offersNeitherSuspendNorResume() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.podStatus).thenReturn(PodStatus.RUNNING_ABOVE_MIN_VOLUME) + whenever(podStateManager.deliverySuspended).thenReturn(false) + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_resume_delivery)).thenReturn("Resume") + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_suspend_delivery)).thenReturn("Suspend") + + val state = createViewModel().uiState.value + + assertThat(state.primaryActions.first { it.label == "Resume" }.visible).isFalse() + assertThat(state.primaryActions.none { it.label == "Suspend" }).isTrue() + } + + @Test + fun suspendedActivePod_busyQueue_disablesResume() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.podStatus).thenReturn(PodStatus.RUNNING_ABOVE_MIN_VOLUME) + whenever(podStateManager.deliverySuspended).thenReturn(true) + whenever(commandQueue.size()).thenReturn(1) + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_resume_delivery)).thenReturn("Resume") + + val resume = createViewModel().uiState.value.primaryActions.first { it.label == "Resume" } + + assertThat(resume.visible).isTrue() + assertThat(resume.enabled).isFalse() + } + + @Test + fun activePod_resumeQueued_keepsResumeVisible() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.podStatus).thenReturn(PodStatus.RUNNING_ABOVE_MIN_VOLUME) + whenever(podStateManager.deliverySuspended).thenReturn(false) + whenever(commandQueue.isCustomCommandInQueue(CommandResumeDelivery::class)).thenReturn(true) + whenever(commandQueue.size()).thenReturn(1) + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_resume_delivery)).thenReturn("Resume") + + val resume = createViewModel().uiState.value.primaryActions.first { it.label == "Resume" } + + assertThat(resume.visible).isTrue() + assertThat(resume.enabled).isFalse() + } + + @Test + fun preActivation_suspendedState_doesNotOfferResume() { + whenever(podStateManager.deliverySuspended).thenReturn(true) + whenever(rh.gs(CommonR.string.omnipod_common_overview_button_resume_delivery)).thenReturn("Resume") + + val resume = createViewModel().uiState.value.primaryActions.first { it.label == "Resume" } + + assertThat(resume.visible).isFalse() + } + + @Test + fun above50Reservoir_showsOver50RatherThanAnExactAmount() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(null) + whenever(rh.gs(CoreUiR.string.reservoir_label)).thenReturn("Reservoir") + whenever(rh.gs(eq(CoreUiR.string.overview_reservoir_concentration_value_over), eq("0 U"))).thenReturn(">50 U") + + val row = createViewModel().uiState.value.infoRows.filterIsInstance().first { it.label == "Reservoir" } + + assertThat(row.value).isEqualTo(">50 U") + assertThat(row.level).isEqualTo(StatusLevel.NORMAL) + } + + @Test + fun measuredReservoir_showsMeasuredAmount() { + whenever(podStateManager.activationProgress).thenReturn(ActivationProgress.COMPLETED) + whenever(podStateManager.reservoirPulsesRemaining).thenReturn(250) + whenever(rh.gs(CoreUiR.string.reservoir_label)).thenReturn("Reservoir") + whenever(ch.insulinAmountString(any())).thenReturn("12.5 U") + whenever(ch.fromPump(any(), eq(false))).thenReturn(12.5) + + val row = createViewModel().uiState.value.infoRows.filterIsInstance().first { it.label == "Reservoir" } + + assertThat(row.value).isEqualTo("12.5 U") + assertThat(row.level).isEqualTo(StatusLevel.CRITICAL) + } +} diff --git a/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/wizard/compose/O5OmnipodWizardViewModelTest.kt b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/wizard/compose/O5OmnipodWizardViewModelTest.kt new file mode 100644 index 000000000000..722fcfaa4bfd --- /dev/null +++ b/pump/omnipod/omnipod5/src/test/kotlin/app/aaps/pump/omnipod/omnipod5/ui/wizard/compose/O5OmnipodWizardViewModelTest.kt @@ -0,0 +1,277 @@ +package app.aaps.pump.omnipod.omnipod5.ui.wizard.compose +import app.aaps.pump.omnipod.common.ui.wizard.compose.OmnipodWizardStep +import app.aaps.pump.omnipod.common.ui.wizard.compose.ActivationType +import app.aaps.pump.omnipod.common.ui.wizard.compose.ActionState + +import app.aaps.core.data.model.ICfg +import app.aaps.core.data.model.TE +import app.aaps.core.data.ue.Sources +import app.aaps.core.interfaces.db.PersistenceLayer +import app.aaps.core.interfaces.insulin.InsulinManager +import app.aaps.core.interfaces.logging.AAPSLogger +import app.aaps.core.interfaces.notifications.NotificationManager +import app.aaps.core.interfaces.profile.ProfileFunction +import app.aaps.core.interfaces.profile.ProfileRepository +import app.aaps.core.interfaces.pump.PumpEnactResult +import app.aaps.core.interfaces.pump.PumpSync +import app.aaps.core.interfaces.queue.CommandQueue +import app.aaps.core.interfaces.resources.ResourceHelper +import app.aaps.core.interfaces.rx.AapsSchedulers +import app.aaps.core.interfaces.rx.bus.RxBus +import app.aaps.core.keys.BooleanKey +import app.aaps.core.keys.interfaces.Preferences +import app.aaps.pump.omnipod.omnipod5.bledriver.comm.O5BleManager +import app.aaps.pump.omnipod.common.bledriver.pod.definition.AlarmType +import app.aaps.pump.omnipod.omnipod5.bledriver.pod.state.O5PodStateManager +import app.aaps.pump.omnipod.omnipod5.history.O5History +import app.aaps.shared.tests.rx.TestAapsSchedulers +import com.google.common.truth.Truth.assertThat +import io.reactivex.rxjava3.core.Observable +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.mockito.Answers +import org.mockito.Mock +import org.mockito.MockitoAnnotations +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.inOrder +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +/** + * Mirrors [app.aaps.pump.omnipod.dash.ui.wizard.compose.DashOmnipodWizardViewModelTest]'s + * pattern for O5's concrete [O5OmnipodWizardViewModel] - covers the synchronous, + * pure wizard-navigation and selection logic inherited from + * [OmnipodWizardViewModel] plus the O5-specific overrides. The BLE steps of + * `doInitializePod()`/`doInsertCannula()` are not exercised here, only that they mark the + * activation as running for the queue and clear it again on failure. + * + * The VM's `init{}` launches a coroutine via `viewModelScope`. A `StandardTestDispatcher` + * as Main defers that coroutine (no `advanceUntilIdle()` here), so construction stays + * clean and every assertion runs against the deterministic default state. + */ +@OptIn(ExperimentalCoroutinesApi::class) +internal class O5OmnipodWizardViewModelTest { + + @Mock private lateinit var bleManager: O5BleManager + @Mock private lateinit var podStateManager: O5PodStateManager + @Mock private lateinit var preferences: Preferences + @Mock private lateinit var rh: ResourceHelper + @Mock private lateinit var commandQueue: CommandQueue + @Mock private lateinit var notificationManager: NotificationManager + @Mock private lateinit var history: O5History + @Mock private lateinit var pumpSync: PumpSync + @Mock private lateinit var insulinManager: InsulinManager + @Mock private lateinit var profileFunction: ProfileFunction + @Mock private lateinit var profileRepository: ProfileRepository + @Mock private lateinit var persistenceLayer: PersistenceLayer + private val enactResult: PumpEnactResult = mock(defaultAnswer = Answers.RETURNS_SELF).also { + whenever(it.comment).thenReturn("error") + } + private val pumpEnactResultProvider: () -> PumpEnactResult = { enactResult } + @Mock private lateinit var logger: AAPSLogger + @Mock private lateinit var rxBus: RxBus + private val aapsSchedulers: AapsSchedulers = TestAapsSchedulers() + + private lateinit var sut: O5OmnipodWizardViewModel + + @BeforeEach + fun setUp() { + MockitoAnnotations.openMocks(this) + Dispatchers.setMain(StandardTestDispatcher()) + sut = O5OmnipodWizardViewModel( + bleManager, podStateManager, preferences, rh, commandQueue, + notificationManager, history, pumpSync, insulinManager, persistenceLayer, + profileFunction, profileRepository, pumpEnactResultProvider, logger, aapsSchedulers, rxBus + ) + } + + @AfterEach + fun tearDown() = Dispatchers.resetMain() + + @Test + fun defaultState_isIdleAndUninitialized() { + assertThat(sut.currentStep.value).isNull() + assertThat(sut.totalSteps.value).isEqualTo(0) + assertThat(sut.currentStepIndex.value).isEqualTo(0) + assertThat(sut.canGoBack.value).isFalse() + assertThat(sut.actionState.value).isEqualTo(ActionState.Idle) + assertThat(sut.ready.value).isFalse() + assertThat(sut.availableInsulins.value).isEmpty() + assertThat(sut.selectedInsulin.value).isNull() + assertThat(sut.showInsulinStep).isFalse() + assertThat(sut.siteLocation.value).isEqualTo(TE.Location.NONE) + assertThat(sut.siteArrow.value).isEqualTo(TE.Arrow.NONE) + } + + @Test + fun pumpSource_isOmnipod5() { + assertThat(sut.pumpSource).isEqualTo(Sources.Omnipod5) + } + + @Test + fun isPodInAlarm_reflectsAlarmType_unlikeDashsUnimplementedStub() { + whenever(podStateManager.alarmType).thenReturn(null) + assertThat(sut.isPodInAlarm()).isFalse() + + whenever(podStateManager.alarmType).thenReturn(AlarmType.ALARM_EMPTY_RESERVOIR) + assertThat(sut.isPodInAlarm()).isTrue() + } + + @Test + fun podStateQueries_reflectActivationTimeoutAndPairingState() { + whenever(podStateManager.isPodActivationTimeExceeded).thenReturn(true) + whenever(podStateManager.ltk).thenReturn(null) + + assertThat(sut.isPodActivationTimeExceeded()).isTrue() + assertThat(sut.isPodDeactivatable()).isFalse() + + whenever(podStateManager.ltk).thenReturn(ByteArray(16)) + whenever(podStateManager.controllerId).thenReturn(0x11223340L) + whenever(podStateManager.podId).thenReturn(0x11223341L) + + assertThat(sut.isPodDeactivatable()).isTrue() + } + + @Test + fun podStateQueries_doNotReportActivationTimeoutForOtherStates() { + whenever(podStateManager.isPodActivationTimeExceeded).thenReturn(false) + + assertThat(sut.isPodActivationTimeExceeded()).isFalse() + } + + @Test + fun profileGateStep_hasNoBodyTextResource() { + assertThat(sut.getTextForStep(OmnipodWizardStep.PROFILE_GATE)).isEqualTo(0) + } + + @Test + fun everyWizardStep_hasATitleAndTextResourceMapping() { + for (step in OmnipodWizardStep.entries) { + sut.getTitleForStep(step) + sut.getTextForStep(step) + } + } + + @Test + fun initializeDeactivation_buildsThreeStepFlow() { + sut.initializeDeactivation() + + assertThat(sut.totalSteps.value).isEqualTo(3) + assertThat(sut.currentStepIndex.value).isEqualTo(0) + assertThat(sut.currentStep.value).isEqualTo(OmnipodWizardStep.START_POD_DEACTIVATION) + assertThat(sut.canGoBack.value).isFalse() + + sut.moveToNext() + assertThat(sut.currentStepIndex.value).isEqualTo(1) + assertThat(sut.currentStep.value).isEqualTo(OmnipodWizardStep.DEACTIVATE_POD) + + sut.moveToNext() + assertThat(sut.currentStepIndex.value).isEqualTo(2) + assertThat(sut.currentStep.value).isEqualTo(OmnipodWizardStep.POD_DEACTIVATED) + } + + @Test + fun initializeActivationLong_buildsFullFlow_withoutOptionalSteps() { + whenever(preferences.get(BooleanKey.SiteRotationManagePump)).thenReturn(false) + + sut.initializeActivation(ActivationType.LONG) + + assertThat(sut.totalSteps.value).isEqualTo(5) + assertThat(sut.currentStepIndex.value).isEqualTo(0) + assertThat(sut.currentStep.value).isEqualTo(OmnipodWizardStep.START_POD_ACTIVATION) + + sut.moveToNext() + assertThat(sut.currentStep.value).isEqualTo(OmnipodWizardStep.INITIALIZE_POD) + } + + @Test + fun selectInsulin_updatesSelectedInsulin() { + val insulin: ICfg = mock() + + sut.selectInsulin(insulin) + + assertThat(sut.selectedInsulin.value).isSameInstanceAs(insulin) + } + + @Test + fun selectProfile_updatesSelectedProfile() { + sut.selectProfile("Default") + + assertThat(sut.selectedProfile.value).isEqualTo("Default") + } + + @Test + fun updateSiteLocationAndArrow_areReflectedInSelectors() { + sut.updateSiteLocation(TE.Location.SIDE_RIGHT_UPPER_ARM) + sut.updateSiteArrow(TE.Arrow.UP) + + assertThat(sut.siteLocation.value).isEqualTo(TE.Location.SIDE_RIGHT_UPPER_ARM) + assertThat(sut.siteArrow.value).isEqualTo(TE.Arrow.UP) + assertThat(sut.getSelectedSiteLocation()).isEqualTo(TE.Location.SIDE_RIGHT_UPPER_ARM) + assertThat(sut.getSelectedSiteArrow()).isEqualTo(TE.Arrow.UP) + } + + /** + * The wizard talks to the pod outside the command queue. [O5BleManager.isActivationRunning] is + * what keeps the queue away from the BLE link meanwhile (Dash #5219), so it must be set before + * pairing starts and cleared on every way out, or the queue stays blocked for ever. + */ + @Test + fun initializePod_marksActivationRunningDuringPairing_andClearsItWhenPairingFails() { + whenever(podStateManager.ltk).thenReturn(null) + whenever(bleManager.pairNewPod()).thenReturn(Observable.error(IllegalStateException("pairing failed"))) + + runStep(OmnipodWizardStep.INITIALIZE_POD) + + inOrder(bleManager) { + verify(bleManager).isActivationRunning = true + verify(bleManager).pairNewPod() + verify(bleManager).isActivationRunning = false + } + } + + @Test + fun initializePod_clearsActivationRunningWhenPairingThrows() { + whenever(podStateManager.ltk).thenReturn(null) + whenever(bleManager.pairNewPod()).doAnswer { throw IllegalStateException("no adapter") } + + runStep(OmnipodWizardStep.INITIALIZE_POD) + + inOrder(bleManager) { + verify(bleManager).isActivationRunning = true + verify(bleManager).isActivationRunning = false + } + } + + @Test + fun insertCannula_marksActivationRunning_andClearsItWhenItFails() { + // No profile, so part 2 fails at its first line. + runBlocking { whenever(pumpSync.expectedPumpState()).doAnswer { throw IllegalStateException("No profile set") } } + + runStep(OmnipodWizardStep.INSERT_CANNULA) + + inOrder(bleManager) { + verify(bleManager).isActivationRunning = true + verify(bleManager).isActivationRunning = false + } + } + + /** Runs the wizard action of [step] the way the UI does, and waits until it has finished. */ + private fun runStep(step: OmnipodWizardStep) { + sut.moveToStep(step) + sut.executeAction() + runBlocking { + withTimeout(5_000) { sut.actionState.first { it !is ActionState.Executing } } + } + assertThat(sut.actionState.value).isInstanceOf(ActionState.Error::class.java) + } +} diff --git a/settings.gradle b/settings.gradle index 8c1964654606..225256e7a5c8 100644 --- a/settings.gradle +++ b/settings.gradle @@ -53,6 +53,7 @@ include ':pump:medtronic' include ':pump:omnipod:common' include ':pump:omnipod:dash' include ':pump:omnipod:eros' +include ':pump:omnipod:omnipod5' include ':pump:common' include ':pump:rileylink' include ':pump:carelevo'