diff --git a/pump/combov2/comboctl/src/commonMain/kotlin/info/nightscout/comboctl/main/RTNavigation.kt b/pump/combov2/comboctl/src/commonMain/kotlin/info/nightscout/comboctl/main/RTNavigation.kt index 8607fcfe44..154bc75be5 100644 --- a/pump/combov2/comboctl/src/commonMain/kotlin/info/nightscout/comboctl/main/RTNavigation.kt +++ b/pump/combov2/comboctl/src/commonMain/kotlin/info/nightscout/comboctl/main/RTNavigation.kt @@ -1045,10 +1045,17 @@ internal fun computeShortRTButtonPress( require(stepSize > 0) val distance = (targetQuantity - currentQuantity).absoluteValue if (cyclicQuantityRange != null) { + // With a cyclic quantity, if the absolute distance between + // quantities exceeds half of that range, we have the option + // to change the quantity in the opposite direction which + // requires fewer button presses. For example, if the range + // is 60, and the absolute distance is 40, we'd normally have + // to press a button 40 times to get to the target quantity. + // But since cyclic quantities wrap around, we can instead + // press the opposite button 60-40 = 20 times to also get + // to the target quantity. if (distance > (cyclicQuantityRange / 2)) { - val firstPart = (cyclicQuantityRange - targetQuantity) - val secondPart = currentQuantity - 0 - numNeededShortRTButtonPresses = computeNumSteps(stepSize, firstPart + secondPart) + numNeededShortRTButtonPresses = computeNumSteps(stepSize, cyclicQuantityRange - distance) shortRTButtonToPress = if (targetQuantity < currentQuantity) incrementButton else decrementButton } else { numNeededShortRTButtonPresses = computeNumSteps(stepSize, distance) diff --git a/pump/combov2/comboctl/src/jvmTest/kotlin/info/nightscout/comboctl/main/RTNavigationTest.kt b/pump/combov2/comboctl/src/jvmTest/kotlin/info/nightscout/comboctl/main/RTNavigationTest.kt index 8ec81377bb..ca93288ddf 100644 --- a/pump/combov2/comboctl/src/jvmTest/kotlin/info/nightscout/comboctl/main/RTNavigationTest.kt +++ b/pump/combov2/comboctl/src/jvmTest/kotlin/info/nightscout/comboctl/main/RTNavigationTest.kt @@ -274,6 +274,19 @@ class RTNavigationTest { ) assertEquals(Pair(((60 - 50) + (10 - 0)) / 1, RTNavigationButton.DOWN), result) + // Another cyclic quantity range test with a wrap around, + // this time from the other direction (wrapping around + // from quantity 58 to target quantity 1). + result = computeShortRTButtonPress( + currentQuantity = 58, + targetQuantity = 1, + cyclicQuantityRange = 60, + incrementSteps = arrayOf(Pair(0, 1)), + incrementButton = RTNavigationButton.UP, + decrementButton = RTNavigationButton.DOWN + ) + assertEquals(Pair(3, RTNavigationButton.UP), result) + // Additional test to check that cyclic ranges are handled correctly // even if currentQuantity is slightly higher than targetQuantity. This // verifies that the computation does not produce negative distances.