diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt index 6532aa1441..289131a72d 100644 --- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt +++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt @@ -14,8 +14,10 @@ import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import to.bitkit.async.ServiceQueue import to.bitkit.models.msatCeilOf +import to.bitkit.nfc.NfcDevOverride import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.ProbeOutcome +import to.bitkit.ui.shared.effects.NfcState import to.bitkit.utils.Logger import kotlin.time.Duration.Companion.seconds import to.bitkit.repositories.ProbeReadiness as NodeProbeReadiness @@ -42,6 +44,8 @@ class DevToolsProvider : ContentProvider() { override fun call(method: String, arg: String?, extras: Bundle?): Bundle { check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" } return runCatching { + // Needs no node, so it does not wait behind LDK work. + if (method == OverrideNfc.METHOD) return@runCatching OverrideNfc.execute(arg) val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" } ServiceQueue.LDK.blocking { command.execute(deps) } }.getOrElse { @@ -58,6 +62,21 @@ class DevToolsProvider : ContentProvider() { override fun query(uri: Uri, proj: Array?, sel: String?, args: Array?, sort: String?) = null } +private object OverrideNfc { + const val METHOD = "overrideNfc" + + /** Null fields clear the override. */ + @Serializable + data class Args(val adapterState: NfcState? = null, val cameraStopsPolling: Boolean? = null) + + fun execute(arg: String?): DevResult { + val args = arg.deserialize() + Logger.info("Overriding NFC '$args' via devtools", context = TAG) + NfcDevOverride.set(args.adapterState, args.cameraStopsPolling) + return DevResult.Ack() + } +} + private sealed interface DevCommand { companion object { diff --git a/app/src/debug/java/to/bitkit/nfc/NfcDevOverride.kt b/app/src/debug/java/to/bitkit/nfc/NfcDevOverride.kt new file mode 100644 index 0000000000..c22f1dc998 --- /dev/null +++ b/app/src/debug/java/to/bitkit/nfc/NfcDevOverride.kt @@ -0,0 +1,24 @@ +package to.bitkit.nfc + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import to.bitkit.ui.shared.effects.NfcState + +/** + * Debug-only NFC state overrides, set over adb through `DevToolsProvider`, so the scanner status can be checked on + * an emulator, which has no NFC hardware. Null leaves the real value in place. + */ +internal object NfcDevOverride { + private val _adapterState = MutableStateFlow(null) + val adapterState: StateFlow = _adapterState.asStateFlow() + + private val _cameraStopsPolling = MutableStateFlow(null) + val cameraStopsPolling: StateFlow = _cameraStopsPolling.asStateFlow() + + fun set(adapterState: NfcState?, cameraStopsPolling: Boolean?) { + _adapterState.update { adapterState } + _cameraStopsPolling.update { cameraStopsPolling } + } +} diff --git a/app/src/main/java/to/bitkit/ext/Context.kt b/app/src/main/java/to/bitkit/ext/Context.kt index edc146cbe8..4bfc0f209c 100644 --- a/app/src/main/java/to/bitkit/ext/Context.kt +++ b/app/src/main/java/to/bitkit/ext/Context.kt @@ -13,6 +13,7 @@ import android.content.Context.NOTIFICATION_SERVICE import android.content.ContextWrapper import android.content.Intent import android.content.pm.PackageManager.PERMISSION_GRANTED +import android.hardware.camera2.CameraManager import android.hardware.usb.UsbManager import android.net.ConnectivityManager import android.os.PowerManager @@ -51,6 +52,9 @@ val Context.usbManager: UsbManager val Context.bluetoothManager: BluetoothManager get() = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager +val Context.cameraManager: CameraManager + get() = getSystemService(Context.CAMERA_SERVICE) as CameraManager + val Context.isBluetoothEnabled: Boolean get() = bluetoothManager.adapter?.isEnabled == true diff --git a/app/src/main/java/to/bitkit/nfc/NfcPolling.kt b/app/src/main/java/to/bitkit/nfc/NfcPolling.kt new file mode 100644 index 0000000000..c0b7701241 --- /dev/null +++ b/app/src/main/java/to/bitkit/nfc/NfcPolling.kt @@ -0,0 +1,95 @@ +package to.bitkit.nfc + +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import to.bitkit.utils.Logger +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +private const val TAG = "NfcPolling" + +/** + * When this read-only property is above 0, Android's CameraServiceProxy switches NFC polling off while any camera + * is active and back on when none is. Apps cannot turn polling back on meanwhile: NfcService drops their reader + * mode requests while that stop is in place. + */ +internal const val NOTIFY_NFC_PROPERTY = "ro.camera.notify_nfc" + +/** Parses [NOTIFY_NFC_PROPERTY] the way CameraServiceProxy does: `SystemProperties.getInt(name, 0) > 0`. */ +internal fun cameraStopsNfcPolling(propertyValue: String?): Boolean = + (propertyValue?.trim()?.toIntOrNull() ?: 0) > 0 + +/** How long reading a system property may take before the read counts as failed. */ +private val GETPROP_TIMEOUT: Duration = 2.seconds + +private val cachedCameraStopsNfcPolling = AtomicReference(null) + +/** The cached [deviceCameraStopsNfcPolling] result, without reading the property; null until a read succeeds. */ +internal fun peekCameraStopsNfcPolling(): Boolean? = cachedCameraStopsNfcPolling.get() + +/** + * Whether this phone stops NFC polling while a camera is open. Only a successful read is cached; a failed one + * returns false and is retried on the next call. Blocks, so call it off the main thread. + */ +internal fun deviceCameraStopsNfcPolling(): Boolean { + cachedCameraStopsNfcPolling.get()?.let { return it } + return runCatching { readCommandOutput("getprop", NOTIFY_NFC_PROPERTY) } + .onFailure { Logger.warn("Failed to read '$NOTIFY_NFC_PROPERTY'", it, context = TAG) } + .map(::cameraStopsNfcPolling) + .onSuccess { + cachedCameraStopsNfcPolling.set(it) + Logger.info("Read camera stops NFC polling '$it'", context = TAG) + } + .getOrDefault(false) +} + +/** Runs [command] and returns its output; throws when it times out or exits non-zero, so the read is not cached. */ +internal fun readCommandOutput(vararg command: String): String { + val process = ProcessBuilder(*command).redirectErrorStream(true).start() + return runCatching { + val exited = process.waitFor(GETPROP_TIMEOUT.inWholeMilliseconds, TimeUnit.MILLISECONDS) + check(exited) { "${command.first()} timed out" } + check(process.exitValue() == 0) { "${command.first()} failed with exit code ${process.exitValue()}" } + process.inputStream.bufferedReader().use { it.readText() } + }.also { process.destroy() }.getOrThrow() +} + +/** + * Treats NFC polling as stopped while any present camera is unavailable, on phones where [NOTIFY_NFC_PROPERTY] is + * set. CameraServiceProxy stops polling when a camera becomes active and resumes it when none is, and an NFC + * toggle hides the stop from apps until it is sent again, so this errs toward reporting NFC as not reading. The + * camera state is kept across NFC toggles, and Compose observes it. + * + * Not thread safe: feed it from the main thread only. + */ +internal class CameraNfcStopTracker { + private var unavailableCameras by mutableStateOf(emptySet()) + + val isAnyCameraUnavailable get() = unavailableCameras.isNotEmpty() + + fun isNfcStopped(isNfcOn: Boolean) = isNfcOn && isAnyCameraUnavailable + + /** + * [presentCameras] is `CameraManager.cameraIdList`, or null when it could not be read. A camera missing from it + * was removed, not opened; without the list the camera counts as present. + */ + fun onCameraUnavailable(cameraId: String, presentCameras: Set?) { + unavailableCameras = if (presentCameras == null || cameraId in presentCameras) { + unavailableCameras + cameraId + } else { + unavailableCameras - cameraId + } + } + + fun onCameraAvailable(cameraId: String) = run { unavailableCameras = unavailableCameras - cameraId } + + /** Drops cameras that left without an available callback, e.g. after the camera service restarted. */ + fun retainPresent(presentCameras: Set) = run { + unavailableCameras = unavailableCameras intersect presentCameras + } + + fun clear() = run { unavailableCameras = emptySet() } +} diff --git a/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt b/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt index 955462602b..f10110d62c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt +++ b/app/src/main/java/to/bitkit/ui/screens/scanner/NearbyScanSources.kt @@ -51,11 +51,13 @@ import to.bitkit.ui.shared.effects.nearbyPermissions import to.bitkit.ui.shared.effects.openNfcSettings import to.bitkit.ui.shared.effects.rememberBluetoothState import to.bitkit.ui.shared.effects.rememberNfcState +import to.bitkit.ui.shared.effects.rememberNfcStoppedByCamera import to.bitkit.ui.theme.Colors /** * NFC and Bluetooth availability on a payment scanner, with the actions that turn each one on. - * While [isPaused], neither source reads, so neither counts as active. + * While [isPaused], neither source reads, so neither counts as active. NFC does not count while + * [isNfcStoppedByCamera]: the phone stops polling while a camera is open, though NFC stays on. */ @Stable data class NearbyScanSources( @@ -64,8 +66,9 @@ data class NearbyScanSources( val onEnableNfc: () -> Unit, val onEnableBluetooth: () -> Unit, val isPaused: Boolean = false, + val isNfcStoppedByCamera: Boolean = false, ) { - val isNfcActive get() = nfcState == NfcState.ON && !isPaused + val isNfcActive get() = nfcState == NfcState.ON && !isPaused && !isNfcStoppedByCamera val isBluetoothActive get() = bluetoothState == BluetoothState.ON && !isPaused val canEnableNfc get() = nfcState == NfcState.OFF val canEnableBluetooth @@ -95,6 +98,7 @@ fun rememberNearbyScanSources( val isPaused = isNearbyPaused() var refreshKey by remember { mutableIntStateOf(0) } val nfcState = rememberNfcState() + val isNfcStoppedByCamera = rememberNfcStoppedByCamera(nfcState) val bluetoothState = rememberBluetoothState(NearbyRole.SCAN, refreshKey) var permissionRequested by remember { mutableStateOf(false) } @@ -123,6 +127,7 @@ fun rememberNearbyScanSources( nfcState = nfcState, bluetoothState = bluetoothState, isPaused = isPaused, + isNfcStoppedByCamera = isNfcStoppedByCamera, onEnableNfc = { context.openNfcSettings() }, onEnableBluetooth = { when (bluetoothState) { diff --git a/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt index 5bd5fb26c6..5cb74c6ea3 100644 --- a/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt +++ b/app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt @@ -1,10 +1,13 @@ package to.bitkit.ui.shared.effects import android.app.Activity +import android.content.BroadcastReceiver import android.content.ComponentName import android.content.Context import android.content.Intent +import android.content.IntentFilter import android.content.pm.PackageManager +import android.hardware.camera2.CameraManager import android.nfc.NfcAdapter import android.nfc.Tag import android.nfc.cardemulation.CardEmulation @@ -15,24 +18,35 @@ import android.provider.Settings import androidx.activity.compose.LocalActivity import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue import androidx.compose.ui.platform.LocalContext +import androidx.core.content.ContextCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext import to.bitkit.androidServices.NdefTagService +import to.bitkit.ext.cameraManager +import to.bitkit.nfc.CameraNfcStopTracker import to.bitkit.nfc.NdefCodec +import to.bitkit.nfc.NfcDevOverride import to.bitkit.nfc.NfcReadDispatcher import to.bitkit.nfc.NfcRepeatGuard import to.bitkit.nfc.NfcTagEmitter import to.bitkit.nfc.READER_FLAGS import to.bitkit.nfc.ReaderModeOwner import to.bitkit.nfc.Type4TagEmulator +import to.bitkit.nfc.deviceCameraStopsNfcPolling import to.bitkit.nfc.nfcPaymentRequest +import to.bitkit.nfc.peekCameraStopsNfcPolling import to.bitkit.utils.Logger private const val TAG = "NfcEffects" @@ -62,20 +76,93 @@ fun rememberCanEmitNfc(): Boolean { return nfcState == NfcState.ON && supportsCardEmulation } -/** NFC availability, refreshed every time the screen resumes (e.g. after the user turns NFC on). */ +/** NFC availability, refreshed when the screen resumes and whenever the adapter turns on or off. */ @Composable fun rememberNfcState(): NfcState { val context = LocalContext.current val lifecycleOwner = LocalLifecycleOwner.current var state by remember { mutableStateOf(context.nfcState()) } - DisposableEffect(lifecycleOwner) { + val override by NfcDevOverride.adapterState.collectAsStateWithLifecycle() + DisposableEffect(context, lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) state = context.nfcState() } + val receiver = object : BroadcastReceiver() { + override fun onReceive(receiverContext: Context, intent: Intent) { + state = context.nfcState() + } + } + // The NFC service, not the system server, sends this protected broadcast, so the receiver must be exported. + ContextCompat.registerReceiver( + context, + receiver, + IntentFilter(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED), + ContextCompat.RECEIVER_EXPORTED, + ) + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + context.unregisterReceiver(receiver) + } + } + return override ?: state +} + +/** + * Whether NFC polling may be off because a camera is open, on phones that switch it off then (see + * [to.bitkit.nfc.NOTIFY_NFC_PROPERTY] and [CameraNfcStopTracker]). Errs toward true: a stop the system no longer + * applies after an NFC toggle still counts until every camera is available again. + */ +@Composable +fun rememberNfcStoppedByCamera(nfcState: NfcState): Boolean { + val override by NfcDevOverride.cameraStopsPolling.collectAsStateWithLifecycle() + // A value read earlier in this process applies from the first frame. + val deviceStopsPolling by produceState(peekCameraStopsNfcPolling() ?: false) { + value = withContext(Dispatchers.IO) { deviceCameraStopsNfcPolling() } + } + val cameraStopsPolling = override ?: deviceStopsPolling + val tracker = rememberCameraNfcStopTracker(enabled = cameraStopsPolling) + val isStopped = cameraStopsPolling && tracker.isNfcStopped(isNfcOn = nfcState == NfcState.ON) + LaunchedEffect(isStopped) { + if (isStopped) Logger.info("Detected NFC polling stopped by an open camera", context = TAG) + } + return isStopped +} + +/** Watches camera availability while [enabled], independent of NFC, so NFC turned on with a camera open is hidden. */ +@Composable +private fun rememberCameraNfcStopTracker(enabled: Boolean): CameraNfcStopTracker { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + val tracker = remember { CameraNfcStopTracker() } + + DisposableEffect(context, lifecycleOwner, enabled) { + if (!enabled) return@DisposableEffect onDispose {} + val cameraManager = context.cameraManager + fun presentCameras(): Set? = runCatching { cameraManager.cameraIdList.toSet() } + .onFailure { Logger.warn("Failed to list cameras", it, context = TAG) } + .getOrNull() + + // Registered on the main looper, so the tracker is only touched from the main thread. + val callback = object : CameraManager.AvailabilityCallback() { + override fun onCameraAvailable(cameraId: String) = tracker.onCameraAvailable(cameraId) + + override fun onCameraUnavailable(cameraId: String) = tracker.onCameraUnavailable(cameraId, presentCameras()) + } + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) presentCameras()?.let(tracker::retainPresent) + } + val registered = runCatching { + cameraManager.registerAvailabilityCallback(callback, Handler(Looper.getMainLooper())) + }.onFailure { Logger.warn("Failed to watch camera availability", it, context = TAG) }.isSuccess lifecycleOwner.lifecycle.addObserver(observer) - onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + if (registered) cameraManager.unregisterAvailabilityCallback(callback) + tracker.clear() + } } - return state + return tracker } /** diff --git a/app/src/release/java/to/bitkit/nfc/NfcDevOverride.kt b/app/src/release/java/to/bitkit/nfc/NfcDevOverride.kt new file mode 100644 index 0000000000..280c55ede8 --- /dev/null +++ b/app/src/release/java/to/bitkit/nfc/NfcDevOverride.kt @@ -0,0 +1,11 @@ +package to.bitkit.nfc + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import to.bitkit.ui.shared.effects.NfcState + +/** Release builds take no NFC overrides; see the debug source set. */ +internal object NfcDevOverride { + val adapterState: StateFlow = MutableStateFlow(null) + val cameraStopsPolling: StateFlow = MutableStateFlow(null) +} diff --git a/app/src/test/java/to/bitkit/nfc/NfcPollingTest.kt b/app/src/test/java/to/bitkit/nfc/NfcPollingTest.kt new file mode 100644 index 0000000000..d488080e8d --- /dev/null +++ b/app/src/test/java/to/bitkit/nfc/NfcPollingTest.kt @@ -0,0 +1,108 @@ +package to.bitkit.nfc + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class NfcPollingTest { + @Test + fun `positive property value means the camera stops polling`() { + assertTrue(cameraStopsNfcPolling("1")) + assertTrue(cameraStopsNfcPolling("1\n")) + } + + @Test + fun `missing, zero or non-numeric property value means polling stays on`() { + assertFalse(cameraStopsNfcPolling(null)) + assertFalse(cameraStopsNfcPolling("")) + assertFalse(cameraStopsNfcPolling("\n")) + assertFalse(cameraStopsNfcPolling("0")) + // CameraServiceProxy reads the property with SystemProperties.getInt, which falls back to 0 for "true". + assertFalse(cameraStopsNfcPolling("true")) + } + + @Test + fun `command exiting non-zero fails the read instead of returning its output`() { + assertFailsWith { readCommandOutput("sh", "-c", "echo error; exit 1") } + } + + @Test + fun `command exiting zero returns its output`() { + assertEquals("1\n", readCommandOutput("sh", "-c", "echo 1")) + } +} + +class CameraNfcStopTrackerTest { + private val present = setOf("0", "1", "2") + private val tracker = CameraNfcStopTracker() + + @Test + fun `first camera opening stops polling and the last one closing resumes it`() { + tracker.onCameraUnavailable("0", present) + assertTrue(tracker.isAnyCameraUnavailable) + tracker.onCameraUnavailable("1", present) + tracker.onCameraAvailable("0") + assertTrue(tracker.isAnyCameraUnavailable) + tracker.onCameraAvailable("1") + assertFalse(tracker.isAnyCameraUnavailable) + } + + @Test + fun `same camera reported unavailable twice resumes after one available`() { + tracker.onCameraUnavailable("0", present) + tracker.onCameraUnavailable("0", present) + tracker.onCameraAvailable("0") + assertFalse(tracker.isAnyCameraUnavailable) + } + + @Test + fun `available for a camera never seen keeps the stop of an open one`() { + tracker.onCameraUnavailable("0", present) + tracker.onCameraAvailable("1") + assertTrue(tracker.isAnyCameraUnavailable) + } + + @Test + fun `camera missing from the camera list counts as removed, not opened`() { + tracker.onCameraUnavailable("9", present) + assertFalse(tracker.isAnyCameraUnavailable) + tracker.onCameraUnavailable("0", present) + tracker.onCameraUnavailable("0", present - "0") + assertFalse(tracker.isAnyCameraUnavailable) + } + + @Test + fun `cameras gone from the camera list on resume resume polling`() { + tracker.onCameraUnavailable("0", present) + tracker.retainPresent(setOf("1")) + assertFalse(tracker.isAnyCameraUnavailable) + } + + @Test + fun `retain keeps the stop while an open camera is still present`() { + tracker.onCameraUnavailable("0", present) + tracker.retainPresent(present) + assertTrue(tracker.isAnyCameraUnavailable) + } + + @Test + fun `stop survives nfc turned off and on with a camera open`() { + tracker.onCameraUnavailable("0", present) + assertTrue(tracker.isNfcStopped(isNfcOn = true)) + assertFalse(tracker.isNfcStopped(isNfcOn = false)) + assertTrue(tracker.isNfcStopped(isNfcOn = true)) + } + + @Test + fun `nfc on with no camera open is not stopped`() { + assertFalse(tracker.isNfcStopped(isNfcOn = true)) + } + + @Test + fun `camera counts as present when the camera list cannot be read`() { + tracker.onCameraUnavailable("0", presentCameras = null) + assertTrue(tracker.isNfcStopped(isNfcOn = true)) + } +} diff --git a/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt b/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt index bcc868093d..3345681ef7 100644 --- a/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/scanner/NearbyScanSourcesTest.kt @@ -5,10 +5,23 @@ import to.bitkit.R import to.bitkit.ui.shared.effects.BluetoothState import to.bitkit.ui.shared.effects.NfcState import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue class NearbyScanSourcesTest { - private fun sources(isPaused: Boolean) = - NearbyScanSources(NfcState.ON, BluetoothState.ON, onEnableNfc = {}, onEnableBluetooth = {}, isPaused = isPaused) + private fun sources( + isPaused: Boolean = false, + nfcState: NfcState = NfcState.ON, + bluetoothState: BluetoothState = BluetoothState.ON, + isNfcStoppedByCamera: Boolean = false, + ) = NearbyScanSources( + nfcState = nfcState, + bluetoothState = bluetoothState, + onEnableNfc = {}, + onEnableBluetooth = {}, + isPaused = isPaused, + isNfcStoppedByCamera = isNfcStoppedByCamera, + ) @Test fun `status lists the sources that read`() { @@ -19,4 +32,35 @@ class NearbyScanSourcesTest { fun `status lists only the camera while nearby payments pause`() { assertEquals(R.string.other__scanner_status_qr, scannerStatusText(sources(isPaused = true))) } + + @Test + fun `status drops nfc while the camera stops polling and keeps bluetooth`() { + val sources = sources(isNfcStoppedByCamera = true) + assertFalse(sources.isNfcActive) + assertTrue(sources.isBluetoothActive) + assertFalse(sources.canEnableNfc) + assertEquals(R.string.other__scanner_status_qr_bluetooth, scannerStatusText(sources)) + } + + @Test + fun `status drops nfc while the camera stops polling without bluetooth`() { + val sources = sources(isNfcStoppedByCamera = true, bluetoothState = BluetoothState.OFF) + assertEquals(R.string.other__scanner_status_qr, scannerStatusText(sources)) + } + + @Test + fun `status drops nfc and offers to enable it while the adapter is off`() { + val sources = sources(nfcState = NfcState.OFF) + assertFalse(sources.isNfcActive) + assertTrue(sources.canEnableNfc) + assertEquals(R.string.other__scanner_status_qr_bluetooth, scannerStatusText(sources)) + } + + @Test + fun `status lists nfc again once the camera stop ends`() { + assertEquals( + R.string.other__scanner_status_qr_nfc_bluetooth, + scannerStatusText(sources(isNfcStoppedByCamera = false)), + ) + } } diff --git a/changelog.d/next/2000.fixed.md b/changelog.d/next/2000.fixed.md new file mode 100644 index 0000000000..1ce1749d79 --- /dev/null +++ b/changelog.d/next/2000.fixed.md @@ -0,0 +1 @@ +The scanner no longer says it is reading NFC while the phone has NFC polling turned off, such as when NFC is switched off or on phones that pause NFC while the camera is open.