Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -58,6 +62,21 @@ class DevToolsProvider : ContentProvider() {
override fun query(uri: Uri, proj: Array<String>?, sel: String?, args: Array<String>?, 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<Args>()
Logger.info("Overriding NFC '$args' via devtools", context = TAG)
NfcDevOverride.set(args.adapterState, args.cameraStopsPolling)
return DevResult.Ack()
}
}

private sealed interface DevCommand {

companion object {
Expand Down
24 changes: 24 additions & 0 deletions app/src/debug/java/to/bitkit/nfc/NfcDevOverride.kt
Original file line number Diff line number Diff line change
@@ -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<NfcState?>(null)
val adapterState: StateFlow<NfcState?> = _adapterState.asStateFlow()

private val _cameraStopsPolling = MutableStateFlow<Boolean?>(null)
val cameraStopsPolling: StateFlow<Boolean?> = _cameraStopsPolling.asStateFlow()

fun set(adapterState: NfcState?, cameraStopsPolling: Boolean?) {
_adapterState.update { adapterState }
_cameraStopsPolling.update { cameraStopsPolling }
}
}
4 changes: 4 additions & 0 deletions app/src/main/java/to/bitkit/ext/Context.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
95 changes: 95 additions & 0 deletions app/src/main/java/to/bitkit/nfc/NfcPolling.kt
Original file line number Diff line number Diff line change
@@ -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<Boolean?>(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<String>())

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<String>?) {
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<String>) = run {
unavailableCameras = unavailableCameras intersect presentCameras
}

fun clear() = run { unavailableCameras = emptySet() }
}
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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) }
Expand Down Expand Up @@ -123,6 +127,7 @@ fun rememberNearbyScanSources(
nfcState = nfcState,
bluetoothState = bluetoothState,
isPaused = isPaused,
isNfcStoppedByCamera = isNfcStoppedByCamera,
onEnableNfc = { context.openNfcSettings() },
onEnableBluetooth = {
when (bluetoothState) {
Expand Down
95 changes: 91 additions & 4 deletions app/src/main/java/to/bitkit/ui/shared/effects/NfcEffects.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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"
Expand Down Expand Up @@ -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<String>? = 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
}

/**
Expand Down
11 changes: 11 additions & 0 deletions app/src/release/java/to/bitkit/nfc/NfcDevOverride.kt
Original file line number Diff line number Diff line change
@@ -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<NfcState?> = MutableStateFlow(null)
val cameraStopsPolling: StateFlow<Boolean?> = MutableStateFlow(null)
}
Loading