提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
@@ -0,0 +1,41 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.bleserial"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
testOptions {
unitTests.isReturnDefaultValues = true
}
}
dependencies {
implementation(project(":core:redact"))
implementation(libs.coroutines.core)
implementation(libs.coroutines.android)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
testImplementation(libs.junit)
testImplementation(libs.coroutines.test)
testImplementation(libs.mockk)
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,31 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!--
BLE-serial console (Nordic UART Service / HM-10). Unlike Classic-SPP #406,
a BLE UART peripheral (an nRF board, an HM-10 module, a BLE RS232 adapter)
usually isn't bonded and won't appear in bondedDevices, so it must be
DISCOVERED by an active BLE scan — hence BLUETOOTH_SCAN, which #406
deliberately omitted. `neverForLocation` asserts we don't derive location
from BLE, so no location permission is needed on API 31+. Pre-31, a BLE
scan still legally requires (fine) location + the legacy BT permissions.
BLUETOOTH_CONNECT covers the GATT connect and reading device names.
Declared in the module that uses Bluetooth so the app inherits it via
manifest merge (the #406 gap: the app doesn't depend on an unrelated
module's manifest).
-->
<uses-permission
android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="30" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="false" />
</manifest>
@@ -0,0 +1,326 @@
package sh.haven.core.bleserial
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
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 android.util.Log
import java.util.ArrayDeque
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
private const val TAG = "BleSerialConnector"
/**
* Opens a BLE-serial (GATT) link to a peripheral by MAC address, resolving the
* Nordic UART Service (or HM-10, or explicit UUIDs), enabling notifications, and
* negotiating a larger MTU. The GATT API is asynchronous and callback-driven;
* [connect] drives that state machine to completion and blocks until the link is
* usable, so callers (mirroring the RFCOMM #406 path) treat it like a blocking
* dial. Must run off the main thread. BLUETOOTH_CONNECT must be granted.
*/
class AndroidBleSerialConnector(private val context: Context) {
@SuppressLint("MissingPermission") // BLUETOOTH_SCAN/CONNECT gated at the call site
fun connect(address: String, params: BleSerialParams = BleSerialParams()): BleSerialLink {
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
?: throw IllegalStateException("This device has no Bluetooth adapter")
if (!adapter.isEnabled) throw IllegalStateException("Bluetooth is off")
// Scan for the exact MAC first, then connect to the *scanned* device.
// `getRemoteDevice(String)`/`getRemoteLeDevice` don't reliably connect a
// never-seen random-static address (nRF boards, HM-10) on OEM stacks —
// the direct connect just times out (both were tried in the device test).
// A ScanResult's device carries the correct address type and primes the
// stack, and finding it also proves the peripheral is advertising.
val device = scanForDevice(adapter, address, SCAN_TIMEOUT_MS)
val link = AndroidBleSerialLink(context, params)
link.connectBlocking(device, CONNECT_TIMEOUT_MS)
return link
}
@SuppressLint("MissingPermission")
private fun scanForDevice(
adapter: BluetoothAdapter,
address: String,
timeoutMs: Long,
): BluetoothDevice {
val scanner = adapter.bluetoothLeScanner
?: throw IllegalStateException("BLE scanning unavailable")
val latch = CountDownLatch(1)
val found = java.util.concurrent.atomic.AtomicReference<BluetoothDevice?>()
val callback = object : android.bluetooth.le.ScanCallback() {
override fun onScanResult(callbackType: Int, result: android.bluetooth.le.ScanResult) {
if (result.device.address.equals(address, ignoreCase = true)) {
found.set(result.device)
latch.countDown()
}
}
}
val filter = android.bluetooth.le.ScanFilter.Builder().setDeviceAddress(address).build()
val settings = android.bluetooth.le.ScanSettings.Builder()
.setScanMode(android.bluetooth.le.ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
scanner.startScan(listOf(filter), settings, callback)
try {
if (!latch.await(timeoutMs, TimeUnit.MILLISECONDS)) {
throw IllegalStateException(
"BLE peripheral $address not found — is it powered on, in range, and advertising?",
)
}
} finally {
runCatching { scanner.stopScan(callback) }
}
return found.get() ?: throw IllegalStateException("BLE peripheral $address not found")
}
private companion object {
const val SCAN_TIMEOUT_MS = 12_000L
const val CONNECT_TIMEOUT_MS = 20_000L
}
}
/**
* [BleSerialLink] backed by an open [BluetoothGatt]. Owns the GATT callback, a
* pre-[start] notification buffer, and a single-in-flight write queue (BLE
* permits one GATT operation at a time).
*/
@SuppressLint("MissingPermission")
@Suppress("DEPRECATION") // pre-33 setValue/writeCharacteristic path — works on all minSdk 26+ levels
internal class AndroidBleSerialLink(
private val context: Context,
private val params: BleSerialParams,
) : BleSerialLink {
@Volatile private var gatt: BluetoothGatt? = null
@Volatile private var writeChar: BluetoothGattCharacteristic? = null
@Volatile private var notifyChar: BluetoothGattCharacteristic? = null
@Volatile private var name: String? = null
@Volatile private var mtuPayload = DEFAULT_MTU - 3
@Volatile private var onData: ((ByteArray) -> Unit)? = null
@Volatile private var onError: ((Throwable) -> Unit)? = null
private val preStartBuffer = ArrayDeque<ByteArray>()
private val ready = CountDownLatch(1)
@Volatile private var readyError: Throwable? = null
@Volatile private var started = false
@Volatile private var closed = false
// Single-in-flight write queue; drained on onCharacteristicWrite.
private val writeQueue = ArrayDeque<ByteArray>()
private var writeInFlight = false
override val displayName: String? get() = name
fun connectBlocking(device: BluetoothDevice, timeoutMs: Long) {
name = runCatching { device.name }.getOrNull()
gatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
if (gatt == null) {
throw IllegalStateException("connectGatt returned null for ${device.address}")
}
if (!ready.await(timeoutMs, TimeUnit.MILLISECONDS)) {
close()
throw IllegalStateException("BLE connect timed out after ${timeoutMs}ms")
}
readyError?.let { close(); throw it }
}
override fun start(onData: (ByteArray) -> Unit, onError: (Throwable) -> Unit) {
synchronized(preStartBuffer) {
this.onData = onData
this.onError = onError
started = true
while (preStartBuffer.isNotEmpty()) onData(preStartBuffer.poll())
}
}
override fun write(bytes: ByteArray) {
if (closed || bytes.isEmpty()) return
val ch = writeChar ?: return
val useNoResponse =
(ch.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
synchronized(writeQueue) {
var i = 0
while (i < bytes.size) {
val end = minOf(i + mtuPayload, bytes.size)
writeQueue.add(bytes.copyOfRange(i, end))
i = end
}
pumpWrites(useNoResponse)
}
}
// Caller holds writeQueue lock.
private fun pumpWrites(useNoResponse: Boolean) {
if (writeInFlight) return
val g = gatt ?: return
val ch = writeChar ?: return
val chunk = writeQueue.poll() ?: return
writeInFlight = true
ch.writeType = if (useNoResponse) {
BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
} else {
BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
}
ch.value = chunk
val ok = runCatching { g.writeCharacteristic(ch) }.getOrDefault(false)
// WRITE_TYPE_NO_RESPONSE still fires onCharacteristicWrite on most stacks;
// if the initiate failed outright, don't stall the queue.
if (!ok) {
writeInFlight = false
if (writeQueue.isNotEmpty()) pumpWrites(useNoResponse)
}
}
override fun close() {
if (closed) return
closed = true
val g = gatt
gatt = null
runCatching { g?.disconnect() }
runCatching { g?.close() }
}
private fun deliver(bytes: ByteArray) {
synchronized(preStartBuffer) {
val cb = onData
if (started && cb != null) cb(bytes) else preStartBuffer.add(bytes)
}
}
private fun failReady(t: Throwable) {
readyError = t
ready.countDown()
}
private val gattCallback = object : android.bluetooth.BluetoothGattCallback() {
override fun onConnectionStateChange(g: BluetoothGatt, status: Int, newState: Int) {
when (newState) {
BluetoothProfile.STATE_CONNECTED -> {
// Larger MTU first (bigger writes/notifications); discovery
// follows in onMtuChanged, or here if the request can't start.
if (!runCatching { g.requestMtu(REQUEST_MTU) }.getOrDefault(false)) {
g.discoverServices()
}
}
BluetoothProfile.STATE_DISCONNECTED -> {
if (ready.count > 0L) {
failReady(IllegalStateException("BLE disconnected before ready (status $status)"))
} else if (!closed) {
onError?.invoke(IllegalStateException("BLE link dropped (status $status)"))
}
}
}
}
override fun onMtuChanged(g: BluetoothGatt, mtu: Int, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS && mtu > DEFAULT_MTU) mtuPayload = mtu - 3
g.discoverServices()
}
override fun onServicesDiscovered(g: BluetoothGatt, status: Int) {
if (status != BluetoothGatt.GATT_SUCCESS) {
failReady(IllegalStateException("Service discovery failed (status $status)")); return
}
val resolved = resolveCharacteristics(g)
if (resolved == null) {
failReady(
IllegalStateException(
"No BLE-UART service on this device " +
"(tried Nordic UART + HM-10). If it uses custom UUIDs, they must be supplied.",
),
)
return
}
writeChar = resolved.first
notifyChar = resolved.second
enableNotifications(g, resolved.second)
}
override fun onDescriptorWrite(g: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) {
if (descriptor.uuid != BleSerialParams.CCCD) return
if (status == BluetoothGatt.GATT_SUCCESS) {
ready.countDown() // link is fully usable
} else {
failReady(IllegalStateException("Enabling notifications failed (status $status)"))
}
}
// Pre-33: the framework calls this and populates ch.value.
override fun onCharacteristicChanged(g: BluetoothGatt, ch: BluetoothGattCharacteristic) {
if (ch.uuid == notifyChar?.uuid) {
val value = ch.value ?: return
if (value.isNotEmpty()) deliver(value.copyOf())
}
}
// API 33+: the framework calls this 3-arg form instead (its default impl
// does NOT repopulate ch.value), so read the value param directly. We do
// NOT call super here, so the 2-arg override never double-fires on 33+.
override fun onCharacteristicChanged(
g: BluetoothGatt,
ch: BluetoothGattCharacteristic,
value: ByteArray,
) {
if (ch.uuid == notifyChar?.uuid && value.isNotEmpty()) deliver(value.copyOf())
}
override fun onCharacteristicWrite(g: BluetoothGatt, ch: BluetoothGattCharacteristic, status: Int) {
synchronized(writeQueue) {
writeInFlight = false
val noResp = (ch.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0
if (writeQueue.isNotEmpty()) pumpWrites(noResp)
}
}
}
private fun enableNotifications(g: BluetoothGatt, ch: BluetoothGattCharacteristic) {
g.setCharacteristicNotification(ch, true)
val cccd = ch.getDescriptor(BleSerialParams.CCCD)
if (cccd == null) {
failReady(IllegalStateException("Notify characteristic has no CCCD")); return
}
val indicate = (ch.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0 &&
(ch.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY) == 0
cccd.value = if (indicate) {
BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
} else {
BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
}
if (!runCatching { g.writeDescriptor(cccd) }.getOrDefault(false)) {
failReady(IllegalStateException("Could not write CCCD to enable notifications"))
}
}
/** @return (writeChar, notifyChar) or null if no known/explicit profile matched. */
private fun resolveCharacteristics(
g: BluetoothGatt,
): Pair<BluetoothGattCharacteristic, BluetoothGattCharacteristic>? {
// Explicit UUIDs win.
if (params.serviceUuid != null && params.writeUuid != null && params.notifyUuid != null) {
val svc: BluetoothGattService? = g.getService(params.serviceUuid)
val w = svc?.getCharacteristic(params.writeUuid)
val n = svc?.getCharacteristic(params.notifyUuid)
return if (w != null && n != null) w to n else null
}
for (p in BleSerialParams.AUTO_PROFILES) {
val svc = g.getService(p.service) ?: continue
val w = svc.getCharacteristic(p.write) ?: continue
val n = svc.getCharacteristic(p.notify) ?: continue
Log.d(TAG, "matched ${p.name} on ${name ?: "device"}")
return w to n
}
return null
}
private companion object {
const val DEFAULT_MTU = 23
const val REQUEST_MTU = 247
}
}
@@ -0,0 +1,75 @@
package sh.haven.core.bleserial
import java.util.UUID
/**
* A live BLE-serial byte pipe to a connected GATT peripheral (Nordic UART
* Service, HM-10, or a compatible BLE-UART bridge).
*
* Callback-shaped rather than stream-shaped because GATT delivers reads as
* asynchronous characteristic-change notifications, not a blocking InputStream —
* so [BleSerialSession] stays transport-agnostic and unit-testable with a fake
* link, no Bluetooth hardware. Mirrors [sh.haven.core.usbserial.UsbSerialLink].
*/
interface BleSerialLink {
/** Human-facing peripheral name (advertised name), if known. */
val displayName: String?
/**
* Begin pumping incoming bytes (TX-characteristic notifications) to [onData].
* [onError] fires once if the link drops on its own (out of range, peripheral
* reset); it does NOT fire on an explicit [close]. Any bytes that arrived
* between connect and [start] are replayed here so an on-open greeting isn't
* lost.
*/
fun start(onData: (ByteArray) -> Unit, onError: (Throwable) -> Unit)
/** Write keystrokes / commands to the peripheral (RX characteristic). */
fun write(bytes: ByteArray)
/** Disconnect the GATT link and release it. Idempotent. */
fun close()
}
/**
* Which GATT service/characteristics carry the serial stream. Defaults to
* auto-detect: the connector tries the Nordic UART Service, then HM-10. Supply
* explicit UUIDs for a device that uses neither (e.g. a vendor whose manual just
* says "fill in the correct UUID").
*/
data class BleSerialParams(
val serviceUuid: UUID? = null,
/** Characteristic the client WRITES to (peripheral's RX). */
val writeUuid: UUID? = null,
/** Characteristic the client SUBSCRIBES to for notifications (peripheral's TX). */
val notifyUuid: UUID? = null,
) {
/** A known BLE-UART profile the connector probes when no explicit UUIDs are given. */
data class Profile(val name: String, val service: UUID, val write: UUID, val notify: UUID)
companion object {
private fun uuid(s: String) = UUID.fromString(s)
/** Nordic UART Service — the de-facto standard (nRF SDK "ble_app_uart"). */
val NUS = Profile(
name = "Nordic UART",
service = uuid("6e400001-b5a3-f393-e0a9-e50e24dcca9e"),
write = uuid("6e400002-b5a3-f393-e0a9-e50e24dcca9e"),
notify = uuid("6e400003-b5a3-f393-e0a9-e50e24dcca9e"),
)
/** HM-10 / CC254x clones — one characteristic for both directions. */
val HM10 = Profile(
name = "HM-10",
service = uuid("0000ffe0-0000-1000-8000-00805f9b34fb"),
write = uuid("0000ffe1-0000-1000-8000-00805f9b34fb"),
notify = uuid("0000ffe1-0000-1000-8000-00805f9b34fb"),
)
/** Client Characteristic Configuration Descriptor — enables notifications. */
val CCCD: UUID = uuid("00002902-0000-1000-8000-00805f9b34fb")
/** Probe order when [BleSerialParams] gives no explicit UUIDs. */
val AUTO_PROFILES = listOf(NUS, HM10)
}
}
@@ -0,0 +1,93 @@
package sh.haven.core.bleserial
import android.util.Log
import java.io.Closeable
import java.util.concurrent.atomic.AtomicBoolean
/**
* A live BLE-serial terminal session over an open [BleSerialLink].
*
* Same transport-session shape as [sh.haven.core.btserial.BtSerialSession] and
* MoshSession/EtSession, so [BleSerialSessionManager] mirrors the other managers
* and the terminal ViewModel wires it identically (the callback IS termlib's
* `feedOutput`). Notification-driven rather than reader-thread based — the link
* pushes bytes, so there is no blocking read loop.
*
* @param onDataReceived output sink — (buffer, offset, length), the emulator feed.
* @param onDisconnected fired once when the link drops on its own (out of range,
* peripheral reset), NOT on an explicit [close].
*/
class BleSerialSession(
val sessionId: String,
private val link: BleSerialLink,
onDataReceived: (ByteArray, Int, Int) -> Unit,
private val onDisconnected: (String) -> Unit,
) : Closeable {
@Volatile
private var callback: ((ByteArray, Int, Int) -> Unit)? = onDataReceived
/**
* Optional read-only output tap (the serial↔TCP bridge). Fires alongside the
* terminal [callback] on every inbound chunk; unlike [callback] it survives
* [detach] (a bridge outlives a tab remount) and is dropped only by [setTap]
* or [close]. Write to sinks synchronously — see SerialTcpBridge.
*/
@Volatile
private var tap: ((ByteArray, Int, Int) -> Unit)? = null
private val closed = AtomicBoolean(false)
fun setTap(t: ((ByteArray, Int, Int) -> Unit)?) { tap = t }
fun start() {
link.start(
onData = { bytes ->
callback?.invoke(bytes, 0, bytes.size)
tap?.invoke(bytes, 0, bytes.size)
},
onError = {
if (closed.compareAndSet(false, true)) {
runCatching { link.close() }
onDisconnected(sessionId)
}
},
)
}
/** Send keystrokes to the peripheral. No-op once closed. */
fun sendInput(bytes: ByteArray) {
if (closed.get()) return
try {
link.write(bytes)
} catch (e: Exception) {
Log.d(TAG, "write failed for $sessionId: ${e.message}")
}
}
/** Stop delivering output to the current terminal without dropping the link. */
fun detach() {
callback = null
}
/** Re-wire output to a (new) terminal after a tab remount. */
fun reattach(onDataReceived: (ByteArray, Int, Int) -> Unit) {
callback = onDataReceived
}
val remoteName: String? get() = link.displayName
val isClosed: Boolean get() = closed.get()
/** User teardown — does NOT fire [onDisconnected]. */
override fun close() {
if (closed.compareAndSet(false, true)) {
callback = null
tap = null
runCatching { link.close() }
}
}
companion object {
private const val TAG = "BleSerialSession"
}
}
@@ -0,0 +1,205 @@
package sh.haven.core.bleserial
import android.content.Context
import android.util.Log
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.util.UUID
import java.util.concurrent.Executors
import javax.inject.Inject
import javax.inject.Singleton
import sh.haven.core.redact.LogRedact
private const val TAG = "BleSerialSessionManager"
/**
* Manages BLE-serial terminal sessions, mirroring [sh.haven.core.btserial.BtSerialSessionManager]:
* register → connect (open the GATT link) → create terminal → detach/reattach/remove.
*
* The GATT connect is the only blocking part and runs on IO in [connectSession];
* everything else is registry bookkeeping.
*/
@Singleton
class BleSerialSessionManager @Inject constructor(
@ApplicationContext private val context: Context,
) {
data class SessionState(
val sessionId: String,
val profileId: String,
val label: String,
val status: Status,
val deviceAddress: String = "",
val params: BleSerialParams = BleSerialParams(),
val deviceName: String? = null,
/** Open GATT link, set by [connectSession], consumed by [createTerminalSession]. */
val link: BleSerialLink? = null,
val session: BleSerialSession? = null,
) {
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
}
private val connector by lazy { AndroidBleSerialConnector(context) }
/**
* Opens the GATT link. Test seam — the real path connects via
* [AndroidBleSerialConnector]; tests substitute a fake link.
*/
internal var openLink: (address: String, params: BleSerialParams) -> BleSerialLink =
{ address, params -> connector.connect(address, params) }
private val _sessions = MutableStateFlow<Map<String, SessionState>>(emptyMap())
val sessions: StateFlow<Map<String, SessionState>> = _sessions.asStateFlow()
private val ioExecutor = Executors.newSingleThreadExecutor { r ->
Thread(r, "bleserial-session-io").apply { isDaemon = true }
}
val activeSessions: List<SessionState>
get() = _sessions.value.values.filter {
it.status == SessionState.Status.CONNECTED || it.status == SessionState.Status.CONNECTING
}
/** Register a new session (status CONNECTING). Returns the generated sessionId. */
fun registerSession(
profileId: String,
label: String,
deviceAddress: String,
params: BleSerialParams = BleSerialParams(),
): String {
val sessionId = UUID.randomUUID().toString()
_sessions.update { map ->
map + (sessionId to SessionState(
sessionId = sessionId,
profileId = profileId,
label = label,
status = SessionState.Status.CONNECTING,
deviceAddress = deviceAddress,
params = params,
))
}
return sessionId
}
/**
* Open the GATT link (blocking, on IO). Sets status CONNECTED and stashes the
* link for [createTerminalSession]. Throws on failure (status → ERROR).
*/
suspend fun connectSession(sessionId: String) {
val state = _sessions.value[sessionId]
?: throw IllegalStateException("Session $sessionId not found")
if (state.link != null || state.session != null) return
if (state.deviceAddress.isEmpty()) throw IllegalStateException("No device address for $sessionId")
val link = try {
withContext(Dispatchers.IO) { openLink(state.deviceAddress, state.params) }
} catch (e: Exception) {
Log.e(TAG, "GATT connect failed for ${LogRedact.of(state.label)}: ${e.message}")
updateStatus(sessionId, SessionState.Status.ERROR)
throw e
}
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(
status = SessionState.Status.CONNECTED,
deviceName = link.displayName,
link = link,
))
}
}
/**
* Wrap the already-open link ([connectSession] first) in a terminal session,
* wiring peripheral output to [onDataReceived]. Non-suspend so the terminal
* syncSessions loop can call it. Idempotent.
*/
fun createTerminalSession(
sessionId: String,
onDataReceived: (ByteArray, Int, Int) -> Unit,
): BleSerialSession? {
val state = _sessions.value[sessionId] ?: return null
state.session?.let { return it }
val link = state.link ?: return null
val session = BleSerialSession(
sessionId = sessionId,
link = link,
onDataReceived = onDataReceived,
onDisconnected = { updateStatus(it, SessionState.Status.DISCONNECTED) },
)
session.start()
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(session = session))
}
return session
}
fun isReadyForTerminal(sessionId: String): Boolean {
val s = _sessions.value[sessionId] ?: return false
return s.status == SessionState.Status.CONNECTED && s.session == null && s.link != null
}
/** Detach the terminal without dropping the link. */
fun detachTerminalSession(sessionId: String) {
val state = _sessions.value[sessionId] ?: return
state.session?.detach()
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(session = null))
}
}
fun updateStatus(sessionId: String, status: SessionState.Status) {
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(status = status))
}
}
/** Send [text] as UTF-8 to the session (sendInput contract, #366). */
fun sendInput(sessionId: String, text: String) {
val session = _sessions.value[sessionId]?.session
?: throw IllegalStateException("No live BLE-serial session: $sessionId")
session.sendInput(text.toByteArray(Charsets.UTF_8))
}
// Close the terminal session if one exists (it owns the link), else the bare
// link opened by connectSession before a terminal was created.
private fun tearDown(state: SessionState) {
runCatching { state.session?.close() ?: state.link?.close() }
.onFailure { Log.e(TAG, "tearDown failed for ${state.sessionId}", it) }
}
fun removeSession(sessionId: String) {
val state = _sessions.value[sessionId] ?: return
_sessions.update { it - sessionId }
ioExecutor.execute { tearDown(state) }
}
fun removeAllSessionsForProfile(profileId: String) {
val toRemove = _sessions.value.values.filter { it.profileId == profileId }
_sessions.update { map -> map.filterValues { it.profileId != profileId } }
ioExecutor.execute { toRemove.forEach { tearDown(it) } }
}
fun disconnectAll() {
val snapshot = _sessions.value.values.toList()
_sessions.update { emptyMap() }
ioExecutor.execute { snapshot.forEach { tearDown(it) } }
}
fun getSessionsForProfile(profileId: String): List<SessionState> =
_sessions.value.values.filter { it.profileId == profileId }
fun isProfileConnected(profileId: String): Boolean =
_sessions.value.values.any {
it.profileId == profileId && it.status == SessionState.Status.CONNECTED
}
}
@@ -0,0 +1,99 @@
package sh.haven.core.bleserial
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/** A [BleSerialLink] with no Bluetooth behind it — drives the session/manager in tests. */
private class FakeBleLink(override val displayName: String? = "FakeBLE") : BleSerialLink {
var onData: ((ByteArray) -> Unit)? = null
var onError: ((Throwable) -> Unit)? = null
val written = mutableListOf<ByteArray>()
var closed = false
override fun start(onData: (ByteArray) -> Unit, onError: (Throwable) -> Unit) {
this.onData = onData
this.onError = onError
}
override fun write(bytes: ByteArray) { written.add(bytes) }
override fun close() { closed = true }
/** Simulate a notification from the peripheral. */
fun emit(bytes: ByteArray) = onData?.invoke(bytes)
fun dropLink() = onError?.invoke(RuntimeException("out of range"))
}
class BleSerialSessionTest {
private fun managerWith(link: FakeBleLink): BleSerialSessionManager {
// ApplicationContext is only touched by the lazy connector, which the
// openLink seam replaces — so a null context is never dereferenced.
@Suppress("UNCHECKED_CAST")
val mgr = BleSerialSessionManager(context = mockContext())
mgr.openLink = { _, _ -> link }
return mgr
}
private fun mockContext(): android.content.Context =
io.mockk.mockk(relaxed = true)
@Test
fun `connect then create terminal delivers peripheral bytes`() = runTest {
val link = FakeBleLink()
val mgr = managerWith(link)
val id = mgr.registerSession("p1", "nRF", "AA:BB:CC:DD:EE:FF")
mgr.connectSession(id)
assertEquals(BleSerialSessionManager.SessionState.Status.CONNECTED, mgr.sessions.value[id]!!.status)
assertEquals("FakeBLE", mgr.sessions.value[id]!!.deviceName)
val received = mutableListOf<Byte>()
mgr.createTerminalSession(id) { buf, off, len -> received += buf.copyOfRange(off, off + len).toList() }
link.emit("hello".toByteArray())
assertArrayEquals("hello".toByteArray(), received.toByteArray())
}
@Test
fun `sendInput reaches the link as UTF-8`() = runTest {
val link = FakeBleLink()
val mgr = managerWith(link)
val id = mgr.registerSession("p1", "nRF", "AA:BB:CC:DD:EE:FF")
mgr.connectSession(id)
mgr.createTerminalSession(id) { _, _, _ -> }
mgr.sendInput(id, "G28\n")
assertEquals(1, link.written.size)
assertArrayEquals("G28\n".toByteArray(), link.written[0])
}
@Test
fun `link drop marks the session disconnected`() = runTest {
val link = FakeBleLink()
val mgr = managerWith(link)
val id = mgr.registerSession("p1", "nRF", "AA:BB:CC:DD:EE:FF")
mgr.connectSession(id)
mgr.createTerminalSession(id) { _, _, _ -> }
link.dropLink()
assertEquals(BleSerialSessionManager.SessionState.Status.DISCONNECTED, mgr.sessions.value[id]!!.status)
assertTrue(link.closed)
}
@Test
fun `detach stops delivery without closing the link`() = runTest {
val link = FakeBleLink()
val mgr = managerWith(link)
val id = mgr.registerSession("p1", "nRF", "AA:BB:CC:DD:EE:FF")
mgr.connectSession(id)
val received = mutableListOf<Byte>()
mgr.createTerminalSession(id) { buf, off, len -> received += buf.copyOfRange(off, off + len).toList() }
mgr.detachTerminalSession(id)
link.emit("dropped".toByteArray())
assertTrue(received.isEmpty())
assertTrue(!link.closed)
}
}