提交 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.btserial"
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,18 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!--
Bluetooth-serial (SPP) console (#406). BLUETOOTH_CONNECT (API 31+) covers both
listing bonded devices and opening the RFCOMM socket; the legacy BLUETOOTH
permission is the pre-31 equivalent. No scanning — pairing is done in Android
Settings — so BLUETOOTH_SCAN is deliberately not requested.
Declared here, in the module that uses Bluetooth, so the app inherits it via
manifest merge rather than relying on an unrelated module's manifest (which
the app does NOT actually depend on — #406 device test caught the gap).
-->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
</manifest>
@@ -0,0 +1,112 @@
package sh.haven.core.btserial
import android.util.Log
import java.io.Closeable
import java.util.concurrent.atomic.AtomicBoolean
/**
* A live Bluetooth-serial terminal session over an open [BtSerialTransport].
*
* A dedicated reader thread pumps RFCOMM input to the terminal callback;
* keystrokes go back out via [sendInput]. Same transport-session shape as
* EtSession / MoshSession, so [BtSerialSessionManager] mirrors the other
* managers and the terminal ViewModel wires it identically (the callback IS
* termlib's `feedOutput`).
*
* @param onDataReceived output sink — (buffer, offset, length), the emulator feed.
* @param onDisconnected fired once when the link drops on its own (NOT on an
* explicit [close], which is a user teardown).
*/
class BtSerialSession(
val sessionId: String,
private val transport: BtSerialTransport,
onDataReceived: (ByteArray, Int, Int) -> Unit,
private val onDisconnected: (String) -> Unit,
) : Closeable {
// Fetch the streams ONCE (some stream getters install a fresh pipe per call
// and orphan buffered bytes — cf. the JSch #381 lesson).
private val input = transport.input
private val output = transport.output
@Volatile
private var callback: ((ByteArray, Int, Int) -> Unit)? = onDataReceived
/**
* Optional read-only output tap (the serial↔TCP bridge). Fires alongside the
* terminal [callback]; unlike [callback] it survives [detach] and is dropped
* only by [setTap] or [close]. The tap MUST consume `buf` synchronously — the
* reader below reuses one buffer, so the tap can't hand the array off to
* another thread. SerialTcpBridge writes to its sockets inline, so it's safe.
*/
@Volatile
private var tap: ((ByteArray, Int, Int) -> Unit)? = null
private val closed = AtomicBoolean(false)
fun setTap(t: ((ByteArray, Int, Int) -> Unit)?) { tap = t }
private val reader = Thread({
val buf = ByteArray(4096)
try {
while (!closed.get()) {
val n = input.read(buf)
if (n < 0) break // EOF — remote closed the link
if (n > 0) {
callback?.invoke(buf, 0, n)
tap?.invoke(buf, 0, n)
}
}
} catch (e: Exception) {
if (!closed.get()) Log.d(TAG, "read loop ended for $sessionId: ${e.message}")
} finally {
// A self-terminating loop (EOF/error) reports the drop; an explicit
// close() already set `closed`, so this no-ops there.
if (closed.compareAndSet(false, true)) {
runCatching { transport.close() }
onDisconnected(sessionId)
}
}
}, "btserial-read-$sessionId").apply { isDaemon = true }
fun start() {
reader.start()
}
/** Send keystrokes to the device. No-op once closed. */
fun sendInput(bytes: ByteArray) {
if (closed.get()) return
try {
output.write(bytes)
output.flush()
} 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() = transport.remoteName
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 { transport.close() }
}
}
companion object {
private const val TAG = "BtSerialSession"
}
}
@@ -0,0 +1,209 @@
package sh.haven.core.btserial
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 = "BtSerialSessionManager"
/**
* Manages Bluetooth-serial terminal sessions (#406), mirroring
* [sh.haven.core.et.EtSessionManager]: register → connect (open RFCOMM) →
* create terminal → detach/reattach/remove.
*
* The RFCOMM connect is the only blocking part and runs on IO in
* [createTerminalSession]; everything else is registry bookkeeping.
*/
@Singleton
class BtSerialSessionManager @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 secure: Boolean = true,
val deviceName: String? = null,
/** Open RFCOMM link, set by [connectSession], consumed by [createTerminalSession]. */
val transport: BtSerialTransport? = null,
val session: BtSerialSession? = null,
) {
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
}
// Built on first real connect only (tests override openTransport before that,
// so no Bluetooth is touched under test).
private val connector by lazy { AndroidBtSerialConnector(context) }
/**
* Opens the RFCOMM transport. Test seam — the real path dials a Bluetooth
* socket via [AndroidBtSerialConnector]; tests substitute piped streams.
*/
internal var openTransport: (address: String, secure: Boolean) -> BtSerialTransport =
{ address, secure -> connector.connect(address, secure) }
private val _sessions = MutableStateFlow<Map<String, SessionState>>(emptyMap())
val sessions: StateFlow<Map<String, SessionState>> = _sessions.asStateFlow()
private val ioExecutor = Executors.newSingleThreadExecutor { r ->
Thread(r, "btserial-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,
secure: Boolean = true,
): 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,
secure = secure,
))
}
return sessionId
}
/**
* Open the RFCOMM link (blocking, on IO). Sets status CONNECTED and stashes
* the transport for [createTerminalSession] to wrap. Throws on failure
* (status → ERROR). Mirrors EtSessionManager.connectSession.
*/
suspend fun connectSession(sessionId: String) {
val state = _sessions.value[sessionId]
?: throw IllegalStateException("Session $sessionId not found")
if (state.transport != null || state.session != null) return
if (state.deviceAddress.isEmpty()) throw IllegalStateException("No device address for $sessionId")
val transport = try {
withContext(Dispatchers.IO) { openTransport(state.deviceAddress, state.secure) }
} catch (e: Exception) {
Log.e(TAG, "RFCOMM 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 = transport.remoteName,
transport = transport,
))
}
}
/**
* Wrap the already-open transport ([connectSession] first) in a terminal
* session, wiring device output to [onDataReceived]. Non-suspend so the
* terminal syncSessions loop can call it. Idempotent.
*/
fun createTerminalSession(
sessionId: String,
onDataReceived: (ByteArray, Int, Int) -> Unit,
): BtSerialSession? {
val state = _sessions.value[sessionId] ?: return null
state.session?.let { return it }
val transport = state.transport ?: return null
val session = BtSerialSession(
sessionId = sessionId,
transport = transport,
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.transport != 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 BT-serial session: $sessionId")
session.sendInput(text.toByteArray(Charsets.UTF_8))
}
// Close the terminal session if one exists (it owns the transport), else the
// bare transport opened by connectSession before a terminal was created.
private fun tearDown(state: SessionState) {
runCatching { state.session?.close() ?: state.transport?.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,63 @@
package sh.haven.core.btserial
import android.annotation.SuppressLint
import android.bluetooth.BluetoothManager
import android.content.Context
import java.io.InputStream
import java.io.OutputStream
import java.util.UUID
/**
* An open Bluetooth-serial (RFCOMM / SPP) byte pipe to a paired device.
*
* Deliberately just streams + close, so the terminal-facing code
* ([BtSerialSession]) is transport-agnostic and unit-testable with plain piped
* streams — no Bluetooth hardware in the tests.
*/
interface BtSerialTransport {
val input: InputStream
val output: OutputStream
val remoteName: String?
fun close()
}
/**
* Opens a Bluetooth Classic RFCOMM connection to a **bonded** device using the
* standard Serial Port Profile UUID — the same mechanism Reticulum's shipping
* [network.reticulum.android.spp.AndroidSppDriver] uses, and what a BT-to-serial
* console adapter presents (#406).
*
* `connect` blocks (1–12 s) and must run off the main thread. BLUETOOTH_CONNECT
* must be granted before calling; the caller (UI) owns that runtime request.
*/
class AndroidBtSerialConnector(private val context: Context) {
@SuppressLint("MissingPermission") // BLUETOOTH_CONNECT gated at the call site
fun connect(address: String, secure: Boolean = true): BtSerialTransport {
val adapter = (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
?: throw IllegalStateException("This device has no Bluetooth adapter")
val device = adapter.getRemoteDevice(address)
val socket = if (secure) {
device.createRfcommSocketToServiceRecord(SPP_UUID)
} else {
device.createInsecureRfcommSocketToServiceRecord(SPP_UUID)
}
// An in-progress discovery scan slows every connect and makes RFCOMM
// flaky — SPP callers are expected to cancel it first.
runCatching { adapter.cancelDiscovery() }
socket.connect()
return object : BtSerialTransport {
override val input: InputStream get() = socket.inputStream
override val output: OutputStream get() = socket.outputStream
override val remoteName: String? = device.name
override fun close() {
runCatching { socket.close() }
}
}
}
companion object {
/** Standard Serial Port Profile UUID — matches AndroidSppDriver.SPP_UUID. */
val SPP_UUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
}
}
@@ -0,0 +1,162 @@
package sh.haven.core.btserial
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* A [BtSerialTransport] backed by plain piped streams — the device's "output"
* is what the test writes into [deviceToApp]; the app's keystrokes land in
* [appToDevice]. No Bluetooth involved.
*/
private class FakeTransport : BtSerialTransport {
private val deviceSink = PipedOutputStream()
val deviceToApp = PipedInputStream(deviceSink, 64 * 1024)
val appToDevice = ByteArrayOutputStream()
val closed = AtomicBoolean(false)
override val input: InputStream get() = deviceToApp
override val output = appToDevice
override val remoteName: String? = "Bench Console"
override fun close() {
closed.set(true)
runCatching { deviceSink.close() }
}
/** Simulate the device sending bytes to the app. */
fun deviceSends(bytes: ByteArray) {
deviceSink.write(bytes)
deviceSink.flush()
}
}
class BtSerialSessionTest {
@Test
fun `device output reaches the terminal callback`() {
val transport = FakeTransport()
val received = ByteArrayOutputStream()
val latch = CountDownLatch(1)
val session = BtSerialSession(
sessionId = "s1",
transport = transport,
onDataReceived = { buf, off, len ->
received.write(buf, off, len)
if (received.size() >= 7) latch.countDown()
},
onDisconnected = {},
)
session.start()
transport.deviceSends("Switch>".toByteArray())
assertTrue("callback should receive device bytes", latch.await(2, TimeUnit.SECONDS))
assertEquals("Switch>", received.toString("UTF-8"))
session.close()
}
@Test
fun `keystrokes are written to the device`() {
val transport = FakeTransport()
val session = BtSerialSession("s2", transport, onDataReceived = { _, _, _ -> }, onDisconnected = {})
session.start()
session.sendInput("enable\n".toByteArray())
assertArrayEquals("enable\n".toByteArray(), transport.appToDevice.toByteArray())
session.close()
}
@Test
fun `remote hangup fires onDisconnected exactly once`() {
val transport = FakeTransport()
val dropped = CountDownLatch(1)
val count = java.util.concurrent.atomic.AtomicInteger(0)
val session = BtSerialSession(
"s3", transport,
onDataReceived = { _, _, _ -> },
onDisconnected = { count.incrementAndGet(); dropped.countDown() },
)
session.start()
transport.close() // device end goes away → read loop hits EOF/error
assertTrue("onDisconnected should fire on hangup", dropped.await(2, TimeUnit.SECONDS))
assertEquals(1, count.get())
assertTrue(session.isClosed)
}
@Test
fun `explicit close does NOT fire onDisconnected`() {
val transport = FakeTransport()
val fired = AtomicBoolean(false)
val session = BtSerialSession(
"s4", transport,
onDataReceived = { _, _, _ -> },
onDisconnected = { fired.set(true) },
)
session.start()
session.close()
Thread.sleep(200) // let the reader unwind
assertTrue("transport closed", transport.closed.get())
assertFalse("user teardown must not look like a drop", fired.get())
assertTrue(session.isClosed)
}
@Test
fun `detach stops delivery, reattach resumes it`() {
val transport = FakeTransport()
val a = ByteArrayOutputStream()
val session = BtSerialSession("s5", transport, onDataReceived = { b, o, l -> a.write(b, o, l) }, onDisconnected = {})
session.start()
session.detach()
transport.deviceSends("lost".toByteArray())
Thread.sleep(150)
assertEquals("no delivery while detached", 0, a.size())
val b = ByteArrayOutputStream()
val latch = CountDownLatch(1)
session.reattach { buf, off, len -> b.write(buf, off, len); latch.countDown() }
transport.deviceSends("kept".toByteArray())
assertTrue(latch.await(2, TimeUnit.SECONDS))
assertEquals("kept", b.toString("UTF-8"))
session.close()
}
@Test
fun `manager connect-create-send-remove lifecycle`() = runTest {
val transport = FakeTransport()
val mgr = BtSerialSessionManager(context = mockContext()).apply {
openTransport = { _, _ -> transport }
}
val id = mgr.registerSession("p1", "core-switch", deviceAddress = "AA:BB:CC:DD:EE:FF")
assertEquals(BtSerialSessionManager.SessionState.Status.CONNECTING, mgr.sessions.value[id]!!.status)
mgr.connectSession(id) // opens the RFCOMM transport (blocking, on IO)
assertEquals(BtSerialSessionManager.SessionState.Status.CONNECTED, mgr.sessions.value[id]!!.status)
assertTrue(mgr.isReadyForTerminal(id))
val session = mgr.createTerminalSession(id) { _, _, _ -> }
assertTrue(session != null)
assertTrue(mgr.isProfileConnected("p1"))
mgr.sendInput(id, "show version\n")
assertArrayEquals("show version\n".toByteArray(), transport.appToDevice.toByteArray())
mgr.removeSession(id)
assertFalse(mgr.sessions.value.containsKey(id))
}
// The manager only touches Context inside AndroidBtSerialConnector, which the
// openTransport seam replaces in tests — so a relaxed stub is enough.
private fun mockContext(): android.content.Context = io.mockk.mockk(relaxed = true)
}