diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 3bb5932..ab3c7ea 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -96,6 +96,8 @@ kotlin { dependencies { implementation(libs.androidx.core.ktx) implementation(libs.androidx.activity.compose) + // USB serial adapters (FTDI, CP210x, CH34x, PL2303, CDC-ACM): the modem as a serial port on one + implementation(libs.usb.serial) implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.datastore.preferences) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index ed9a177..6f0a969 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -22,6 +22,10 @@ + + + + + + diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt index 0f06116..add4a14 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/Bridges.kt @@ -37,6 +37,15 @@ object Bridges { private var tcp: TcpBridge? = null private var tcpJob: Job? = null + private val _usb = MutableStateFlow(UsbBridge.State.Stopped) + val usbState: StateFlow = _usb.asStateFlow() + private val _gadget = MutableStateFlow(UsbGadget.State.Stopped) + val gadgetState: StateFlow = _gadget.asStateFlow() + private var usb: UsbBridge? = null + private var usbJob: Job? = null + private var gadget: UsbGadget? = null + private var gadgetJob: Job? = null + private var bt: BluetoothBridge? = null private var btJob: Job? = null private var applied: BridgeSettings? = null @@ -90,6 +99,26 @@ object Bridges { t.start() } } + val usbSame = old != null && old.usb == s.usb && old.usbBaud == s.usbBaud && old.usbFormat == s.usbFormat && + old.usbCarrierOnDtr == s.usbCarrierOnDtr && old.usbDtrHangsUp == s.usbDtrHangsUp + if (!usbSame || (s.usb && usb == null)) { + stopUsb() + if (s.usb) { + val u = UsbBridge(context.applicationContext, serial, signals.asStateFlow(), format(s.usbBaud, s.usbFormat), s.usbCarrierOnDtr, s.usbDtrHangsUp) + usb = u + usbJob = scope.launch { u.state.collect { _usb.value = it } } + u.start() + } + } + if (old?.usbGadget != s.usbGadget || (s.usbGadget && gadget == null)) { + stopGadget() + if (s.usbGadget) { + val g = UsbGadget(serial) + gadget = g + gadgetJob = scope.launch { g.state.collect { _gadget.value = it } } + scope.launch { g.start() } + } + } val btSame = old != null && old.bluetooth == s.bluetooth && old.btConnectTo == s.btConnectTo if (!btSame || (s.bluetooth && bt == null)) { stopBt() @@ -106,6 +135,8 @@ object Bridges { fun stopAll() { stopTcp() stopBt() + stopUsb() + stopGadget() applied = null } @@ -116,6 +147,28 @@ object Bridges { _tcp.value = TcpBridge.State.Stopped } + private fun stopUsb() { + usb?.stop() + usb = null + usbJob?.cancel() + _usb.value = UsbBridge.State.Stopped + } + + private fun stopGadget() { + val g = gadget + gadget = null + gadgetJob?.cancel() + // (su and a rebind: off the caller's thread) + if (g != null) scope.launch { g.stop() } + _gadget.value = UsbGadget.State.Stopped + } + + /** "8N1" as a format at [baud] */ + fun format(baud: Int, f: String): SerialFormat { + val m = Regex("([5-8])([NEOMS])([12])").matchEntire(f.uppercase()) + return if (m == null) SerialFormat(baud) else SerialFormat(baud, m.groupValues[1].toInt(), m.groupValues[2][0], m.groupValues[3].toInt()) + } + private fun stopBt() { bt?.stop() bt = null diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt index edb620a..83cc322 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt @@ -125,7 +125,7 @@ class SerialBridge( } /** DTR off: the call over (as AT&D2 has it) */ - private fun dropDtr() { + fun dropDtr() { val s = signals.value if (s.offhook || s.carrier) Thread({ hangUp() }, "bridge-hangup").apply { isDaemon = true; start() } } diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt new file mode 100644 index 0000000..a8f9896 --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.bridge + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbManager +import android.os.Build +import com.hoho.android.usbserial.driver.UsbSerialPort +import com.hoho.android.usbserial.driver.UsbSerialProber +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream + +/** a serial line's character format and speed */ +data class SerialFormat(val baud: Int = 115200, val dataBits: Int = 8, val parity: Char = 'N', val stopBits: Int = 1) { + override fun toString() = "$baud $dataBits$parity$stopBits" + + val parityCode: Int get() = when (parity) { + 'E' -> UsbSerialPort.PARITY_EVEN + 'O' -> UsbSerialPort.PARITY_ODD + 'M' -> UsbSerialPort.PARITY_MARK + 'S' -> UsbSerialPort.PARITY_SPACE + else -> UsbSerialPort.PARITY_NONE + } + + val stopCode: Int get() = if (stopBits == 2) UsbSerialPort.STOPBITS_2 else UsbSerialPort.STOPBITS_1 +} + +/** + * An open USB serial adapter's port serving the modem through [bridge], + * cabled as a modem is (a null modem to the computer): its DTR out the + * modem's carrier (the computer's DCD) when [carrierOnDtr], RTS on; the + * computer's DTR (on the adapter's DSR) dropped hangs up when + * [dtrHangsUp]. Until the port fails, or [close]. + */ +class UsbPortLink( + private val port: UsbSerialPort, + private val bridge: SerialBridge, + private val signals: StateFlow, + private val name: String, + private val carrierOnDtr: Boolean = true, + private val dtrHangsUp: Boolean = true, +) { + @Volatile private var open = true + + fun close() { + open = false + runCatching { port.close() } + } + + private val input = object : InputStream() { + private val buf = ByteArray(4096) + private var have = 0 + private var at = 0 + + override fun read(): Int { + val one = ByteArray(1) + return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff + } + + override fun read(b: ByteArray, off: Int, len: Int): Int { + while (open) { + if (at < have) { + val n = minOf(len, have - at) + System.arraycopy(buf, at, b, off, n) + at += n + return n + } + // (a timeout: the port polled again, so a close is seen) + have = try { port.read(buf, 200) } catch (_: IOException) { return -1 } + at = 0 + } + return -1 + } + } + + private val output = object : OutputStream() { + override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1) + override fun write(b: ByteArray, off: Int, len: Int) { + if (!open) throw IOException("the adapter is closed") + port.write(b.copyOfRange(off, off + len), 2000) + } + } + + /** served until the adapter goes (false: another client had the modem) */ + fun serve(): Boolean { + val p = Port("usb", name, input, output) { close() } + if (!bridge.tryClaim(p)) { + close() + return false + } + val lines = Thread({ watchLines() }, "usb-lines").apply { isDaemon = true; start() } + try { + bridge.serve(p, null) + } finally { + open = false + lines.interrupt() + } + return true + } + + /** the modem's lines out, the computer's DTR in */ + private fun watchLines() { + var lastCarrier: Boolean? = null + var computerDtr: Boolean? = null + runCatching { port.setRTS(true) } + while (open) { + val s = signals.value + val carrier = if (carrierOnDtr) s.carrier else s.ready + if (carrier != lastCarrier) { + runCatching { port.setDTR(carrier) } + lastCarrier = carrier + } + if (dtrHangsUp) { + val dsr = runCatching { port.dsr }.getOrNull() + if (dsr != null) { + // (its fall: the computer's DTR dropped) + if (computerDtr == true && !dsr) bridge.dropDtr() + computerDtr = dsr + } + } + try { Thread.sleep(150) } catch (_: InterruptedException) { break } + } + } +} + +/** + * The modem on a USB serial adapter plugged into the phone (FTDI, CP210x, + * CH34x, PL2303, CDC-ACM): the first one found, again whenever one is + * plugged in while it's on; Android's permission for it asked for. + */ +@SuppressLint("UnspecifiedRegisterReceiverFlag") +class UsbBridge( + private val context: Context, + private val bridge: SerialBridge, + private val signals: StateFlow, + val format: SerialFormat = SerialFormat(), + private val carrierOnDtr: Boolean = true, + private val dtrHangsUp: Boolean = true, +) { + sealed interface State { + data object Stopped : State + data object Waiting : State + data class NeedsPermission(val device: String) : State + data class Connected(val device: String) : State + data class Failed(val why: String) : State + } + + private val _state = MutableStateFlow(State.Stopped) + val state: StateFlow = _state.asStateFlow() + + private val usb: UsbManager? get() = context.getSystemService(UsbManager::class.java) + @Volatile private var link: UsbPortLink? = null + @Volatile private var running = false + + private val receiver = object : BroadcastReceiver() { + override fun onReceive(c: Context, i: Intent) { + when (i.action) { + UsbManager.ACTION_USB_DEVICE_ATTACHED, ACTION_PERMISSION -> if (link == null) Thread { find() }.start() + UsbManager.ACTION_USB_DEVICE_DETACHED -> { + link?.close() + } + } + } + } + + fun start() { + if (running) return + if (usb == null) { + _state.value = State.Failed("this phone has no USB host") + return + } + running = true + val f = IntentFilter().apply { + addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED) + addAction(UsbManager.ACTION_USB_DEVICE_DETACHED) + addAction(ACTION_PERMISSION) + } + if (Build.VERSION.SDK_INT >= 33) context.registerReceiver(receiver, f, Context.RECEIVER_NOT_EXPORTED) + else context.registerReceiver(receiver, f) + Thread { find() }.start() + } + + fun stop() { + if (!running) return + running = false + runCatching { context.unregisterReceiver(receiver) } + link?.close() + link = null + _state.value = State.Stopped + } + + /** the adapters there are: (a name, the device) */ + fun adapters(): List> = + usb?.let { m -> UsbSerialProber.getDefaultProber().findAllDrivers(m).map { label(it.device) to it.device } }.orEmpty() + + @Synchronized + private fun find() { + if (!running || link != null) return + val m = usb ?: return + val driver = UsbSerialProber.getDefaultProber().findAllDrivers(m).firstOrNull() + if (driver == null) { + _state.value = State.Waiting + return + } + val dev = driver.device + if (!m.hasPermission(dev)) { + _state.value = State.NeedsPermission(label(dev)) + val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0 + val pi = PendingIntent.getBroadcast(context, 0, Intent(ACTION_PERMISSION).setPackage(context.packageName), flags) + m.requestPermission(dev, pi) + return + } + val conn = m.openDevice(dev) + if (conn == null) { + _state.value = State.Failed("can't open ${label(dev)}") + return + } + val port = driver.ports.first() + try { + port.open(conn) + port.setParameters(format.baud, format.dataBits, format.stopCode, format.parityCode) + } catch (e: IOException) { + runCatching { port.close() } + _state.value = State.Failed("${label(dev)}: ${e.message}") + return + } + val l = UsbPortLink(port, bridge, signals, label(dev), carrierOnDtr, dtrHangsUp) + link = l + _state.value = State.Connected(label(dev)) + Thread({ + val served = l.serve() + link = null + _state.value = if (!served) State.Failed("the modem is in use") else State.Waiting + // (another adapter, or this one again once replugged) + if (running) find() + }, "usb-bridge").apply { isDaemon = true; start() } + } + + private fun label(d: UsbDevice): String = + (listOfNotNull(d.manufacturerName, d.productName).joinToString(" ").ifBlank { null }) + ?: "USB %04x:%04x".format(d.vendorId, d.productId) + + companion object { + const val ACTION_PERMISSION = "com.neodesktop.dmodem.USB_PERMISSION" + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt new file mode 100644 index 0000000..5a9af42 --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbGadget.kt @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.bridge + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.util.concurrent.TimeUnit + +/** + * The phone's own USB port as a serial port to a computer (root only): + * a CDC-ACM function added to the phone's USB gadget in configfs (beside + * adb, MTP, …), so the computer sees a modem (COM3, /dev/ttyACM0), and + * the modem served on the phone's end of it, /dev/ttyGS0. Whether a + * phone's kernel has the function is the phone's: it says so if not. + */ +class UsbGadget( + private val bridge: SerialBridge, + /** a root shell's command run: its exit status and output (su -c on a phone; the tests' own) */ + private val root: (String) -> Pair = ::su, + private val tty: String = TTY, +) { + sealed interface State { + data object Stopped : State + /** the function there, waiting for the computer */ + data object Ready : State + data object Connected : State + data class Failed(val why: String) : State + } + + private val _state = MutableStateFlow(State.Stopped) + val state: StateFlow = _state.asStateFlow() + @Volatile private var running = false + private var thread: Thread? = null + @Volatile private var input: FileInputStream? = null + + fun start(): Boolean { + if (running) return true + val (status, out) = root(ENABLE) + if (status != 0) { + _state.value = State.Failed(out.lines().lastOrNull { it.isNotBlank() }?.trim() ?: "root refused (status $status)") + return false + } + running = true + _state.value = State.Ready + thread = Thread({ serve() }, "usb-gadget").apply { isDaemon = true; start() } + return true + } + + fun stop() { + if (!running) return + running = false + runCatching { input?.close() } + thread?.join(2000) + root(DISABLE) + _state.value = State.Stopped + } + + /** the tty served, opened again after each time the computer goes */ + private fun serve() { + while (running) { + val i = try { FileInputStream(tty) } catch (e: IOException) { + _state.value = State.Failed("$tty: ${e.message}") + running = false + return + } + val o = FileOutputStream(tty) + input = i + val p = Port("usb", "the computer on USB", i, o) { runCatching { i.close() }; runCatching { o.close() } } + if (bridge.tryClaim(p)) { + _state.value = State.Connected + bridge.serve(p, null) + } else { + runCatching { i.close() }; runCatching { o.close() } + } + if (running) { + _state.value = State.Ready + Thread.sleep(1000) + } + } + } + + companion object { + const val TTY = "/dev/ttyGS0" + + /** + * an ACM function linked into the gadget's first configuration, the + * gadget bound again (the computer sees it anew), the tty raw and + * the app's to open + */ + val ENABLE = """ + set -e + G=${'$'}(ls -d /config/usb_gadget/* 2>/dev/null | head -1) + [ -n "${'$'}G" ] || { echo "no USB gadget in configfs on this phone"; exit 2; } + C=${'$'}(ls -d ${'$'}G/configs/* | head -1) + mkdir -p ${'$'}G/functions/acm.gs0 2>/dev/null || { echo "this phone's kernel has no USB serial (ACM) function"; exit 3; } + [ -e ${'$'}C/f_dmodem_acm ] || ln -s ${'$'}G/functions/acm.gs0 ${'$'}C/f_dmodem_acm + U=${'$'}(cat ${'$'}G/UDC); [ -n "${'$'}U" ] || U=${'$'}(ls /sys/class/udc | head -1) + echo "" > ${'$'}G/UDC; sleep 1; echo "${'$'}U" > ${'$'}G/UDC + for i in 1 2 3 4 5; do [ -e $TTY ] && break; sleep 1; done + [ -e $TTY ] || { echo "$TTY didn't appear"; exit 4; } + chmod 666 $TTY + stty -F $TTY raw -echo 2>/dev/null || true + echo ok + """.trimIndent() + + /** the function out of the configuration again, the gadget bound as before */ + val DISABLE = """ + G=${'$'}(ls -d /config/usb_gadget/* 2>/dev/null | head -1) + [ -n "${'$'}G" ] || exit 0 + C=${'$'}(ls -d ${'$'}G/configs/* | head -1) + [ -e ${'$'}C/f_dmodem_acm ] || exit 0 + rm ${'$'}C/f_dmodem_acm + U=${'$'}(cat ${'$'}G/UDC); [ -n "${'$'}U" ] || U=${'$'}(ls /sys/class/udc | head -1) + echo "" > ${'$'}G/UDC; sleep 1; echo "${'$'}U" > ${'$'}G/UDC + echo ok + """.trimIndent() + + /** whether this phone can be asked for root (an su there) */ + fun rootAvailable(): Boolean = + listOf("/system/xbin/su", "/system/bin/su", "/sbin/su", "/su/bin/su", "/debug_ramdisk/su").any { File(it).exists() } + + /** a command as root: su -c, its status and output (stdout and stderr) */ + fun su(cmd: String): Pair = try { + val p = ProcessBuilder("su", "-c", cmd).redirectErrorStream(true).start() + val out = p.inputStream.bufferedReader().readText() + if (!p.waitFor(30, TimeUnit.SECONDS)) { p.destroy(); 124 to "su timed out" } else p.exitValue() to out + } catch (e: IOException) { + 127 to "no root on this phone (su: ${e.message})" + } + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt index 1132544..c6cbcbe 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt @@ -29,6 +29,17 @@ data class BridgeSettings( val btConnectTo: String = "", /** the client going hangs up the call (DTR dropped) */ val hangUpOnClose: Boolean = true, + /** a USB serial adapter plugged into the phone */ + val usb: Boolean = false, + val usbBaud: Int = 115200, + /** its character format: data bits, parity (N E O M S), stop bits ("8N1") */ + val usbFormat: String = "8N1", + /** the adapter's DTR out is the modem's carrier (the computer's DCD, on a null modem cable) */ + val usbCarrierOnDtr: Boolean = true, + /** the computer's DTR (the adapter's DSR) dropped hangs up */ + val usbDtrHangsUp: Boolean = true, + /** the phone's own USB port as a serial port to a computer (root) */ + val usbGadget: Boolean = false, ) private val Context.bridgeStore: DataStore by preferencesDataStore("bridges") @@ -43,6 +54,12 @@ class BridgeSettingsStore(private val context: Context) { val bt = booleanPreferencesKey("bt") val btConnectTo = stringPreferencesKey("bt_connect_to") val hangUp = booleanPreferencesKey("hang_up_on_close") + val usb = booleanPreferencesKey("usb") + val usbBaud = intPreferencesKey("usb_baud") + val usbFormat = stringPreferencesKey("usb_format") + val usbCarrierOnDtr = booleanPreferencesKey("usb_carrier_on_dtr") + val usbDtrHangsUp = booleanPreferencesKey("usb_dtr_hangs_up") + val usbGadget = booleanPreferencesKey("usb_gadget") } val settings: Flow = context.bridgeStore.data.map { from(it) } @@ -58,6 +75,12 @@ class BridgeSettingsStore(private val context: Context) { bluetooth = p[K.bt] ?: d.bluetooth, btConnectTo = p[K.btConnectTo] ?: d.btConnectTo, hangUpOnClose = p[K.hangUp] ?: d.hangUpOnClose, + usb = p[K.usb] ?: d.usb, + usbBaud = p[K.usbBaud] ?: d.usbBaud, + usbFormat = p[K.usbFormat] ?: d.usbFormat, + usbCarrierOnDtr = p[K.usbCarrierOnDtr] ?: d.usbCarrierOnDtr, + usbDtrHangsUp = p[K.usbDtrHangsUp] ?: d.usbDtrHangsUp, + usbGadget = p[K.usbGadget] ?: d.usbGadget, ) } @@ -82,6 +105,12 @@ class BridgeSettingsStore(private val context: Context) { p[K.bt] = s.bluetooth p[K.btConnectTo] = s.btConnectTo.trim() p[K.hangUp] = s.hangUpOnClose + p[K.usb] = s.usb + p[K.usbBaud] = s.usbBaud + p[K.usbFormat] = s.usbFormat + p[K.usbCarrierOnDtr] = s.usbCarrierOnDtr + p[K.usbDtrHangsUp] = s.usbDtrHangsUp + p[K.usbGadget] = s.usbGadget } } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt b/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt index dd2a6d8..a13226c 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt @@ -58,6 +58,8 @@ fun BridgeSection() { val run by ModemState.run.collectAsStateWithLifecycle() val tcpState by Bridges.tcpState.collectAsStateWithLifecycle() val btState by Bridges.btState.collectAsStateWithLifecycle() + val usbState by Bridges.usbState.collectAsStateWithLifecycle() + val gadgetState by Bridges.gadgetState.collectAsStateWithLifecycle() val client by Bridges.serial.client.collectAsStateWithLifecycle() var hasBt by remember { mutableStateOf(BluetoothBridge.hasPermission(context)) } var paired by remember { mutableStateOf(BluetoothBridge.paired(context)) } @@ -146,6 +148,24 @@ fun BridgeSection() { } } + // USB + Toggle("On a USB serial adapter (OTG)", s.usb) { v -> change { it.copy(usb = v) } } + if (s.usb) { + Text(usbText(usbState), style = MaterialTheme.typography.bodySmall) + Applied("Speed (bit/s)", s.usbBaud.toString(), number = true) { v -> + v.toIntOrNull()?.takeIf { it in 50..4_000_000 }?.let { b -> change { it.copy(usbBaud = b) } } + } + Applied("Format (data bits, parity, stop bits)", s.usbFormat) { v -> + v.uppercase().takeIf { Regex("[5-8][NEOMS][12]").matches(it) }?.let { f -> change { it.copy(usbFormat = f) } } + } + Toggle("Its DTR is the modem's carrier (the computer's DCD)", s.usbCarrierOnDtr) { v -> change { it.copy(usbCarrierOnDtr = v) } } + Toggle("The computer dropping DTR hangs up", s.usbDtrHangsUp) { v -> change { it.copy(usbDtrHangsUp = v) } } + } + if (s.usbGadget || com.neodesktop.dmodem.bridge.UsbGadget.rootAvailable()) { + Toggle("This phone's USB port as a serial port to a computer (root)", s.usbGadget) { v -> change { it.copy(usbGadget = v) } } + if (s.usbGadget) Text(gadgetText(gadgetState), style = MaterialTheme.typography.bodySmall) + } + Toggle("Hang up when the client disconnects (drops DTR)", s.hangUpOnClose) { v -> change { it.copy(hangUpOnClose = v) } } } } @@ -157,6 +177,21 @@ private fun tcpText(st: TcpBridge.State, s: BridgeSettings): String = when (st) is TcpBridge.State.Failed -> "Can't listen: ${st.why}" } +private fun usbText(st: com.neodesktop.dmodem.bridge.UsbBridge.State): String = when (st) { + com.neodesktop.dmodem.bridge.UsbBridge.State.Stopped -> "Starts with the modem" + com.neodesktop.dmodem.bridge.UsbBridge.State.Waiting -> "Waiting for an adapter to be plugged in" + is com.neodesktop.dmodem.bridge.UsbBridge.State.NeedsPermission -> "Allow D-Modem to use ${st.device} (Android asks)" + is com.neodesktop.dmodem.bridge.UsbBridge.State.Connected -> "On ${st.device}" + is com.neodesktop.dmodem.bridge.UsbBridge.State.Failed -> st.why +} + +private fun gadgetText(st: com.neodesktop.dmodem.bridge.UsbGadget.State): String = when (st) { + com.neodesktop.dmodem.bridge.UsbGadget.State.Stopped -> "Starts with the modem" + com.neodesktop.dmodem.bridge.UsbGadget.State.Ready -> "Ready: the computer sees a modem on its USB (COM port, /dev/ttyACM0)" + com.neodesktop.dmodem.bridge.UsbGadget.State.Connected -> "The computer is using the modem" + is com.neodesktop.dmodem.bridge.UsbGadget.State.Failed -> st.why +} + private fun btText(st: BluetoothBridge.State): String = when (st) { BluetoothBridge.State.Stopped -> "Starts with the modem" is BluetoothBridge.State.Listening -> "Waiting for a device to connect to \"${st.name}\"" diff --git a/app/src/main/res/xml/usb_serial_adapters.xml b/app/src/main/res/xml/usb_serial_adapters.xml new file mode 100644 index 0000000..3d165a2 --- /dev/null +++ b/app/src/main/res/xml/usb_serial_adapters.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt b/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt new file mode 100644 index 0000000..34438e8 --- /dev/null +++ b/app/src/test/java/com/neodesktop/dmodem/bridge/UsbBridgeTest.kt @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.bridge + +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbDeviceConnection +import android.hardware.usb.UsbEndpoint +import com.hoho.android.usbserial.driver.UsbSerialDriver +import com.hoho.android.usbserial.driver.UsbSerialPort +import com.neodesktop.dmodem.terminal.TerminalLink +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.IOException +import java.util.EnumSet +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * The modem on a USB serial adapter (a port of its driver's, faked: what + * the computer sends, its DTR on the adapter's DSR) and on the phone's + * own USB port as a gadget (a pty for /dev/ttyGS0, root faked). + */ +class UsbBridgeTest { + + private class FakeModem : TerminalLink { + override val state: StateFlow = MutableStateFlow(TerminalLink.State.Open) + val listeners = CopyOnWriteArrayList() + val got = ByteArrayOutputStream() + override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } + override fun write(data: ByteArray, offset: Int, length: Int): Boolean { + synchronized(got) { got.write(data, offset, length) } + if (String(data, offset, length).endsWith("\r")) { + val ok = "\r\nOK\r\n".toByteArray() + listeners.forEach { it.onData(ok, ok.size) } + } + return true + } + fun sent() = synchronized(got) { String(got.toByteArray()) } + } + + /** an adapter's port: what the computer sends (to read), what it got, its lines */ + private class FakePort : UsbSerialPort { + val fromComputer = LinkedBlockingQueue() + val toComputer = ByteArrayOutputStream() + @Volatile var dtr = false + @Volatile var rts = false + @Volatile var dsr = true + @Volatile var closed = false + override fun read(dest: ByteArray, timeout: Int): Int { + if (closed) throw IOException("closed") + val b = fromComputer.poll(timeout.toLong(), TimeUnit.MILLISECONDS) ?: return 0 + System.arraycopy(b, 0, dest, 0, b.size) + return b.size + } + override fun read(dest: ByteArray, length: Int, timeout: Int): Int = read(dest, timeout) + override fun write(src: ByteArray, timeout: Int) { synchronized(toComputer) { toComputer.write(src) } } + override fun write(src: ByteArray, length: Int, timeout: Int) { synchronized(toComputer) { toComputer.write(src, 0, length) } } + override fun setDTR(value: Boolean) { dtr = value } + override fun setRTS(value: Boolean) { rts = value } + override fun getDSR() = dsr + override fun getDTR() = dtr + override fun getRTS() = rts + override fun getCD() = dsr + override fun getCTS() = true + override fun getRI() = false + override fun close() { closed = true } + override fun isOpen() = !closed + override fun open(connection: UsbDeviceConnection?) {} + override fun setParameters(baudRate: Int, dataBits: Int, stopBits: Int, parity: Int) {} + override fun getDriver(): UsbSerialDriver? = null + override fun getDevice(): UsbDevice? = null + override fun getPortNumber() = 0 + override fun getWriteEndpoint(): UsbEndpoint? = null + override fun getReadEndpoint(): UsbEndpoint? = null + override fun getSerial(): String? = null + override fun getControlLines(): EnumSet = EnumSet.noneOf(UsbSerialPort.ControlLine::class.java) + override fun getSupportedControlLines(): EnumSet = EnumSet.allOf(UsbSerialPort.ControlLine::class.java) + override fun setFlowControl(flowControl: UsbSerialPort.FlowControl?) {} + override fun getFlowControl() = UsbSerialPort.FlowControl.NONE + override fun getSupportedFlowControl(): EnumSet = EnumSet.of(UsbSerialPort.FlowControl.NONE) + override fun getXON() = true + override fun purgeHwBuffers(purgeWriteBuffers: Boolean, purgeReadBuffers: Boolean) {} + override fun setBreak(value: Boolean) {} + fun said() = synchronized(toComputer) { String(toComputer.toByteArray()) } + } + + private fun waitUntil(what: String, ok: () -> Boolean) { + val end = System.currentTimeMillis() + 5000 + while (!ok() && System.currentTimeMillis() < end) Thread.sleep(20) + assertTrue(what, ok()) + } + + @Test + fun anAdapterCarriesTheModemAndItsLines() { + val modem = FakeModem() + val signals = MutableStateFlow(LineSignals(ready = true)) + val hangUps = AtomicInteger() + val bridge = SerialBridge(modem, signals, { hangUps.incrementAndGet() }, hangUpOnClose = false) + val port = FakePort() + val link = UsbPortLink(port, bridge, signals, "FTDI FT232R") + val t = Thread { link.serve() }.apply { start() } + waitUntil("claimed") { bridge.client.value?.via == "usb" } + assertEquals("FTDI FT232R", bridge.client.value?.name) + // the computer's command in, the modem's answer out + port.fromComputer.add("ATDT5551212\r".toByteArray()) + waitUntil("OK to the computer") { port.said().contains("OK") } + assertEquals("ATDT5551212\r", modem.sent()) + // RTS on; DTR (the computer's DCD) off until a carrier, then on + assertTrue(port.rts) + assertTrue(!port.dtr) + signals.value = LineSignals(ready = true, offhook = true, carrier = true) + waitUntil("DCD on") { port.dtr } + // the computer drops its DTR: hung up + port.dsr = false + waitUntil("hung up") { hangUps.get() == 1 } + // unplugged: the port closed, the bridge free + link.close() + t.join(5000) + assertEquals(null, bridge.client.value) + } + + @Test + fun thePhonesUsbPortAsAGadget() { + assumeTrue(File("/usr/bin/python3").canExecute()) + // a pty pair: its slave as /dev/ttyGS0, its master (the computer's side) through python + val py = ProcessBuilder( + "python3", "-u", "-c", + """ +import os, pty, tty, sys, threading +m, s = pty.openpty(); tty.setraw(s); tty.setraw(m) +print(os.ttyname(s), flush=True) +def out(): + while True: + d = os.read(m, 4096) + sys.stdout.write(d.decode('latin-1').replace('\r', '').replace('\n', '') + '\n'); sys.stdout.flush() +threading.Thread(target=out, daemon=True).start() +for line in sys.stdin: + os.write(m, line.rstrip('\n').replace('', '\r').encode()) + """.trimIndent(), + ).start() + try { + val r = py.inputStream.bufferedReader() + val tty = r.readLine() + val modem = FakeModem() + val signals = MutableStateFlow(LineSignals(ready = true)) + val bridge = SerialBridge(modem, signals, {}, hangUpOnClose = false) + val commands = CopyOnWriteArrayList() + val g = UsbGadget(bridge, root = { cmd -> commands.add(cmd); 0 to "ok" }, tty = tty) + assertTrue(g.start()) + assertTrue(commands.single().contains("functions/acm.gs0")) + waitUntil("claimed") { bridge.client.value?.via == "usb" } + assertEquals(UsbGadget.State.Connected, g.state.value) + // the computer types on its COM port + py.outputStream.write("ATI\n".toByteArray()) + py.outputStream.flush() + val seen = StringBuilder() + val end = System.currentTimeMillis() + 5000 + while (!seen.contains("OK") && System.currentTimeMillis() < end) seen.append(r.readLine()) + assertTrue(seen.toString(), seen.contains("OK")) + assertEquals("ATI\r", modem.sent()) + g.stop() + assertTrue(commands.last().contains("rm ")) + } finally { + py.destroy() + } + // the root scripts at least parse + for (script in listOf(UsbGadget.ENABLE, UsbGadget.DISABLE)) { + val p = ProcessBuilder("sh", "-n", "-c", script).redirectErrorStream(true).start() + val out = p.inputStream.readBytes().decodeToString() + assertEquals(out, 0, p.waitFor()) + } + } + + @Test + fun formats() { + assertEquals(SerialFormat(9600, 7, 'E', 1), Bridges.format(9600, "7e1")) + assertEquals(SerialFormat(115200), Bridges.format(115200, "bad")) + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7e1962f..55b7c0d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,4 +1,5 @@ [versions] +usbSerial = "3.9.0" agp = "9.4.1" kotlin = "2.4.21" composeBom = "2026.09.00" @@ -17,6 +18,7 @@ androidxTestRunner = "1.7.0" androidxTestExtJunit = "1.3.0" [libraries] +usb-serial = { module = "com.github.mik3y:usb-serial-for-android", version.ref = "usbSerial" } androidx-core-ktx = { module = "androidx.core:core-ktx", version.ref = "coreKtx" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } diff --git a/settings.gradle.kts b/settings.gradle.kts index dc67cb6..a06281a 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -10,6 +10,11 @@ dependencyResolutionManagement { repositories { google() mavenCentral() + // usb-serial-for-android (USB serial adapters' drivers) is on JitPack only: JitPack for it alone + exclusiveContent { + forRepository { maven("https://jitpack.io") } + filter { includeGroup("com.github.mik3y") } + } } } rootProject.name = "dmodem-android"