提交 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,44 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.usbserial"
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)
// CDC-ACM + CH34x/FTDI/CP21xx/Prolific USB serial drivers.
implementation(libs.usbserial)
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,132 @@
package sh.haven.core.usbserial
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import com.hoho.android.usbserial.driver.UsbSerialPort
import com.hoho.android.usbserial.driver.UsbSerialProber
import com.hoho.android.usbserial.util.SerialInputOutputManager
/**
* Opens a USB-serial link to an attached adapter using usb-serial-for-android's
* driver probe (CDC-ACM, CH34x, FTDI, CP21xx, Prolific). The USB runtime
* permission must already be granted for [device] — the caller (UI) owns that
* request, exactly as the BT-serial path owns BLUETOOTH_CONNECT.
*
* `connect` does blocking USB IO (open + control transfers for line coding) and
* must run off the main thread.
*/
class AndroidUsbSerialConnector(private val usbManager: UsbManager) {
fun connect(device: UsbDevice, params: UsbSerialParams): UsbSerialLink {
val driver = UsbSerialProber.getDefaultProber().probeDevice(device)
?: throw IllegalStateException(
"No serial driver for ${device.productName ?: device.deviceName} " +
"(${vidPid(device)}) — not a recognised USB-serial adapter",
)
val connection: UsbDeviceConnection = usbManager.openDevice(device)
?: throw IllegalStateException(
"Could not open ${device.productName ?: device.deviceName} — USB permission not granted",
)
val port = driver.ports.firstOrNull()
?: run {
connection.close()
throw IllegalStateException("Serial adapter exposes no ports")
}
try {
port.open(connection)
port.setParameters(
params.baudRate,
params.dataBits,
stopBitsConst(params.stopBits),
parityConst(params.parity),
)
// Flow control (best-effort — not every chipset implements it).
runCatching { port.setFlowControl(flowControlConst(params.flowControl)) }
// Assert DTR — and RTS unless RTS/CTS flow control owns it — on open,
// exactly as a hardware terminal (PuTTY, screen, minicom) does. Many
// CDC-ACM devices gate ALL data flow on DTR: the nRF USB-CDC stack
// returns NRF_ERROR_INVALID_STATE from its write until DTR is set,
// and Arduino `while (!Serial)` sketches never start. Without this
// the port opens but no bytes move. Best-effort — some drivers do
// not implement modem-control lines and throw here.
runCatching { port.setDTR(true) }
if (params.flowControl != UsbSerialParams.FlowControl.RTS_CTS) {
runCatching { port.setRTS(true) }
}
} catch (e: Exception) {
runCatching { port.close() }
runCatching { connection.close() }
throw e
}
return AndroidUsbSerialLink(port, connection, device.productName)
}
private companion object {
fun vidPid(d: UsbDevice) =
"%04x:%04x".format(d.vendorId, d.productId)
fun stopBitsConst(s: UsbSerialParams.StopBits) = when (s) {
UsbSerialParams.StopBits.ONE -> UsbSerialPort.STOPBITS_1
UsbSerialParams.StopBits.ONE_POINT_FIVE -> UsbSerialPort.STOPBITS_1_5
UsbSerialParams.StopBits.TWO -> UsbSerialPort.STOPBITS_2
}
fun parityConst(p: UsbSerialParams.Parity) = when (p) {
UsbSerialParams.Parity.NONE -> UsbSerialPort.PARITY_NONE
UsbSerialParams.Parity.ODD -> UsbSerialPort.PARITY_ODD
UsbSerialParams.Parity.EVEN -> UsbSerialPort.PARITY_EVEN
UsbSerialParams.Parity.MARK -> UsbSerialPort.PARITY_MARK
UsbSerialParams.Parity.SPACE -> UsbSerialPort.PARITY_SPACE
}
fun flowControlConst(f: UsbSerialParams.FlowControl) = when (f) {
UsbSerialParams.FlowControl.NONE -> UsbSerialPort.FlowControl.NONE
UsbSerialParams.FlowControl.RTS_CTS -> UsbSerialPort.FlowControl.RTS_CTS
UsbSerialParams.FlowControl.XON_XOFF -> UsbSerialPort.FlowControl.XON_XOFF
}
}
}
/** [UsbSerialLink] backed by an open usb-serial-for-android port + IO manager. */
private class AndroidUsbSerialLink(
private val port: UsbSerialPort,
private val connection: UsbDeviceConnection,
override val displayName: String?,
) : UsbSerialLink {
@Volatile
private var io: SerialInputOutputManager? = null
override fun start(onData: (ByteArray) -> Unit, onError: (Throwable) -> Unit) {
val manager = SerialInputOutputManager(port).apply {
readTimeout = READ_TIMEOUT_MS
listener = object : SerialInputOutputManager.Listener {
override fun onNewData(data: ByteArray?) {
if (data != null && data.isNotEmpty()) onData(data)
}
override fun onRunError(e: Exception?) {
onError(e ?: RuntimeException("USB serial read error"))
}
}
}
io = manager
manager.start()
}
override fun write(bytes: ByteArray) {
port.write(bytes, WRITE_TIMEOUT_MS)
}
override fun close() {
runCatching { io?.stop() }
runCatching { port.close() }
runCatching { connection.close() }
}
private companion object {
const val READ_TIMEOUT_MS = 200
const val WRITE_TIMEOUT_MS = 2000
}
}
@@ -0,0 +1,114 @@
package sh.haven.core.usbserial
/**
* A live USB-serial byte pipe to an attached adapter (CDC-ACM, CH34x, FTDI,
* CP21xx, …). Callback-shaped rather than stream-shaped because
* usb-serial-for-android delivers reads through a [com.hoho.android.usbserial.util.SerialInputOutputManager]
* listener, not a blocking InputStream — so [UsbSerialSession] stays
* transport-agnostic and unit-testable with a fake link, no USB hardware.
*/
interface UsbSerialLink {
/** Human-facing adapter name (product string), if the device exposed one. */
val displayName: String?
/**
* Begin pumping incoming bytes to [onData]. [onError] fires once if the read
* loop dies on its own (cable pulled, adapter error); it does NOT fire on an
* explicit [close].
*/
fun start(onData: (ByteArray) -> Unit, onError: (Throwable) -> Unit)
/** Write keystrokes / commands to the device. */
fun write(bytes: ByteArray)
/** Tear down the read loop and release the USB device. Idempotent. */
fun close()
}
/**
* Serial line configuration. Defaults (115200 8N1) suit a Duet3D G-code console
* and most Arduino sketches; the profile editor overrides per device.
*/
data class UsbSerialParams(
val baudRate: Int = 115200,
/** Data bits 5..8. */
val dataBits: Int = 8,
val stopBits: StopBits = StopBits.ONE,
val parity: Parity = Parity.NONE,
val flowControl: FlowControl = FlowControl.NONE,
) {
enum class StopBits { ONE, ONE_POINT_FIVE, TWO }
enum class Parity { NONE, ODD, EVEN, MARK, SPACE }
enum class FlowControl { NONE, RTS_CTS, XON_XOFF }
/**
* Serialise the line format (everything but the baud rate) to the compact
* `"<dataBits>,<parity>,<stopBits>,<flow>"` string stored in a profile —
* baud lives in its own column, so it is deliberately excluded here.
*/
fun toConfigString(): String =
"$dataBits,${parity.code},${stopBits.code},${flowControl.code}"
companion object {
/**
* Rebuild params from [baudRate] plus a [config] string produced by
* [toConfigString]. Missing / blank / unrecognised tokens fall back to
* 8N1, no flow control — so a legacy profile that only stored a baud
* rate (config == null) still opens with sane defaults.
*/
fun fromConfigString(baudRate: Int, config: String?): UsbSerialParams {
val t = config?.split(",").orEmpty()
fun tok(i: Int) = t.getOrNull(i)?.trim()?.takeIf { it.isNotEmpty() }
return UsbSerialParams(
baudRate = baudRate,
dataBits = tok(0)?.toIntOrNull()?.coerceIn(5, 8) ?: 8,
parity = parityFromCode(tok(1)),
stopBits = stopBitsFromCode(tok(2)),
flowControl = flowControlFromCode(tok(3)),
)
}
}
}
private val UsbSerialParams.Parity.code: String
get() = when (this) {
UsbSerialParams.Parity.NONE -> "N"
UsbSerialParams.Parity.ODD -> "O"
UsbSerialParams.Parity.EVEN -> "E"
UsbSerialParams.Parity.MARK -> "M"
UsbSerialParams.Parity.SPACE -> "S"
}
private fun parityFromCode(c: String?) = when (c?.uppercase()) {
"O" -> UsbSerialParams.Parity.ODD
"E" -> UsbSerialParams.Parity.EVEN
"M" -> UsbSerialParams.Parity.MARK
"S" -> UsbSerialParams.Parity.SPACE
else -> UsbSerialParams.Parity.NONE
}
private val UsbSerialParams.StopBits.code: String
get() = when (this) {
UsbSerialParams.StopBits.ONE -> "1"
UsbSerialParams.StopBits.ONE_POINT_FIVE -> "1.5"
UsbSerialParams.StopBits.TWO -> "2"
}
private fun stopBitsFromCode(c: String?) = when (c) {
"1.5" -> UsbSerialParams.StopBits.ONE_POINT_FIVE
"2" -> UsbSerialParams.StopBits.TWO
else -> UsbSerialParams.StopBits.ONE
}
private val UsbSerialParams.FlowControl.code: String
get() = when (this) {
UsbSerialParams.FlowControl.NONE -> "none"
UsbSerialParams.FlowControl.RTS_CTS -> "rtscts"
UsbSerialParams.FlowControl.XON_XOFF -> "xonxoff"
}
private fun flowControlFromCode(c: String?) = when (c?.lowercase()) {
"rtscts" -> UsbSerialParams.FlowControl.RTS_CTS
"xonxoff" -> UsbSerialParams.FlowControl.XON_XOFF
else -> UsbSerialParams.FlowControl.NONE
}
@@ -0,0 +1,98 @@
package sh.haven.core.usbserial
import android.util.Log
import java.io.Closeable
import java.util.concurrent.atomic.AtomicBoolean
/**
* A live USB-serial terminal session over an open [UsbSerialLink].
*
* Same transport-session shape as BtSerialSession / EtSession / MoshSession, so
* [UsbSerialSessionManager] mirrors the other managers and the terminal
* ViewModel wires it identically (the callback IS termlib's `feedOutput`). The
* read loop lives inside the link (usb-serial-for-android's IO manager thread);
* this class just routes its bytes to the terminal and guards teardown.
*
* @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 UsbSerialSession(
val sessionId: String,
private val link: UsbSerialLink,
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]; unlike [callback] it survives [detach] 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 = { buf ->
if (!closed.get()) {
callback?.invoke(buf, 0, buf.size)
tap?.invoke(buf, 0, buf.size)
}
},
onError = { e ->
// The link died on its own (cable pulled, adapter error). Report
// the drop once; an explicit close() already set `closed`, so this
// no-ops there.
if (!closed.get()) Log.d(TAG, "read loop ended for $sessionId: ${e.message}")
if (closed.compareAndSet(false, true)) {
runCatching { link.close() }
onDisconnected(sessionId)
}
},
)
}
/** Send keystrokes / commands to the device. 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 displayName: 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 = "UsbSerialSession"
}
}
@@ -0,0 +1,242 @@
package sh.haven.core.usbserial
import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
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 = "UsbSerialSessionManager"
/**
* Manages USB-serial terminal sessions, mirroring [sh.haven.core.btserial]:
* register → connect (open the USB serial port) → create terminal →
* detach/reattach/remove. Only the connect step touches hardware and runs on IO.
*
* A device is identified by its `vendorId:productId` hex key (from the saved
* profile); at connect time we resolve it against the currently-attached
* devices, since USB device names/paths are not stable across re-plugs.
*/
@Singleton
class UsbSerialSessionManager @Inject constructor(
@ApplicationContext private val context: Context,
) {
data class SessionState(
val sessionId: String,
val profileId: String,
val label: String,
val status: Status,
/** `vendorId:productId` hex, e.g. `1a86:7523`. */
val deviceKey: String = "",
val params: UsbSerialParams = UsbSerialParams(),
val deviceName: String? = null,
/** Open link, set by [connectSession], consumed by [createTerminalSession]. */
val link: UsbSerialLink? = null,
val session: UsbSerialSession? = null,
) {
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
}
private val usbManager: UsbManager
get() = context.getSystemService(Context.USB_SERVICE) as UsbManager
// Built on first real connect only (tests override openLink before that, so
// no USB is touched under test).
private val connector by lazy { AndroidUsbSerialConnector(usbManager) }
/** Resolve a saved `vid:pid` key to a currently-attached device. Test seam. */
internal var resolveDevice: (deviceKey: String) -> UsbDevice? = ::defaultResolve
/** Open the serial link for a resolved device. Test seam (real path = USB IO). */
internal var openLink: (device: UsbDevice, params: UsbSerialParams) -> UsbSerialLink =
{ device, params -> connector.connect(device, 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, "usbserial-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,
deviceKey: String,
params: UsbSerialParams = UsbSerialParams(),
): String {
val sessionId = UUID.randomUUID().toString()
_sessions.update { map ->
map + (sessionId to SessionState(
sessionId = sessionId,
profileId = profileId,
label = label,
status = SessionState.Status.CONNECTING,
deviceKey = deviceKey,
params = params,
))
}
return sessionId
}
/**
* Open the USB serial link (blocking, on IO). Sets status CONNECTED and
* stashes the link for [createTerminalSession] to wrap. Throws on failure
* (status → ERROR). Mirrors BtSerialSessionManager.connectSession.
*/
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.deviceKey.isEmpty()) throw IllegalStateException("No device key for $sessionId")
val link = try {
withContext(Dispatchers.IO) {
val device = resolveDevice(state.deviceKey)
?: throw IllegalStateException("USB device ${state.deviceKey} is not attached")
openLink(device, state.params)
}
} catch (e: Exception) {
Log.e(TAG, "USB serial 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 device output to [onDataReceived]. Non-suspend so the terminal
* syncSessions loop can call it. Idempotent.
*/
fun createTerminalSession(
sessionId: String,
onDataReceived: (ByteArray, Int, Int) -> Unit,
): UsbSerialSession? {
val state = _sessions.value[sessionId] ?: return null
state.session?.let { return it }
val link = state.link ?: return null
val session = UsbSerialSession(
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 USB-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
}
private fun defaultResolve(deviceKey: String): UsbDevice? {
val (vid, pid) = parseKey(deviceKey) ?: return null
return usbManager.deviceList.values.firstOrNull {
it.vendorId == vid && it.productId == pid
}
}
companion object {
/** `1a86:7523` → (0x1a86, 0x7523); null if malformed. */
fun parseKey(deviceKey: String): Pair<Int, Int>? {
val parts = deviceKey.split(":")
if (parts.size < 2) return null
val vid = parts[0].toIntOrNull(16) ?: return null
val pid = parts[1].toIntOrNull(16) ?: return null
return vid to pid
}
/** Build the stable key stored in the profile. */
fun deviceKey(vendorId: Int, productId: Int): String =
"%04x:%04x".format(vendorId, productId)
}
}
@@ -0,0 +1,177 @@
package sh.haven.core.usbserial
import android.hardware.usb.UsbDevice
import io.mockk.mockk
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* A [UsbSerialLink] with no hardware: the device's "output" is whatever the test
* feeds via [deviceSends]; the app's keystrokes accumulate in [appToDevice].
*/
private class FakeLink : UsbSerialLink {
val appToDevice = ByteArrayOutputStream()
val closed = AtomicBoolean(false)
private var onData: ((ByteArray) -> Unit)? = null
private var onError: ((Throwable) -> Unit)? = null
override val displayName: String? = "Bench Adapter"
override fun start(onData: (ByteArray) -> Unit, onError: (Throwable) -> Unit) {
this.onData = onData
this.onError = onError
}
override fun write(bytes: ByteArray) {
appToDevice.write(bytes)
}
override fun close() {
closed.set(true)
}
fun deviceSends(bytes: ByteArray) = onData?.invoke(bytes)
/** Simulate the cable being pulled / adapter erroring mid-session. */
fun deviceHangup() = onError?.invoke(RuntimeException("USB detached"))
}
class UsbSerialSessionTest {
@Test
fun `device output reaches the terminal callback`() {
val link = FakeLink()
val received = ByteArrayOutputStream()
val latch = CountDownLatch(1)
val session = UsbSerialSession(
sessionId = "s1",
link = link,
onDataReceived = { buf, off, len ->
received.write(buf, off, len)
if (received.size() >= 3) latch.countDown()
},
onDisconnected = {},
)
session.start()
link.deviceSends("ok\n".toByteArray())
assertTrue("callback should receive device bytes", latch.await(2, TimeUnit.SECONDS))
assertEquals("ok\n", received.toString("UTF-8"))
session.close()
}
@Test
fun `keystrokes are written to the device`() {
val link = FakeLink()
val session = UsbSerialSession("s2", link, onDataReceived = { _, _, _ -> }, onDisconnected = {})
session.start()
session.sendInput("G28\n".toByteArray())
assertArrayEquals("G28\n".toByteArray(), link.appToDevice.toByteArray())
session.close()
}
@Test
fun `cable pull fires onDisconnected exactly once`() {
val link = FakeLink()
val count = java.util.concurrent.atomic.AtomicInteger(0)
val session = UsbSerialSession(
"s3", link,
onDataReceived = { _, _, _ -> },
onDisconnected = { count.incrementAndGet() },
)
session.start()
link.deviceHangup()
link.deviceHangup() // a second error must not double-report
assertEquals(1, count.get())
assertTrue(session.isClosed)
assertTrue("link released on drop", link.closed.get())
}
@Test
fun `explicit close does NOT fire onDisconnected`() {
val link = FakeLink()
val fired = AtomicBoolean(false)
val session = UsbSerialSession(
"s4", link,
onDataReceived = { _, _, _ -> },
onDisconnected = { fired.set(true) },
)
session.start()
session.close()
assertTrue("link closed", link.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 link = FakeLink()
val a = ByteArrayOutputStream()
val session = UsbSerialSession("s5", link, onDataReceived = { b, o, l -> a.write(b, o, l) }, onDisconnected = {})
session.start()
session.detach()
link.deviceSends("lost".toByteArray())
assertEquals("no delivery while detached", 0, a.size())
val b = ByteArrayOutputStream()
session.reattach { buf, off, len -> b.write(buf, off, len) }
link.deviceSends("kept".toByteArray())
assertEquals("kept", b.toString("UTF-8"))
session.close()
}
@Test
fun `manager connect-create-send-remove lifecycle`() = runTest {
val link = FakeLink()
val mgr = UsbSerialSessionManager(context = mockk(relaxed = true)).apply {
resolveDevice = { mockk<UsbDevice>(relaxed = true) }
openLink = { _, _ -> link }
}
val id = mgr.registerSession("p1", "duet", deviceKey = "1d50:60ec")
assertEquals(UsbSerialSessionManager.SessionState.Status.CONNECTING, mgr.sessions.value[id]!!.status)
mgr.connectSession(id)
assertEquals(UsbSerialSessionManager.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, "M115\n")
assertArrayEquals("M115\n".toByteArray(), link.appToDevice.toByteArray())
mgr.removeSession(id)
assertFalse(mgr.sessions.value.containsKey(id))
}
@Test
fun `unattached device surfaces ERROR`() = runTest {
val mgr = UsbSerialSessionManager(context = mockk(relaxed = true)).apply {
resolveDevice = { null } // nothing plugged in
}
val id = mgr.registerSession("p2", "gone", deviceKey = "1a86:7523")
runCatching { mgr.connectSession(id) }
assertEquals(UsbSerialSessionManager.SessionState.Status.ERROR, mgr.sessions.value[id]!!.status)
}
@Test
fun `deviceKey round-trips through parseKey`() {
assertEquals("1a86:7523", UsbSerialSessionManager.deviceKey(0x1a86, 0x7523))
assertEquals(0x1a86 to 0x7523, UsbSerialSessionManager.parseKey("1a86:7523"))
assertNull(UsbSerialSessionManager.parseKey("nonsense"))
}
}