Merge pull request #22 from D-Modem/claude/project-thread-kqjtul

USB serial adapters: a modem on one as the line, /dev/ttyUSB0 in Linux, Start PPP
This commit is contained in:
Neo authored and GitHub committed 2026-11-03 21:43:59 -08:00
commit b79b285c6d
24 files changed
+1163 -49

No files matched your search

+26 -1
View File
@@ -107,6 +107,21 @@ tried on a real one). The phone runs the modem; plugged into it
Line, "A phone line, through a USB modem"; Android asks once whether
D-Modem may use it, and offers the app when one is plugged in.
## A real phone line: a modem on a USB serial adapter
An external modem of its own (a US Robotics, a Zoom, any Hayes modem) on a
USB serial adapter plugged into the phone (a Prolific PL2303, PL2303GS
among them, FTDI, CP210x, CH34x, CDC-ACM, Exar: the adapters the serial
bridges know) can take D-Modem's modem's place: Settings, Line, "A phone
line, through a modem on a USB serial adapter", its speed (8N1) and
RTS/CTS. As with a Bluetooth modem, the terminal, the internet, fax and the
Linux's `/dev/ttyDM0` talk to it with its own AT commands; the status comes
from its result codes and its DCD, where the adapter reads it. DTR is held
up while the modem runs, and stopping it drops DTR (a modem at `&D2` hangs
up). Android asks once whether D-Modem may use the adapter
(`SerialAdapters`, which also keeps the modem's line, the Linux's
`/dev/ttyUSB0` and the USB bridge off each other's adapter). `SerialModemTest`.
## A real phone line: a Bluetooth modem
A modem of its own with Bluetooth's Dial-Up Networking profile, such as
@@ -170,7 +185,10 @@ this line.
an extra keys bar (Esc, sticky Ctrl/Alt, Tab, arrows with auto-repeat,
Home/End/PgUp/PgDn, F1-F12), volume keys as font size or Ctrl/Alt,
bell as vibration or flash, full screen, snippets, session capture to a
file (shared to other apps), hang up (+++ with its guard times, ATH).
file (shared to other apps), hang up (+++ with its guard times, ATH),
and Start PPP: once a call is up (dialled and logged in by hand), the
app's PPP takes it, the phone's traffic through it as the internet's
own dial has it (`PppTakeoverTest`).
Files sent and received by ZMODEM, YMODEM, XMODEM(-1K) and Kermit, and
as Intel HEX or Motorola S-records for EPROM programmers, monitors and
boot loaders: a file sent as records (a file of them already, as it is:
@@ -199,6 +217,13 @@ this line.
closing it drops DTR, so the call hangs up as a serial cable's end
would. `ModemTtyTest`, and `LinuxSystemTest` in a real Alpine under
proot: ATI from the distro, the modem's answer back.
A USB serial adapter plugged into the phone is `/dev/ttyUSB0` there (a
pty of the app's too: Android lets no app's programs at a USB device):
the app opens the adapter when a program opens the port and closes it
(DTR down) when the program does; the speed, stop bits, RTS/CTS and B0's
hang-up follow what the program sets (`stty`, minicom, pppd); a pty keeps
no character size or parity, so it is 8 data bits, no parity.
`SerialTtyTest`.
- **Dial-in** (Settings, Dial-up internet): the phone as an ISP for whoever
calls the modem, on SIP or any other line. A call that rings is answered
(unless the fax settings answer calls already); once it connects, the
+42
View File
@@ -306,6 +306,48 @@ Java_org_dmodem_app_android_local_Pty_openPort(JNIEnv *env, jclass cls)
return m;
}
/* a baud rate's speed_t as bit/s (0 for one not listed) */
static int baud_of(speed_t s)
{
static const struct { speed_t s; int bps; } t[] = {
{ B50, 50 }, { B75, 75 }, { B110, 110 }, { B134, 134 }, { B150, 150 }, { B200, 200 },
{ B300, 300 }, { B600, 600 }, { B1200, 1200 }, { B1800, 1800 }, { B2400, 2400 },
{ B4800, 4800 }, { B9600, 9600 }, { B19200, 19200 }, { B38400, 38400 },
{ B57600, 57600 }, { B115200, 115200 }, { B230400, 230400 }, { B460800, 460800 },
{ B500000, 500000 }, { B576000, 576000 }, { B921600, 921600 }, { B1000000, 1000000 },
};
for (size_t i = 0; i < sizeof t / sizeof t[0]; i++)
if (t[i].s == s)
return t[i].bps;
return 0;
}
/*
* termios(fd): what the program on the slave of master fd set its port to
* (Linux's TCGETS on a master reads its slave's): { bit/s, stop bits,
* RTS/CTS (1 or 0), DTR wanted (0 after B0, else 1) }, or null. A pty keeps
* no character size or parity (it is always CS8, no parity).
*/
JNIEXPORT jintArray JNICALL
Java_org_dmodem_app_android_local_Pty_termios(JNIEnv *env, jclass cls, jint fd)
{
(void)cls;
struct termios t;
if (tcgetattr(fd, &t) != 0)
return NULL;
speed_t sp = cfgetospeed(&t);
jint v[4] = {
baud_of(sp),
(t.c_cflag & CSTOPB) ? 2 : 1,
(t.c_cflag & CRTSCTS) ? 1 : 0,
sp == B0 ? 0 : 1,
};
jintArray a = (*env)->NewIntArray(env, 4);
if (a != NULL)
(*env)->SetIntArrayRegion(env, a, 0, 4, v);
return a;
}
/* the slave's path of master fd (/dev/pts/N), or null */
JNIEXPORT jstring JNICALL
Java_org_dmodem_app_android_local_Pty_ptsName(JNIEnv *env, jclass cls, jint fd)
@@ -33,6 +33,27 @@ object Bridges {
/** the modem as /dev/ttyDM0 in the local Linux: a client of the serial bridge too */
val tty = ModemTty(serial) { ModemState.log.add("bridge: $it") }
private var usbTty: SerialTty? = null
/**
* a USB serial adapter as /dev/ttyUSB0 in the local Linux (one no one else has, opened as a program
* opens the port), made the first time
*/
@Synchronized
fun usbTty(context: Context): SerialTty = usbTty ?: run {
val app = context.applicationContext
val log: (String) -> Unit = { ModemState.log.add("linux: $it") }
SerialTty(SerialTty.PATH, { f ->
when (val o = kotlinx.coroutines.runBlocking { SerialAdapters.open(app, "the local Linux's ${SerialTty.PATH}", f) }) {
is SerialAdapters.Opened.Line -> o.line
is SerialAdapters.Opened.Failed -> {
log("${SerialTty.PATH}: ${o.why}")
null
}
}
}, log).also { usbTty = it }
}
private val _tcp = MutableStateFlow<TcpBridge.State>(TcpBridge.State.Stopped)
val tcpState: StateFlow<TcpBridge.State> = _tcp.asStateFlow()
private val _bt = MutableStateFlow<BluetoothBridge.State>(BluetoothBridge.State.Stopped)
@@ -0,0 +1,193 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.bridge
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 androidx.core.content.ContextCompat
import com.hoho.android.usbserial.driver.UsbSerialPort
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import java.io.Closeable
import java.io.IOException
import kotlin.coroutines.resume
/**
* A serial port the app has open, as the modem's line (an external modem on it) and the local Linux's
* /dev/ttyUSB0 use it: its octets, its speed and format, its lines. A USB serial adapter's
* ([UsbSerialLine]), or the tests' own.
*/
interface SerialLine : Closeable {
/** what to call it ("Prolific PL2303GS") */
val name: String
/** what came, into [buf]: 0 when nothing did in [timeoutMs]; an IOException once it's gone */
fun read(buf: ByteArray, timeoutMs: Int): Int
/** [len] octets of [b] from [off] out; an IOException once it's gone */
fun write(b: ByteArray, off: Int = 0, len: Int = b.size)
/** its speed and character format */
fun setFormat(f: SerialFormat)
/** RTS/CTS flow control on or off: false if it can't */
fun setRtsCts(on: Boolean): Boolean
/** its DTR out */
fun setDtr(on: Boolean)
/** its RTS out */
fun setRts(on: Boolean)
/** DCD in (the modem there has a carrier), or null if it can't say */
fun carrier(): Boolean?
}
/** A USB serial adapter's port as a [SerialLine] (usb-serial-for-android's driver for it). */
class UsbSerialLine(private val port: UsbSerialPort, override val name: String, private val device: String) : SerialLine {
@Volatile private var open = true
/** what came in [timeoutMs] (0: nothing); an IOException once closed or unplugged */
override fun read(buf: ByteArray, timeoutMs: Int): Int {
if (!open) throw IOException("$name is closed")
return port.read(buf, timeoutMs)
}
/** out to the adapter (2 s at most for it to take them) */
override fun write(b: ByteArray, off: Int, len: Int) {
if (!open) throw IOException("$name is closed")
port.write(if (off == 0 && len == b.size) b else b.copyOfRange(off, off + len), 2000)
}
/** the adapter's speed and format set (a speed it can't do: an IOException) */
override fun setFormat(f: SerialFormat) = port.setParameters(f.baud, f.dataBits, f.stopCode, f.parityCode)
/** the adapter's own RTS/CTS flow control, if its chip has it */
override fun setRtsCts(on: Boolean): Boolean {
val want = if (on) UsbSerialPort.FlowControl.RTS_CTS else UsbSerialPort.FlowControl.NONE
if (want !in port.supportedFlowControl) return !on
return runCatching { port.setFlowControl(want) }.isSuccess
}
/** DTR out */
override fun setDtr(on: Boolean) = port.setDTR(on)
/** RTS out */
override fun setRts(on: Boolean) = port.setRTS(on)
/** DCD, where the chip's driver can read it */
override fun carrier(): Boolean? =
if (UsbSerialPort.ControlLine.CD in runCatching { port.supportedControlLines }.getOrDefault(emptySet<UsbSerialPort.ControlLine>())) {
runCatching { port.cd }.getOrNull()
} else null
/** closed (its DTR drops), and the adapter free for others again */
override fun close() {
if (!open) return
open = false
runCatching { port.close() }
SerialAdapters.release(device)
}
}
/**
* Who has each USB serial adapter plugged in (the modem's line, the local Linux's /dev/ttyUSB0, the
* USB bridge), so that two of them never open the same one; and an adapter opened for one of them.
*/
object SerialAdapters {
private val holders = HashMap<String, String>()
/** adapter [device] (its device name) to [who], unless another has it */
@Synchronized
fun take(device: String, who: String): Boolean {
val h = holders[device]
if (h != null && h != who) return false
holders[device] = who
return true
}
/** adapter [device] free again */
@Synchronized
fun release(device: String) {
holders.remove(device)
}
/** who has adapter [device], or null */
@Synchronized
fun holder(device: String): String? = holders[device]
/** an adapter opened, or why none was */
sealed interface Opened {
class Line(val line: UsbSerialLine) : Opened
class Failed(val why: String) : Opened
}
private const val ACTION_PERMISSION = "org.dmodem.app.android.USB_SERIAL_PERMISSION"
/** [d]'s maker and product, else its USB IDs */
fun label(d: UsbDevice): String =
(listOfNotNull(d.manufacturerName, d.productName).joinToString(" ").ifBlank { null })
?: "USB %04x:%04x".format(d.vendorId, d.productId)
/** the adapters plugged in that no one has: their names */
fun free(context: Context): List<String> {
val m = context.getSystemService(UsbManager::class.java) ?: return emptyList()
return UsbSerialAdapters.prober.findAllDrivers(m).map { it.device }.filter { holder(it.deviceName) == null }.map { label(it) }
}
/**
* The first USB serial adapter plugged in that no one else has, opened for [who] at [format]:
* Android asked first if the app may use it (the user has [askMs] to say), unless it has said so.
*/
suspend fun open(context: Context, who: String, format: SerialFormat, askMs: Long = 60_000): Opened {
val m = context.getSystemService(UsbManager::class.java) ?: return Opened.Failed("this phone has no USB host")
val drivers = UsbSerialAdapters.prober.findAllDrivers(m)
if (drivers.isEmpty()) return Opened.Failed("no USB serial adapter plugged in")
val driver = drivers.firstOrNull { holder(it.device.deviceName).let { h -> h == null || h == who } }
?: return Opened.Failed("the USB serial adapter is in use (${drivers.mapNotNull { holder(it.device.deviceName) }.distinct().joinToString()})")
val dev = driver.device
val label = label(dev)
if (!m.hasPermission(dev)) {
val allowed = withTimeoutOrNull(askMs) { ask(context, m, dev) } ?: false
if (!allowed) return Opened.Failed("$label wasn't allowed: allow D-Modem to use it, then try again")
}
if (!take(dev.deviceName, who)) return Opened.Failed("$label is in use (${holder(dev.deviceName)})")
val conn = m.openDevice(dev)
if (conn == null) {
release(dev.deviceName)
return Opened.Failed("can't open $label")
}
val port = driver.ports.first()
return try {
port.open(conn)
port.setParameters(format.baud, format.dataBits, format.stopCode, format.parityCode)
Opened.Line(UsbSerialLine(port, label, dev.deviceName))
} catch (e: IOException) {
runCatching { port.close() }
release(dev.deviceName)
Opened.Failed("$label: ${e.message}")
}
}
/** Android's question for [dev]: whether it was allowed */
private suspend fun ask(context: Context, m: UsbManager, dev: UsbDevice): Boolean =
suspendCancellableCoroutine { cont ->
val receiver = object : BroadcastReceiver() {
/** Android's answer: the question's receiver let go, [cont] resumed with it */
override fun onReceive(c: Context, i: Intent) {
runCatching { context.unregisterReceiver(this) }
if (cont.isActive) cont.resume(i.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
}
}
ContextCompat.registerReceiver(context, receiver, IntentFilter(ACTION_PERMISSION), ContextCompat.RECEIVER_NOT_EXPORTED)
cont.invokeOnCancellation { runCatching { context.unregisterReceiver(receiver) } }
val flags = if (Build.VERSION.SDK_INT >= 31) PendingIntent.FLAG_MUTABLE else 0
m.requestPermission(dev, PendingIntent.getBroadcast(context, 3, Intent(ACTION_PERMISSION).setPackage(context.packageName), flags))
}
}
@@ -0,0 +1,160 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.bridge
import org.dmodem.app.android.local.Pty
import java.io.IOException
/**
* A USB serial adapter plugged into the phone as a serial port for the local Linux: /dev/ttyUSB0 there,
* a pty here (its slave bound in by proot, as [ModemTty]'s is). Android lets no app's programs at the
* USB device itself, so the app opens it ([open]) when a program opens the port, and carries the octets
* between the two until the program closes it (the adapter closed then: its DTR drops, as a real port's
* HUPCL would). What the program sets its port to goes to the adapter as it changes: the speed, the stop
* bits, RTS/CTS, and B0's hang-up (DTR down). A pty keeps no character size or parity: the adapter is
* 8 data bits, no parity. While no program has the port, the adapter is free for the app's own uses.
*/
class SerialTty(
/** where it is in the local Linux */
private val path: String,
/** an adapter opened at a format, blocking (Android may ask the user first); null if there's none (said to the log) */
private val open: (SerialFormat) -> SerialLine?,
private val log: (String) -> Unit = {},
) {
@Volatile private var master = -1
/** the pty's slave here (/dev/pts/N), made the first time, or null if it can't be */
@Synchronized
fun slave(): String? {
if (master < 0) {
val fd = try { Pty.openPort() } catch (e: IOException) { log("$path: ${e.message}"); return null } catch (_: UnsatisfiedLinkError) { return null }
master = fd
Thread({ watch(fd) }, "serial-tty").apply { isDaemon = true; start() }
}
return Pty.ptsName(master)
}
/** whether a program has the port open now */
fun inUse(): Boolean = master >= 0 && (Pty.poll(master, 0) and Pty.POLLHUP) == 0
/** each program that opens the port given the adapter until it closes it */
private fun watch(fd: Int) {
while (true) {
val ev = Pty.poll(fd, 500)
if (ev and Pty.POLLHUP != 0 && ev and Pty.POLLIN == 0) {
// (no program has it: poll says so at once, so wait between looks)
Thread.sleep(200)
continue
}
val t = Settings.of(Pty.termios(fd))
val line = try { open(t.format) } catch (e: Exception) { log("$path: ${e.message}"); null }
if (line == null) {
// (no adapter: what the program sends goes nowhere until it closes the port)
drain(fd)
continue
}
log("$path opened: ${line.name} at ${t.format}" + if (t.rtsCts) ", RTS/CTS" else "")
serve(fd, line, t)
log("$path closed: ${line.name} let go")
}
}
/** [line] carried to and from the program on the pty until it closes it (or the adapter goes) */
private fun serve(fd: Int, line: SerialLine, first: Settings) {
val gone = java.util.concurrent.atomic.AtomicBoolean(false)
try {
apply(line, null, first)
val reader = Thread({
val buf = ByteArray(4096)
try {
while (!gone.get()) {
val n = line.read(buf, 200)
if (n > 0 && !Pty.write(fd, buf, 0, n)) break
}
} catch (_: IOException) {
if (!gone.get()) log("$path: ${line.name} is gone (unplugged?)")
}
gone.set(true)
}, "serial-tty-in").apply { isDaemon = true; start() }
val buf = ByteArray(4096)
var now = first
while (!gone.get()) {
val ev = Pty.poll(fd, 200)
if (ev and Pty.POLLIN != 0) {
val n = Pty.read(fd, buf, 0, buf.size)
if (n < 0) break
if (n > 0) line.write(buf, 0, n)
} else if (ev and Pty.POLLHUP != 0) {
break
}
// (the program's stty, as it changes)
val next = Settings.of(Pty.termios(fd), now)
if (next != now) {
apply(line, now, next)
now = next
}
}
val unplugged = gone.getAndSet(true)
line.close()
reader.join(1000)
// (the adapter gone with the program still on the port: nothing more until it closes it)
if (unplugged) drain(fd)
} catch (e: IOException) {
// (a write to it failed: unplugged)
gone.set(true)
log("$path: ${line.name}: ${e.message}")
line.close()
drain(fd)
} finally {
gone.set(true)
line.close()
}
}
/** what the program set ([next]) to the adapter: what differs from [was] (all of it the first time) */
private fun apply(line: SerialLine, was: Settings?, next: Settings) {
if (was == null || was.format != next.format) {
// (a speed the adapter can't do: kept at the one before)
runCatching { line.setFormat(next.format) }.onFailure { log("$path: ${next.format.baud} bit/s: ${it.message}") }
}
if (was == null || was.rtsCts != next.rtsCts) {
if (!line.setRtsCts(next.rtsCts)) log("$path: ${line.name} has no RTS/CTS flow control of its own")
}
if (was == null || was.dtr != next.dtr) {
// (B0 is a hang-up: DTR down; a speed again, up)
runCatching { line.setDtr(next.dtr) }
runCatching { line.setRts(next.dtr) }
}
}
/** what comes read and dropped until no program has the port */
private fun drain(fd: Int) {
val buf = ByteArray(4096)
while (true) {
val ev = Pty.poll(fd, 500)
if (ev and Pty.POLLIN != 0) {
if (Pty.read(fd, buf, 0, buf.size) < 0) return
} else if (ev and Pty.POLLHUP != 0) {
return
}
}
}
/** what a program set its port to (Pty.termios) */
internal data class Settings(val format: SerialFormat, val rtsCts: Boolean, val dtr: Boolean) {
companion object {
/** from Pty.termios' answer [t] (null: 9600 8N1, as a Linux port starts), [was] what it was before */
fun of(t: IntArray?, was: Settings? = null): Settings {
if (t == null || t.size < 4) return was ?: Settings(SerialFormat(9600), rtsCts = false, dtr = true)
// (B0, or a rate the table doesn't name: the speed it had)
val baud = if (t[0] > 0) t[0] else was?.format?.baud ?: 9600
return Settings(SerialFormat(baud, 8, 'N', if (t[1] == 2) 2 else 1), rtsCts = t[2] != 0, dtr = t[3] != 0)
}
}
}
companion object {
/** where it is in the local Linux */
const val PATH = "/dev/ttyUSB0"
}
}
@@ -238,7 +238,8 @@ class UsbBridge(
private fun find() {
if (!running || link != null) return
val m = usb ?: return
val driver = UsbSerialAdapters.prober.findAllDrivers(m).firstOrNull()
// (not one the modem's line or the local Linux has: SerialAdapters)
val driver = UsbSerialAdapters.prober.findAllDrivers(m).firstOrNull { SerialAdapters.holder(it.device.deviceName).let { h -> h == null || h == WHO } }
if (driver == null) {
_state.value = State.Waiting
return
@@ -251,8 +252,13 @@ class UsbBridge(
m.requestPermission(dev, pi)
return
}
if (!SerialAdapters.take(dev.deviceName, WHO)) {
_state.value = State.Waiting
return
}
val conn = m.openDevice(dev)
if (conn == null) {
SerialAdapters.release(dev.deviceName)
_state.value = State.Failed("can't open ${label(dev)}")
return
}
@@ -262,6 +268,7 @@ class UsbBridge(
port.setParameters(format.baud, format.dataBits, format.stopCode, format.parityCode)
} catch (e: IOException) {
runCatching { port.close() }
SerialAdapters.release(dev.deviceName)
_state.value = State.Failed("${label(dev)}: ${e.message}")
return
}
@@ -285,6 +292,7 @@ class UsbBridge(
_state.value = State.Connected(label(dev))
Thread({
val served = l.serve()
SerialAdapters.release(dev.deviceName)
pico = null
boardJob?.interrupt()
_board.value = null
@@ -317,5 +325,7 @@ class UsbBridge(
companion object {
const val ACTION_PERMISSION = "org.dmodem.app.android.USB_PERMISSION"
/** the bridge, as SerialAdapters says who has an adapter */
const val WHO = "the USB bridge"
}
}
@@ -75,7 +75,10 @@ object Linux {
/** the system with [id] (installed or not), where [place] has it */
fun system(context: Context, id: String): LinuxSystem {
val p = place(context.applicationContext)
return LinuxSystem(File(p.root, id), p.programDir, p.tmpDir, p.storage, p.nameServers, p.extraEnv)
val app = context.applicationContext
return LinuxSystem(File(p.root, id), p.programDir, p.tmpDir, p.storage, p.nameServers, p.extraEnv).also { s ->
s.serialTty = { runCatching { org.dmodem.app.android.bridge.Bridges.usbTty(app).slave() }.getOrNull() }
}
}
/** the systems installed, the first installed first */
@@ -242,6 +242,9 @@ class LinuxSystem(
/** the modem's pty here (its slave's path), bound in as /dev/ttyDM0; null without one */
var modemTty: () -> String? = { runCatching { org.dmodem.app.android.bridge.Bridges.tty.slave() }.getOrNull() }
/** a USB serial adapter's pty here (its slave's path), bound in as /dev/ttyUSB0; null without one */
var serialTty: () -> String? = { null }
/** proot's command: the system's login shell, as root, in /root */
fun command(): List<String> {
val shell = loginShell()
@@ -260,6 +263,8 @@ class LinuxSystem(
storage()?.let { c.addAll(listOf("-b", "${it.path}:/sdcard")) }
// the modem as a serial port (/dev/ttyDM0: minicom, pppd, efax ...)
modemTty()?.let { c.addAll(listOf("-b", "$it:${org.dmodem.app.android.bridge.ModemTty.PATH}")) }
// a USB serial adapter plugged into the phone as a serial port (/dev/ttyUSB0)
serialTty()?.let { c.addAll(listOf("-b", "$it:${org.dmodem.app.android.bridge.SerialTty.PATH}")) }
c.addAll(listOf("-w", "/root", "/usr/bin/env", "-i"))
val env = linkedMapOf(
"HOME" to "/root",
@@ -43,6 +43,12 @@ object Pty {
/** a pty with no program on it, its slave raw (the modem's /dev/ttyDM0): the master's fd */
@JvmStatic external fun openPort(): Int
/**
* what the program on the slave of master [fd] set its port to: bit/s (0 for a rate it doesn't name),
* stop bits, RTS/CTS (1 on), DTR (0 after B0, its hang-up); null if it can't be read
*/
@JvmStatic external fun termios(fd: Int): IntArray?
/** the slave's path of master [fd] (/dev/pts/N) */
@JvmStatic external fun ptsName(fd: Int): String?
@@ -57,14 +57,30 @@ object BluetoothModem {
}
/**
* The status of a modem that says only its result codes (a Bluetooth modem's): online from its CONNECT
* (and its speed), idle again from NO CARRIER, BUSY, NO DIALTONE or NO ANSWER. Fed what the modem sends.
* The status of a modem that says only its result codes (a Bluetooth modem's, a serial adapter's): online
* from its CONNECT (and its speed), idle again from NO CARRIER, BUSY, NO DIALTONE or NO ANSWER. Fed what
* the modem sends, and its DCD where there is one.
*/
class ResultCodeStatus(private val onStatus: (NativeModem.Status) -> Unit) {
private val line = StringBuilder()
private var status = ModemState.IDLE
/** the modem's DCD (a serial adapter's modem): on is online (at the speed its CONNECT said, if it did), off idle */
@Synchronized
fun carrier(on: Boolean) {
val next = when {
!on -> ModemState.IDLE
status.link == NativeModem.Link.ONLINE -> status
else -> NativeModem.Status(NativeModem.Link.ONLINE, true, 0, 0)
}
if (next != status) {
status = next
onStatus(next)
}
}
/** what the modem sent, [length] octets of [data], read a line at a time for its result codes */
@Synchronized
fun feed(data: ByteArray, length: Int) {
for (i in 0 until length) {
val c = data[i].toInt() and 0xff
@@ -64,6 +64,8 @@ class ModemService : Service() {
private const val CALL_NOTIFICATION_ID = 3
private const val NOTIFICATION_ID = 1
private const val DATA_FILE = "dsp_data"
/** the modem's line, as SerialAdapters says who has an adapter */
private const val SERIAL_WHO = "the modem's line"
/** the speaker's sound socket, kept open for the process's life */
@Volatile private var speakerSocket: android.os.ParcelFileDescriptor? = null
@@ -93,9 +95,9 @@ class ModemService : Service() {
/** the USB modem that's the line (LINE_USB), open while the modem runs */
private var usbModem: UsbModems.Opened.Device? = null
/** the Bluetooth modem's connection (LINE_BT_MODEM), in place of D-Modem's modem while it runs */
/** a modem of its own's connection (a Bluetooth modem's socket, a serial adapter's port), in place of D-Modem's modem while it runs */
@Volatile
private var btSocket: android.bluetooth.BluetoothSocket? = null
private var external: java.io.Closeable? = null
private var btWatch: kotlinx.coroutines.Job? = null
private val btStatus = ResultCodeStatus { ModemState.setStatus(it) }
private val btResults = org.dmodem.app.android.terminal.TerminalLink.Listener { d, n -> btStatus.feed(d, n) }
@@ -241,6 +243,7 @@ class ModemService : Service() {
/** the native modem on the default network now, its DTE on the hub, the init commands sent */
private fun startNative(): Boolean {
if (settings.btModem) return startBtModem()
if (settings.serialModem) return startSerialModem()
val cm = getSystemService(ConnectivityManager::class.java)
val net = cm.activeNetwork
val lp = net?.let { cm.getLinkProperties(it) }
@@ -374,11 +377,7 @@ class ModemService : Service() {
}
}
/**
* The Bluetooth modem connected in place of D-Modem's modem: what's written to the modem goes to it,
* what it says to the terminal, the internet and fax; the status from its result codes. Its line's
* own tones: no tones of the app's. Its connection dropping: connected again once, else the modem stops.
*/
/** The Bluetooth modem connected in place of D-Modem's modem ([startExternal]). */
private fun startBtModem(): Boolean {
stopping = false
val name = settings.btModemName.ifBlank { settings.btModemAddress }
@@ -389,8 +388,39 @@ class ModemService : Service() {
ModemState.setError("the Bluetooth modem $name: ${e.message}")
return false
}
btSocket = s
ModemState.dte.attach(s.inputStream, s.outputStream)
return startExternal(s, s.inputStream, s.outputStream, "the Bluetooth modem's")
}
/**
* A modem on a USB serial adapter in place of D-Modem's modem (the first adapter no one else has,
* Android asked first if need be), as a Bluetooth modem is: its result codes and its DCD the status.
*/
private fun startSerialModem(): Boolean {
stopping = false
val f = org.dmodem.app.android.bridge.SerialFormat(settings.serialModemBaud)
val o = runBlocking { org.dmodem.app.android.bridge.SerialAdapters.open(this@ModemService, SERIAL_WHO, f) }
if (o is org.dmodem.app.android.bridge.SerialAdapters.Opened.Failed) {
ModemState.setError("the modem on a USB serial adapter: ${o.why}")
return false
}
val m = SerialModem((o as org.dmodem.app.android.bridge.SerialAdapters.Opened.Line).line)
log("the modem: a modem on ${m.name} at $f" + if (settings.serialModemRtsCts) ", RTS/CTS" else "")
m.start(settings.serialModemRtsCts, ::log) { on ->
log("the modem's DCD " + if (on) "on" else "off")
btStatus.carrier(on)
}
return startExternal(m, m.input, m.output, "the serial adapter's")
}
/**
* A modem of its own connected ([conn], its streams [input] and [output]): what's written to the modem
* goes to it, what it says to the terminal, the internet and fax; the status from its result codes.
* Its line's own tones: no tones of the app's. Its connection dropping ([what] connection): connected
* again once, else the modem stops.
*/
private fun startExternal(conn: java.io.Closeable, input: java.io.InputStream, output: java.io.OutputStream, what: String): Boolean {
external = conn
ModemState.dte.attach(input, output)
ModemState.setStatus(ModemState.IDLE)
ModemState.speaker.enabled = false
ModemState.tones.enabled = false
@@ -406,7 +436,7 @@ class ModemService : Service() {
btWatch = scope.launch {
// (the reader's end: the connection gone, not by our stop)
ModemState.dte.state.first { it is org.dmodem.app.android.terminal.TerminalLink.State.Closed && !stopping }
log("the Bluetooth modem's connection dropped: connecting again")
log("$what connection dropped: connecting again")
restart()
}
return true
@@ -426,9 +456,9 @@ class ModemService : Service() {
callNotification(null)
ModemState.speaker.setLevel(0)
org.dmodem.app.android.peer.Peers.stop()
// (a Bluetooth modem's connection, or D-Modem's modem)
btSocket?.let { s -> runCatching { s.close() } } ?: NativeModem.stop()
btSocket = null
// (a modem of its own's connection, or D-Modem's modem)
external?.let { s -> runCatching { s.close() } } ?: NativeModem.stop()
external = null
// (the device let go once the modem has)
usbModem?.connection?.close()
usbModem = null
@@ -607,6 +637,7 @@ class ModemService : Service() {
ModemSettings.LINE_NONE -> " (no line)"
ModemSettings.LINE_USB -> " (line: the ${usbModem?.kind?.label ?: "USB modem"})"
ModemSettings.LINE_BT_MODEM -> " (the Bluetooth modem ${settings.btModemName.ifBlank { settings.btModemAddress }})"
ModemSettings.LINE_SERIAL_MODEM -> " (the modem on the USB serial adapter)"
else -> ""
}
}
@@ -633,7 +664,7 @@ class ModemService : Service() {
private fun callerOfLine(): String = when (settings.line) {
ModemSettings.LINE_WIFI, ModemSettings.LINE_BLUETOOTH -> "The other phone"
ModemSettings.LINE_CELL -> "A mobile call"
ModemSettings.LINE_USB, ModemSettings.LINE_BT_MODEM -> "A call on the phone line"
ModemSettings.LINE_USB, ModemSettings.LINE_BT_MODEM, ModemSettings.LINE_SERIAL_MODEM -> "A call on the phone line"
else -> "A SIP call"
}
@@ -0,0 +1,99 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.modem
import org.dmodem.app.android.bridge.SerialLine
import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
/**
* A modem of its own on a USB serial adapter (the line LINE_SERIAL_MODEM): a US Robotics Courier, a
* Zoom, any Hayes modem on a cable to the adapter (a Prolific PL2303's, an FTDI's, ...). It takes the app's
* AT commands and data in place of D-Modem's own modem, as a Bluetooth modem does: the terminal, the
* internet, fax and the local Linux's /dev/ttyDM0 talk to it. Its DTR and RTS are held up while it's
* open (closing it drops DTR: a modem set to &D2 hangs up), and its DCD, where the adapter reads it,
* says whether it's online.
*/
class SerialModem(private val line: SerialLine) : Closeable {
@Volatile private var open = true
private var watch: Thread? = null
val name: String get() = line.name
/** its octets: -1 once closed or the adapter's gone */
val input: InputStream = object : InputStream() {
private val buf = ByteArray(4096)
private var have = 0
private var at = 0
/** one octet, or -1 at the end */
override fun read(): Int {
val one = ByteArray(1)
return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 0xff
}
/** what the modem sent into [b], waiting for some; -1 once closed or gone */
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: polled again, so a close is seen)
have = try { line.read(buf, 200) } catch (_: IOException) { return -1 }
at = 0
}
return -1
}
}
/** octets to it: an IOException once closed or gone */
val output: OutputStream = object : OutputStream() {
/** one octet to the modem */
override fun write(b: Int) = write(byteArrayOf(b.toByte()), 0, 1)
/** [len] octets of [b] to the modem */
override fun write(b: ByteArray, off: Int, len: Int) {
if (!open) throw IOException("${line.name} is closed")
line.write(b, off, len)
}
}
/**
* DTR and RTS up, RTS/CTS flow control as [rtsCts] has it (said to [log] when the adapter can't),
* and its DCD watched: each change to [onCarrier]
*/
fun start(rtsCts: Boolean, log: (String) -> Unit = {}, onCarrier: (Boolean) -> Unit = {}) {
runCatching { line.setDtr(true) }
runCatching { line.setRts(true) }
if (rtsCts && !line.setRtsCts(true)) log("${line.name} has no RTS/CTS flow control of its own: none")
watch = Thread({
var last: Boolean? = null
try {
while (open) {
val cd = runCatching { line.carrier() }.getOrNull()
if (cd != null && cd != last) {
// (the first look only says so if it's on: a modem idle isn't news)
if (last != null || cd) onCarrier(cd)
last = cd
}
Thread.sleep(250)
}
} catch (_: InterruptedException) {
}
}, "serial-modem-dcd").apply { isDaemon = true; start() }
}
/** closed: DTR down (the modem hangs up), the adapter let go */
override fun close() {
if (!open) return
open = false
watch?.interrupt()
runCatching { line.setDtr(false) }
line.close()
}
}
@@ -71,12 +71,13 @@ object Internet {
_state.value = _state.value?.let(f)
}
/** why it can't start now, or null */
fun busy(): String? = when {
/** why it can't start now, or null; [dial]: it dials (the modem on hook), else it takes the call there is (online) */
fun busy(dial: Boolean = true): String? = when {
ModemState.run.value != ModemState.Run.RUNNING -> "the modem is off"
running -> "it's connected already"
Fax.running -> "a fax call is going on"
ModemState.status.value.offhook -> "the modem is in a call"
dial && ModemState.status.value.offhook -> "the modem is in a call"
!dial && ModemState.status.value.link != NativeModem.Link.ONLINE -> "no call to start PPP on: dial and log in first"
Bridges.serial.client.value != null -> "the modem is in use by ${Bridges.serial.client.value?.name}"
else -> null
}
@@ -85,11 +86,13 @@ object Internet {
* the ISP dialled and PPP brought up; [openTunnel] gets the link's
* address and DNS servers (its packets to [sendIp]): null when it
* can't (the link comes down again). Null when it has started, else
* why it can't.
* why it can't. Not [dial]: PPP started on the call the modem has now
* (dialled and logged in by hand in the terminal), the ISP's user and
* password for PPP's own login if it asks; PPP's end hangs it up.
*/
fun connect(isp: IspSettings, openTunnel: (Ppp.IpConfig) -> Tunnel?): String? {
busy()?.let { return it }
if (!isp.complete) return "no number for the ISP"
fun connect(isp: IspSettings, dial: Boolean = true, openTunnel: (Ppp.IpConfig) -> Tunnel?): String? {
busy(dial)?.let { return it }
if (dial && !isp.complete) return "no number for the ISP"
val hub = ModemState.dte
lateinit var listener: TerminalLink.Listener
val io = TransferIo { b -> if (!hub.writeAs(listener, b)) throw IOException("the modem has gone") }
@@ -98,26 +101,15 @@ object Internet {
if (!hub.claim(listener)) return "the modem is in use"
line = io
stopping = false
_state.value = State("Dialling ${isp.number}")
_state.value = if (dial) State("Dialling ${isp.number}") else State("Starting PPP", connect = "CONNECT")
Thread({
var why: String? = null
var online = false
var online = !dial
try {
val c = Class1(io) { ModemState.log.add("internet: $it") }
// (data mode; X3: a SIP line has no dial tone)
if (c.command("E0V1X3+FCLASS=0") != "OK") throw IOException("the modem didn't answer")
for (cmd in isp.initCommands.split(Regex("[\\r\\n;]+")).map { it.trim() }.filter { it.isNotEmpty() }) {
c.command(cmd.removePrefix("AT").removePrefix("at"))
}
val r = c.command("D${isp.number}", 90_000)
if (r == null || !r.startsWith("CONNECT")) throw IOException(dialResult(r))
online = true
set { it.copy(phase = "Logging in", connect = r) }
// the ISP's login script first, if it has one (a text login before PPP)
if (isp.script.isNotBlank()) {
set { it.copy(phase = "Running the login script") }
ChatScript(isp.script, isp.user, isp.password).run(io) { ModemState.log.add("script: $it") }
set { it.copy(phase = "Logging in") }
if (dial) {
dialIsp(isp, io) { online = true }
} else {
ModemState.log.add("internet: PPP on the call the modem has")
}
val done = java.util.concurrent.CountDownLatch(1)
val p = Ppp(
@@ -183,6 +175,29 @@ object Internet {
return null
}
/**
* the ISP dialled on [io] (the modem's, claimed), [onConnect] told at its CONNECT, and its login script
* (if any) run; an IOException saying why if it doesn't connect
*/
private fun dialIsp(isp: IspSettings, io: TransferIo, onConnect: () -> Unit) {
val c = Class1(io) { ModemState.log.add("internet: $it") }
// (data mode; X3: a SIP line has no dial tone)
if (c.command("E0V1X3+FCLASS=0") != "OK") throw IOException("the modem didn't answer")
for (cmd in isp.initCommands.split(Regex("[\\r\\n;]+")).map { it.trim() }.filter { it.isNotEmpty() }) {
c.command(cmd.removePrefix("AT").removePrefix("at"))
}
val r = c.command("D${isp.number}", 90_000)
if (r == null || !r.startsWith("CONNECT")) throw IOException(dialResult(r))
onConnect()
set { it.copy(phase = "Logging in", connect = r) }
// the ISP's login script first, if it has one (a text login before PPP)
if (isp.script.isNotBlank()) {
set { it.copy(phase = "Running the login script") }
ChatScript(isp.script, isp.user, isp.password).run(io) { ModemState.log.add("script: $it") }
set { it.copy(phase = "Logging in") }
}
}
/** a packet from the phone (the VPN's) to the link */
fun sendIp(packet: ByteArray): Boolean = ppp?.sendIp(packet) ?: false
@@ -65,6 +65,9 @@ data class ModemSettings(
/** the Bluetooth modem's (LINE_BT_MODEM): the paired device's address, its name to show */
val btModemAddress: String = "",
val btModemName: String = "",
/** the modem on a USB serial adapter's (LINE_SERIAL_MODEM): the adapter's speed, and RTS/CTS flow control (8N1) */
val serialModemBaud: Int = 115200,
val serialModemRtsCts: Boolean = true,
/** each call on a USB modem's line recorded (LineRecordings), for a bug report */
val recordLine: Boolean = false,
/** a USB modem's line: the modem's sound to it louder or softer, dB (-20 to 20; D-Modem-RE's DMODEM_USB_TX_GAIN) */
@@ -82,7 +85,7 @@ data class ModemSettings(
}
/** the line is another phone (or this phone's mobile calls, or none), not SIP: the app carries its samples */
val peer: Boolean get() = line != LINE_SIP && line != LINE_USB && line != LINE_BT_MODEM
val peer: Boolean get() = line != LINE_SIP && line != LINE_USB && line != LINE_BT_MODEM && line != LINE_SERIAL_MODEM
/** the line is a SIP account's */
val sip: Boolean get() = line == LINE_SIP
@@ -93,6 +96,9 @@ data class ModemSettings(
/** a modem of its own on Bluetooth (BluetoothModem) in place of D-Modem's: it has the line */
val btModem: Boolean get() = line == LINE_BT_MODEM
/** a modem of its own on a USB serial adapter (SerialModem) in place of D-Modem's: it has the line */
val serialModem: Boolean get() = line == LINE_SERIAL_MODEM
/** no line at all: the modem on its own (AT commands, the terminal, the bridges); a dial gets NO DIALTONE */
val noLine: Boolean get() = line == LINE_NONE
@@ -120,6 +126,9 @@ data class ModemSettings(
const val LINE_NONE = "none"
const val LINE_USB = "usb"
const val LINE_BT_MODEM = "bt_modem"
const val LINE_SERIAL_MODEM = "serial_modem"
/** the speeds offered for a serial adapter's modem */
val SERIAL_SPEEDS = listOf(2400, 9600, 19200, 38400, 57600, 115200, 230400)
/** the mobile-call line's V.cvm (D-Modem-RE's +MS=VCVM) */
const val CELL_VCVM = "VCVM"
@@ -168,6 +177,8 @@ class SettingsStore(private val context: Context) {
val cellSpeed = stringPreferencesKey("cell_speed")
val btModemAddress = stringPreferencesKey("bt_modem_address")
val btModemName = stringPreferencesKey("bt_modem_name")
val serialModemBaud = intPreferencesKey("serial_modem_baud")
val serialModemRtsCts = booleanPreferencesKey("serial_modem_rtscts")
val recordLine = booleanPreferencesKey("record_line")
val usbTxGain = intPreferencesKey("usb_tx_gain")
val usbTxAuto = booleanPreferencesKey("usb_tx_auto")
@@ -200,6 +211,8 @@ class SettingsStore(private val context: Context) {
cellSpeed = (p[Keys.cellSpeed] ?: d.cellSpeed).let { if (it == "V_CVM") ModemSettings.CELL_VCVM else it },
btModemAddress = p[Keys.btModemAddress] ?: d.btModemAddress,
btModemName = p[Keys.btModemName] ?: d.btModemName,
serialModemBaud = p[Keys.serialModemBaud] ?: d.serialModemBaud,
serialModemRtsCts = p[Keys.serialModemRtsCts] ?: d.serialModemRtsCts,
recordLine = p[Keys.recordLine] ?: d.recordLine,
usbTxGain = p[Keys.usbTxGain] ?: d.usbTxGain,
usbTxAuto = p[Keys.usbTxAuto] ?: d.usbTxAuto,
@@ -235,6 +248,8 @@ class SettingsStore(private val context: Context) {
p[Keys.cellSpeed] = s.cellSpeed
p[Keys.btModemAddress] = s.btModemAddress
p[Keys.btModemName] = s.btModemName
p[Keys.serialModemBaud] = s.serialModemBaud
p[Keys.serialModemRtsCts] = s.serialModemRtsCts
p[Keys.recordLine] = s.recordLine
p[Keys.usbTxGain] = s.usbTxGain.coerceIn(-20, 20)
p[Keys.usbTxAuto] = s.usbTxAuto
@@ -310,6 +310,14 @@ private fun LineCard(s: ModemSettings, run: ModemState.Run, network: String?, on
PeerLineRows(s, run, network)
return@Column
}
if (s.serialModem) {
InfoRow("Via", "a phone line, through a modem on a USB serial adapter")
InfoRow("Port", "${s.serialModemBaud} bit/s 8N1" + if (s.serialModemRtsCts) ", RTS/CTS" else "")
if (run == ModemState.Run.RUNNING) {
Text("Its own AT commands: calls ring in the terminal (RING)", style = MaterialTheme.typography.bodySmall)
}
return@Column
}
if (s.btModem) {
InfoRow("Via", "a phone line, through a Bluetooth modem")
InfoRow("Modem", s.btModemName.ifBlank { s.btModemAddress }.ifBlank { "none chosen" })
@@ -125,7 +125,9 @@ fun LinuxSection(onOpened: () -> Unit = {}) {
if (systems.isNotEmpty()) {
Text(
"In each: /root is home, /sdcard the phone's storage, and /dev/ttyDM0 the modem as a serial port " +
"(minicom -D /dev/ttyDM0, pppd, efax: the program that opens it has the modem until it closes it).",
"(minicom -D /dev/ttyDM0, pppd, efax: the program that opens it has the modem until it closes it). " +
"A USB serial adapter plugged into the phone is /dev/ttyUSB0 (the speed and RTS/CTS as the program sets " +
"them; 8 data bits, no parity; closing it drops DTR). Android asks once whether D-Modem may use it.",
style = MaterialTheme.typography.bodySmall,
)
}
@@ -241,7 +241,8 @@ class MainActivity : ComponentActivity() {
private fun callerOfLine(): String = when (org.dmodem.app.android.modem.ModemState.line) {
org.dmodem.app.android.settings.ModemSettings.LINE_WIFI, org.dmodem.app.android.settings.ModemSettings.LINE_BLUETOOTH -> "The other phone"
org.dmodem.app.android.settings.ModemSettings.LINE_CELL -> "A mobile call"
org.dmodem.app.android.settings.ModemSettings.LINE_USB, org.dmodem.app.android.settings.ModemSettings.LINE_BT_MODEM -> "A call on the phone line"
org.dmodem.app.android.settings.ModemSettings.LINE_USB, org.dmodem.app.android.settings.ModemSettings.LINE_BT_MODEM,
org.dmodem.app.android.settings.ModemSettings.LINE_SERIAL_MODEM -> "A call on the phone line"
else -> "A SIP call"
}
@@ -28,6 +28,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
@@ -65,13 +66,14 @@ fun LineChoice(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
ModemSettings.LINE_BLUETOOTH to "Another phone with D-Modem, on Bluetooth",
ModemSettings.LINE_CELL to "This phone's mobile calls (slow; root)",
ModemSettings.LINE_USB to "A phone line, through a USB modem",
ModemSettings.LINE_SERIAL_MODEM to "A phone line, through a modem on a USB serial adapter",
ModemSettings.LINE_BT_MODEM to "A phone line, through a Bluetooth modem (Dial-Up Networking)",
ModemSettings.LINE_NONE to "No line (the modem on its own)",
)
// the line chosen: the permission asked for first where it needs one
fun choose(line: String) {
when (line) {
ModemSettings.LINE_SIP, ModemSettings.LINE_CELL, ModemSettings.LINE_NONE, ModemSettings.LINE_USB ->
ModemSettings.LINE_SIP, ModemSettings.LINE_CELL, ModemSettings.LINE_NONE, ModemSettings.LINE_USB, ModemSettings.LINE_SERIAL_MODEM ->
onChange(s.copy(line = line))
ModemSettings.LINE_WIFI -> onChange(
s.copy(line = line, peerAddress = if (s.line == line) s.peerAddress else "", peerName = ""),
@@ -124,7 +126,7 @@ fun LineChoice(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
/** the line menu's filters: the kinds of line, each its icon's button; MORE every line */
enum class LineKind(val label: String, private val lines: Set<String>) {
USB("USB", setOf(ModemSettings.LINE_USB)),
USB("USB", setOf(ModemSettings.LINE_USB, ModemSettings.LINE_SERIAL_MODEM)),
BLUETOOTH("Bluetooth", setOf(ModemSettings.LINE_BLUETOOTH, ModemSettings.LINE_BT_MODEM)),
NETWORK("Wi-Fi / Cell", setOf(ModemSettings.LINE_SIP, ModemSettings.LINE_WIFI, ModemSettings.LINE_CELL)),
MORE("More", emptySet());
@@ -378,6 +380,53 @@ fun BluetoothModemFields(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
}
}
/** A modem of its own on a USB serial adapter (a Hayes modem on a PL2303's cable, say): the port's speed, RTS/CTS */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SerialModemFields(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
val context = LocalContext.current
val free = remember { org.dmodem.app.android.bridge.SerialAdapters.free(context) }
Text(
"An external modem (a US Robotics, a Zoom, any Hayes modem) on a USB serial adapter (Prolific PL2303, FTDI, " +
"CP210x, CH34x, CDC-ACM) plugged into the phone: it dials and answers, and the terminal, the internet, fax " +
"and the Linux's /dev/ttyDM0 talk to it in place of D-Modem's own modem (its own AT commands). DTR is held " +
"up while the modem runs; stopping it drops DTR. Android asks once whether D-Modem may use the adapter.",
style = MaterialTheme.typography.bodySmall,
)
Text(
"Adapter: " + if (free.isEmpty()) "none plugged in (or in use)" else free.joinToString(", "),
style = MaterialTheme.typography.bodyMedium,
)
var open by remember { mutableStateOf(false) }
ExposedDropdownMenuBox(expanded = open, onExpandedChange = { open = it }) {
OutlinedTextField(
value = "${s.serialModemBaud} bit/s",
onValueChange = {},
readOnly = true,
singleLine = true,
label = { Text("The port's speed (8N1)") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = open) },
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryNotEditable),
)
ExposedDropdownMenu(expanded = open, onDismissRequest = { open = false }) {
for (b in ModemSettings.SERIAL_SPEEDS) {
DropdownMenuItem(
text = { Text("$b bit/s") },
onClick = {
open = false
onChange(s.copy(serialModemBaud = b))
},
contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
)
}
}
}
Row(Modifier.fillMaxWidth().clickable { onChange(s.copy(serialModemRtsCts = !s.serialModemRtsCts)) }, verticalAlignment = Alignment.CenterVertically) {
Text("RTS/CTS flow control (the modem's &K3)", Modifier.weight(1f))
Switch(checked = s.serialModemRtsCts, onCheckedChange = { onChange(s.copy(serialModemRtsCts = it)) })
}
}
/** a labelled radio button, the whole row tappable */
@Composable
private fun LineRadio(label: String, selected: Boolean, onClick: () -> Unit) {
@@ -178,6 +178,8 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {
)
} else if (s.btModem) {
BluetoothModemFields(s) { s = it }
} else if (s.serialModem) {
SerialModemFields(s) { s = it }
} else {
Text("SIP account", style = MaterialTheme.typography.titleSmall)
OutlinedTextField(
@@ -356,6 +358,7 @@ private fun lineSummary(s: ModemSettings): String = when (s.line) {
ModemSettings.LINE_NONE -> "No line: the modem on its own"
ModemSettings.LINE_USB -> "A phone line, through a USB modem"
ModemSettings.LINE_BT_MODEM -> "A Bluetooth modem" + s.btModemName.let { if (it.isBlank()) "" else ": $it" }
ModemSettings.LINE_SERIAL_MODEM -> "A modem on a USB serial adapter, ${s.serialModemBaud} bit/s"
else -> if (s.complete) "SIP: ${s.user}@${s.domain}" + (if (s.listen) ", taking calls" else "") else "SIP: no account set up yet"
}
@@ -132,6 +132,20 @@ fun TerminalScreen(
if (!session.sendFiles(proto, files)) Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
}
}
/** the app's PPP on the call the modem has now (logged in by hand), the phone's traffic through it; why not in a toast */
fun startPpp() {
val app = context.applicationContext
scope.launch {
val isp = org.dmodem.app.android.settings.IspSettingsStore(app).current()
org.dmodem.app.android.ppp.Internet.connect(isp, dial = false) { cfg -> org.dmodem.app.android.ppp.PppVpnService.open(app, cfg) }
?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
?: Toast.makeText(context, "PPP started on the call: Home shows the connection", Toast.LENGTH_SHORT).show()
}
}
// the system's VPN consent, the first time
val pppConsent = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == android.app.Activity.RESULT_OK) startPpp() else Toast.makeText(context, "The VPN wasn't allowed", Toast.LENGTH_LONG).show()
}
// the remote's rz waiting: files to pick for it
DisposableEffect(session) {
session.onSendWanted = { proto ->
@@ -215,6 +229,10 @@ fun TerminalScreen(
Terminal.close(session)
}
},
onStartPpp = if (isModem && status.link == NativeModem.Link.ONLINE) ({
val ask = android.net.VpnService.prepare(context)
if (ask != null) pppConsent.launch(ask) else startPpp()
}) else null,
onClear = { session.clear() },
onReset = { session.reset() },
onFullscreen = { onFullscreen(true) },
@@ -430,7 +448,7 @@ private fun barText(
return if (title.isNotBlank()) "$state — $title" else state
}
/** the terminal's bar: its line, the keyboard, snippets and capture buttons, and a menu of the rest (hang up, paste, new shells, files, character set, clear, reset, full screen, the AT command reference) */
/** the terminal's bar: its line, the keyboard, snippets and capture buttons, and a menu of the rest (hang up, start PPP, paste, new shells, files, character set, clear, reset, full screen, the AT command reference) */
@Composable
private fun TopBar(
text: String,
@@ -447,6 +465,8 @@ private fun TopBar(
onReceiveFiles: () -> Unit,
onCapture: () -> Unit,
onHangUp: () -> Unit,
/** PPP started on the modem's call (dialled and logged in by hand): null when the modem isn't online */
onStartPpp: (() -> Unit)?,
onClear: () -> Unit,
onReset: () -> Unit,
onFullscreen: () -> Unit,
@@ -471,6 +491,9 @@ private fun TopBar(
IconButton(onClick = { menu = true }) { Icon(Icons.Filled.MoreVert, "More") }
DropdownMenu(expanded = menu, onDismissRequest = { menu = false }) {
DropdownMenuItem(text = { Text(if (isModem) "Hang up" else "Disconnect") }, onClick = { menu = false; onHangUp() })
if (onStartPpp != null) {
DropdownMenuItem(text = { Text("Start PPP (the internet on this call)") }, onClick = { menu = false; onStartPpp() })
}
DropdownMenuItem(text = { Text("Paste") }, onClick = { menu = false; onPaste() })
DropdownMenuItem(text = { Text("New local shell") }, onClick = { menu = false; onNewShell() })
DropdownMenuItem(text = { Text("New Linux shell…") }, onClick = { menu = false; onNewLinux() })
@@ -0,0 +1,58 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.bridge
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/** A serial adapter for the tests: what's written to it kept, what it "receives" queued, its settings and lines noted. */
class FakeSerialLine(override val name: String = "a test adapter") : SerialLine {
/** octets the far end sends (the app reads them) */
val incoming = LinkedBlockingQueue<ByteArray>()
private val got = ByteArrayOutputStream()
@Volatile var format: SerialFormat? = null
private set
@Volatile var rtsCts: Boolean? = null
private set
@Volatile var dtr: Boolean? = null
private set
@Volatile var rts: Boolean? = null
private set
/** its DCD (null: it can't say) */
@Volatile var cd: Boolean? = null
@Volatile var closed = false
/** unplugged: reads and writes fail */
@Volatile var gone = false
/** what was written to it, as text */
fun sent(): String = synchronized(got) { String(got.toByteArray(), Charsets.ISO_8859_1) }
/** the next queued octets (0 after [timeoutMs] with none); an IOException once closed or gone */
override fun read(buf: ByteArray, timeoutMs: Int): Int {
if (closed || gone) throw IOException("closed")
val b = incoming.poll(timeoutMs.toLong(), TimeUnit.MILLISECONDS) ?: return 0
System.arraycopy(b, 0, buf, 0, b.size)
return b.size
}
/** kept; an IOException once closed or gone */
override fun write(b: ByteArray, off: Int, len: Int) {
if (closed || gone) throw IOException("closed")
synchronized(got) { got.write(b, off, len) }
}
/** noted */
override fun setFormat(f: SerialFormat) { format = f }
/** noted */
override fun setRtsCts(on: Boolean): Boolean { rtsCts = on; return true }
/** noted */
override fun setDtr(on: Boolean) { dtr = on }
/** noted */
override fun setRts(on: Boolean) { rts = on }
/** as set */
override fun carrier(): Boolean? = cd
/** noted */
override fun close() { closed = true }
}
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.bridge
import org.dmodem.app.android.local.LocalShellTest
import org.dmodem.app.android.local.Pty
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import java.io.RandomAccessFile
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
/**
* A USB serial adapter as /dev/ttyUSB0 ([SerialTty]): a program opening the pty's slave gets the
* adapter opened at the port's settings, its octets to the adapter and back; its stty (speed, RTS/CTS,
* B0's hang-up) to the adapter as it changes; closing the port closes the adapter; no adapter, nothing.
*/
class SerialTtyTest {
private val log = CopyOnWriteArrayList<String>()
@Volatile private var line: FakeSerialLine? = FakeSerialLine()
private val opened = CopyOnWriteArrayList<SerialFormat>()
private val tty = SerialTty("/dev/ttyUSB0", { f -> opened.add(f); line }, { log.add(it) })
/** the pty library built for the host, loaded */
@Before
fun setUp() = Pty.load(LocalShellTest.hostPty())
/** [cond] waited for ([secs] at most), failing with [what] (and the log) if it never holds */
private fun until(what: String, secs: Int = 5, cond: () -> Boolean) {
val end = System.currentTimeMillis() + secs * 1000L
while (!cond()) {
if (System.currentTimeMillis() > end) throw AssertionError("$what\n${log.joinToString("\n")}")
Thread.sleep(20)
}
}
/** stty run on the port with [args] ([check]: it must say it did all of it) */
private fun stty(slave: String, vararg args: String, check: Boolean = true) {
val p = ProcessBuilder(listOf("stty", "-F", slave) + args).redirectErrorStream(true).start()
val out = p.inputStream.readBytes().decodeToString()
assertTrue(p.waitFor(10, TimeUnit.SECONDS))
if (check) assertEquals(out, 0, p.exitValue())
}
/** text from the port until [want] */
private fun RandomAccessFile.expect(want: String) {
val sb = StringBuilder()
val buf = ByteArray(256)
while (!sb.contains(want)) {
val n = read(buf)
if (n < 0) break
sb.append(String(buf, 0, n, Charsets.ISO_8859_1))
}
assertTrue("\"$want\" in \"$sb\"", sb.contains(want))
}
/** opened: the adapter at the port's speed, DTR up; octets both ways; stty's changes to it; closed, the adapter let go */
@Test
fun aProgramHasTheAdapter() {
val l = line!!
val slave = tty.slave()
assertNotNull(slave)
stty(slave!!, "9600")
val port = RandomAccessFile(slave, "rw")
until("the adapter opened") { l.format != null }
assertEquals(9600, opened.first().baud)
assertEquals(SerialFormat(9600), l.format)
assertEquals(true, l.dtr)
assertEquals(false, l.rtsCts)
assertTrue(tty.inUse())
port.write("ATI\r".toByteArray())
until("the program's octets at the adapter") { l.sent().contains("ATI\r") }
l.incoming.add("\r\nU.S. Robotics 56K\r\nOK\r\n".toByteArray())
port.expect("OK")
// (minicom's, pppd's settings: a speed, RTS/CTS, 2 stop bits)
stty(slave, "115200", "crtscts", "cstopb")
until("the new speed at the adapter") { l.format == SerialFormat(115200, 8, 'N', 2) && l.rtsCts == true }
// (B0: hang up, DTR down; a speed again, up)
// (a pty takes B0, but stty reading it back complains)
stty(slave, "0", check = false)
until("DTR down") { l.dtr == false }
assertEquals(115200, l.format?.baud)
stty(slave, "57600")
until("DTR up") { l.dtr == true && l.format?.baud == 57600 }
port.close()
until("the adapter closed") { l.closed }
}
/** no adapter: the port opens, what's written goes nowhere; one plugged in later is the next program's */
@Test
fun noAdapter() {
line = null
val slave = tty.slave()!!
RandomAccessFile(slave, "rw").use { p ->
until("the adapter looked for") { opened.isNotEmpty() }
p.write("hello\r".toByteArray())
}
// (the port seen closed before it's opened again)
until("the port closed") { !tty.inUse() }
Thread.sleep(1000)
val l = FakeSerialLine()
line = l
RandomAccessFile(slave, "rw").use { p ->
until("the adapter opened") { l.format != null }
p.write("again\r".toByteArray())
until("the octets at it") { l.sent() == "again\r" }
}
until("the adapter closed") { l.closed }
}
/** the adapter unplugged under the program: let go, the program's port quiet until it closes it */
@Test
fun unplugged() {
val l = line!!
val slave = tty.slave()!!
RandomAccessFile(slave, "rw").use { p ->
until("the adapter opened") { l.format != null }
l.gone = true
until("the adapter let go") { l.closed }
p.write("into nothing\r".toByteArray())
}
assertTrue(log.joinToString("\n"), log.any { it.contains("gone") })
}
}
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.modem
import org.dmodem.app.android.NativeModem
import org.dmodem.app.android.bridge.FakeSerialLine
import org.dmodem.app.android.settings.ModemSettings
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/** a modem on a USB serial adapter ([SerialModem]): its lines held up, its octets, its DCD; its status from both */
class SerialModemTest {
/** started: DTR, RTS and RTS/CTS on; octets each way; DCD's changes told; closed: DTR down, the adapter let go */
@Test
fun linesOctetsAndCarrier() {
val line = FakeSerialLine()
val m = SerialModem(line)
val carrier = LinkedBlockingQueue<Boolean>()
line.cd = false
m.start(rtsCts = true) { carrier.add(it) }
assertEquals(true, line.dtr)
assertEquals(true, line.rts)
assertEquals(true, line.rtsCts)
m.output.write("ATDT5551234\r".toByteArray())
assertEquals("ATDT5551234\r", line.sent())
line.incoming.add("CONNECT 28800\r\n".toByteArray())
val buf = ByteArray(64)
val n = m.input.read(buf)
assertEquals("CONNECT 28800\r\n", String(buf, 0, n))
// (idle at the start isn't news; on, then off, is)
line.cd = true
assertEquals(true, carrier.poll(2, TimeUnit.SECONDS))
line.cd = false
assertEquals(false, carrier.poll(2, TimeUnit.SECONDS))
m.close()
assertEquals(false, line.dtr)
assertTrue(line.closed)
assertEquals(-1, m.input.read(buf))
}
/** the adapter unplugged: its input ends (the service sees the modem gone) */
@Test
fun unplugged() {
val line = FakeSerialLine()
val m = SerialModem(line)
m.start(rtsCts = false)
line.gone = true
assertEquals(-1, m.input.read(ByteArray(8)))
m.close()
}
/** DCD and result codes together: online from either, idle from either, a CONNECT after DCD's drop online again */
@Test
fun statusFromCarrierAndResults() {
val seen = mutableListOf<NativeModem.Status>()
val r = ResultCodeStatus { seen += it }
/** [s] fed to the status as the modem's output */
fun say(s: String) = s.toByteArray().let { r.feed(it, it.size) }
r.carrier(true)
assertEquals(NativeModem.Status(NativeModem.Link.ONLINE, true, 0, 0), seen.last())
say("\r\nCONNECT 33600/ARQ\r\n")
assertEquals(NativeModem.Status(NativeModem.Link.ONLINE, true, 33600, 33600), seen.last())
// (DCD on again while online: its speed kept)
r.carrier(true)
assertEquals(2, seen.size)
// (DCD gone with no NO CARRIER: ATQ1, say)
r.carrier(false)
assertEquals(ModemState.IDLE, seen.last())
say("\r\nCONNECT 33600/ARQ\r\n")
assertEquals(NativeModem.Status(NativeModem.Link.ONLINE, true, 33600, 33600), seen.last())
}
/** the line: no SIP account needed, no peer line, a modem of its own */
@Test
fun theLine() {
val s = ModemSettings(line = ModemSettings.LINE_SERIAL_MODEM)
assertTrue(s.serialModem)
assertFalse(s.peer)
assertFalse(s.sip)
assertTrue(s.complete)
assertEquals(115200, s.serialModemBaud)
}
}
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.ppp
import org.dmodem.app.android.NativeModem
import org.dmodem.app.android.modem.ModemState
import org.dmodem.app.android.settings.IspSettings
import org.dmodem.app.ppp.Ip
import org.dmodem.app.ppp.Ppp
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.TimeUnit
/**
* PPP started on a call the modem has already (dialled and logged in by hand in the terminal, then the
* terminal's "Start PPP"): no AT commands, PPP straight away on the DTE, an address from the ISP, a
* packet echoed; disconnected, the call hung up (+++, ATH) and the DTE free.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class PppTakeoverTest {
/** the app's end of the modem, and the far end's (the ISP on the call) */
private val fromApp = PipedInputStream(1 shl 16)
private val toApp = PipedOutputStream()
/** the DTE on pipes, the modem running and online */
@Before
fun setUp() {
val appIn = PipedInputStream(toApp, 1 shl 16)
val appOut = PipedOutputStream(fromApp)
ModemState.dte.attach(appIn, appOut)
ModemState.setRun(ModemState.Run.RUNNING)
ModemState.setStatus(NativeModem.Status(NativeModem.Link.ONLINE, true, 33600, 33600))
}
/** disconnected, the DTE detached, the modem stopped */
@After
fun tearDown() {
Internet.disconnect()
ModemState.dte.detach()
ModemState.setStatus(ModemState.IDLE)
ModemState.setRun(ModemState.Run.STOPPED)
}
/** not online: it says to dial first */
@Test
fun needsACall() {
ModemState.setStatus(ModemState.IDLE)
assertEquals("no call to start PPP on: dial and log in first", Internet.connect(IspSettings(), dial = false) { null })
}
/** PPP on the call: no dial, the link up, a packet each way, the hang-up at the end */
@Test
fun pppOnTheCallThereIs() {
val sent = StringBuilder()
val isp = TestIsp(Ppp.PROTO_PAP, "alice", "s3cret", echo = true) { f -> synchronized(toApp) { toApp.write(f); toApp.flush() } }
Thread {
val buf = ByteArray(4096)
while (true) {
val n = try { fromApp.read(buf) } catch (_: Exception) { -1 }
if (n < 0) break
synchronized(sent) { sent.append(String(buf, 0, n, Charsets.ISO_8859_1)) }
isp.input(buf.copyOf(n))
}
}.apply { isDaemon = true; start() }
val tunnels = ArrayBlockingQueue<Ppp.IpConfig>(1)
val fromLink = ArrayBlockingQueue<ByteArray>(10)
var closed = false
// (no number: none is dialled)
val err = Internet.connect(IspSettings(user = "alice", password = "s3cret"), dial = false) { cfg ->
tunnels.add(cfg)
object : Internet.Tunnel {
/** a packet from the link, kept */
override fun write(packet: ByteArray) { fromLink.add(packet) }
/** closed, noted */
override fun close() { closed = true }
}
}
assertEquals(null, err)
// (the ISP's side of PPP, once the app's is listening)
Thread.sleep(300)
isp.start()
val cfg = tunnels.poll(30, TimeUnit.SECONDS) ?: throw AssertionError("no link: ${ModemState.log.flow.value.takeLast(30)}")
assertEquals("192.168.7.42", cfg.address.hostAddress)
// (PPP's frames from the first octet: no AT commands before them)
assertEquals('\u007e', synchronized(sent) { sent[0] })
assertTrue(Internet.sendIp(Ip.udp(cfg.address.address, byteArrayOf(192.toByte(), 168.toByte(), 7, 1), 5353, 7, "hi".toByteArray())))
val back = fromLink.poll(20, TimeUnit.SECONDS) ?: throw AssertionError("no answer")
assertEquals("pong:hi", String(Ip.udpPayload(back)))
Internet.disconnect()
val end = System.currentTimeMillis() + 15_000
while (Internet.state.value?.running == true && System.currentTimeMillis() < end) Thread.sleep(100)
assertTrue(closed)
assertTrue(!ModemState.dte.claimed)
assertTrue(synchronized(sent) { sent.contains("+++") && sent.contains("ATH") })
}
}