The modem as a serial port on TCP and Bluetooth

A client has the modem's DTE as if on a serial cable, one at a time:
- TCP, raw or Telnet with RFC 2217's port control (the speed and format
  answered, DTR dropped hanging up, DCD/RI/DSR/CTS notified and polled),
  this phone only unless other devices are allowed, an optional password
- Bluetooth SPP: the phone offers the port, or connects to a paired
  device's (an HC-05 on a vintage computer, say), again when it drops
The client going hangs up a call (as DTR dropping would), if set.
They run while the modem is on, set in the settings' new section.
Tested with sockets, pyserial's rfc2217:// client and Robolectric's
Bluetooth.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
Claude committed 2026-10-16 23:22:28 +00:00
1 parent b28e79a9b6
commit be435b52fa
11 files changed
+1489

No files matched your search

+11
View File
@@ -11,6 +11,17 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- the modem as a Bluetooth serial port (SPP): Android 12 on asks for BLUETOOTH_CONNECT -->
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
<!-- the terminal's bell -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- the phone's shared storage in the Linux system (at /sdcard), when the user allows it:
@@ -0,0 +1,189 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.bridge
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.IOException
import java.util.UUID
/**
* The modem as a Bluetooth serial port (SPP, RFCOMM): either the phone
* offers it and a computer (or a Bluetooth serial adapter set to connect)
* connects to it, or the phone connects to a paired device's serial port
* (an HC-05 on a vintage computer's serial port, say), again whenever
* the connection drops while it's on.
*/
@SuppressLint("MissingPermission") // (checked: hasPermission())
class BluetoothBridge(
private val context: Context,
private val bridge: SerialBridge,
/** null: the phone offers the port; else the paired device's address it connects to */
val connectTo: String? = null,
) {
sealed interface State {
data object Stopped : State
/** offering the port, under [name] */
data class Listening(val name: String) : State
data class Connecting(val device: String) : State
data class Connected(val device: String) : State
data class Failed(val why: String) : State
}
private val _state = MutableStateFlow<State>(State.Stopped)
val state: StateFlow<State> = _state.asStateFlow()
@Volatile private var running = false
@Volatile private var server: BluetoothServerSocket? = null
@Volatile private var socket: BluetoothSocket? = null
private var thread: Thread? = null
/** (for the tests: the port offered, the connection there is) */
internal val serverSocket: BluetoothServerSocket? get() = server
internal val connection: BluetoothSocket? get() = socket
private val adapter: BluetoothAdapter?
get() = context.getSystemService(BluetoothManager::class.java)?.adapter
fun start(): Boolean {
if (running) return true
val a = adapter
when {
a == null -> return fail("this phone has no Bluetooth")
!hasPermission(context) -> return fail("Bluetooth isn't allowed (the app's permission)")
!a.isEnabled -> return fail("Bluetooth is off")
}
running = true
thread = Thread({
try {
if (connectTo == null) serve(a!!) else connect(a!!, connectTo)
} catch (e: Exception) {
// (a SecurityException: the permission taken back; anything else the stack throws)
running = false
fail(e.message ?: e.toString())
}
}, "bt-bridge").apply {
isDaemon = true
start()
}
return true
}
fun stop() {
running = false
runCatching { server?.close() }
runCatching { socket?.close() }
thread?.join(2000)
thread = null
_state.value = State.Stopped
}
private fun fail(why: String): Boolean {
_state.value = State.Failed(why)
return false
}
/** the port offered: each client served in turn */
private fun serve(a: BluetoothAdapter) {
while (running) {
val s = try {
a.listenUsingRfcommWithServiceRecord(SERVICE_NAME, SPP)
} catch (e: IOException) {
fail("can't offer the port: ${e.message}")
running = false
return
}
server = s
_state.value = State.Listening(runCatching { a.name }.getOrNull() ?: "this phone")
val c = try { s.accept() } catch (_: IOException) { null }
runCatching { s.close() }
server = null
if (c == null) continue
serveSocket(c)
}
}
/** a paired device's port: connected, again after it drops (a little later each time it fails) */
private fun connect(a: BluetoothAdapter, address: String) {
val d = try { a.getRemoteDevice(address) } catch (e: IllegalArgumentException) {
fail("not a Bluetooth address: $address")
running = false
return
}
var wait = 2_000L
while (running) {
val label = runCatching { d.name }.getOrNull() ?: address
_state.value = State.Connecting(label)
val s = try {
runCatching { a.cancelDiscovery() }
d.createRfcommSocketToServiceRecord(SPP).also { it.connect() }
} catch (e: IOException) {
_state.value = State.Failed("$label: ${e.message ?: "no connection"}")
null
} catch (e: RuntimeException) {
_state.value = State.Failed("$label: $e")
null
}
if (s != null) {
wait = 2_000L
serveSocket(s, label)
}
if (!running) break
try { Thread.sleep(wait) } catch (_: InterruptedException) { break }
wait = (wait * 2).coerceAtMost(60_000L)
}
}
private fun serveSocket(c: BluetoothSocket, known: String? = null) {
val d = c.remoteDevice
val name = known ?: runCatching { d?.name }.getOrNull() ?: d?.address ?: "a device"
socket = c
val p = Port("bluetooth", name, c.inputStream, c.outputStream) { c.close() }
if (!bridge.tryClaim(p)) {
runCatching {
c.outputStream.write("\r\nBUSY: the modem is in use\r\n".toByteArray())
c.close()
}
socket = null
return
}
_state.value = State.Connected(name)
try {
bridge.serve(p, null)
} finally {
socket = null
}
}
companion object {
/** the Serial Port Profile's service class */
val SPP: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
const val SERVICE_NAME = "D-Modem serial port"
/** the permission a bridge needs (Android 12 on: BLUETOOTH_CONNECT, asked for) */
fun permissions(): Array<String> =
if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_CONNECT) else emptyArray()
fun hasPermission(context: Context): Boolean =
permissions().all { context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }
/** the paired devices: (name, address) */
fun paired(context: Context): List<Pair<String, String>> {
if (!hasPermission(context)) return emptyList()
val a = context.getSystemService(BluetoothManager::class.java)?.adapter ?: return emptyList()
return runCatching {
a.bondedDevices.map { (it.name ?: it.address) to it.address }.sortedBy { it.first.lowercase() }
}.getOrDefault(emptyList())
}
}
}
@@ -0,0 +1,139 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.bridge
import android.content.Context
import com.neodesktop.dmodem.NativeModem
import com.neodesktop.dmodem.modem.ModemState
import com.neodesktop.dmodem.settings.BridgeSettings
import com.neodesktop.dmodem.terminal.TerminalLink
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
/**
* The modem's bridges while the modem service runs: TCP and Bluetooth
* as the settings have them, one client on the modem at a time between
* them; the modem's lines (DSR, DCD, RI) from its state.
*/
object Bridges {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val signals = MutableStateFlow(LineSignals())
val serial = SerialBridge(ModemState.dte, signals.asStateFlow(), ::hangUp)
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)
val btState: StateFlow<BluetoothBridge.State> = _bt.asStateFlow()
private var tcp: TcpBridge? = null
private var tcpJob: Job? = null
private var bt: BluetoothBridge? = null
private var btJob: Job? = null
private var applied: BridgeSettings? = null
private var watching = false
/** "RING" from the modem: RI on for a while */
@Volatile private var ringUntil = 0L
private fun watch() {
if (watching) return
watching = true
scope.launch {
combine(ModemState.run, ModemState.status) { r, s -> r to s }.collect { (r, s) -> update(r, s) }
}
ModemState.dte.addListener(TerminalLink.Listener { data, n ->
if (String(data, 0, n, Charsets.ISO_8859_1).contains("RING")) {
ringUntil = System.currentTimeMillis() + 6_000
update(ModemState.run.value, ModemState.status.value)
scope.launch {
kotlinx.coroutines.delay(6_100)
update(ModemState.run.value, ModemState.status.value)
}
}
})
}
private fun update(r: ModemState.Run, s: NativeModem.Status) {
signals.value = LineSignals(
ready = r == ModemState.Run.RUNNING,
offhook = s.offhook,
carrier = s.link == NativeModem.Link.ONLINE,
ringing = System.currentTimeMillis() < ringUntil && !s.offhook,
)
}
/** the bridges as [s] has them: those changed started again, the rest left as they are */
@Synchronized
fun apply(context: Context, s: BridgeSettings) {
watch()
serial.hangUpOnClose = s.hangUpOnClose
val old = applied
applied = s
val tcpSame = old != null && old.tcp == s.tcp && old.tcpPort == s.tcpPort && old.tcpAnyAddress == s.tcpAnyAddress &&
old.tcpTelnet == s.tcpTelnet && old.tcpPassword == s.tcpPassword
if (!tcpSame || (s.tcp && tcp == null)) {
stopTcp()
if (s.tcp) {
val t = TcpBridge(serial, s.tcpPort, s.tcpAnyAddress, s.tcpTelnet, s.tcpPassword)
tcp = t
tcpJob = scope.launch { t.state.collect { _tcp.value = it } }
t.start()
}
}
val btSame = old != null && old.bluetooth == s.bluetooth && old.btConnectTo == s.btConnectTo
if (!btSame || (s.bluetooth && bt == null)) {
stopBt()
if (s.bluetooth) {
val b = BluetoothBridge(context.applicationContext, serial, s.btConnectTo.ifBlank { null })
bt = b
btJob = scope.launch { b.state.collect { _bt.value = it } }
b.start()
}
}
}
@Synchronized
fun stopAll() {
stopTcp()
stopBt()
applied = null
}
private fun stopTcp() {
tcp?.stop()
tcp = null
tcpJob?.cancel()
_tcp.value = TcpBridge.State.Stopped
}
private fun stopBt() {
bt?.stop()
bt = null
btJob?.cancel()
_bt.value = BluetoothBridge.State.Stopped
}
/**
* the call hung up as a DTE's DTR going would: online, +++ between its
* guard times then ATH; dialling or off hook, ATH
*/
fun hangUp() {
val dte = ModemState.dte
if (signals.value.carrier) {
Thread.sleep(GUARD_MS)
dte.write("+++")
Thread.sleep(GUARD_MS)
}
dte.write("\rATH\r")
}
private const val GUARD_MS = 1200L
}
@@ -0,0 +1,352 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.bridge
import com.neodesktop.dmodem.terminal.TerminalLink
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
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/** What a serial port's modem lines say: the modem there (DSR), off hook, a carrier (DCD), ringing (RI). */
data class LineSignals(
val ready: Boolean = false,
val offhook: Boolean = false,
val carrier: Boolean = false,
val ringing: Boolean = false,
)
/** a client on a bridge, for the UI */
data class BridgeClient(val via: String, val name: String, val since: Long = System.currentTimeMillis())
/** a connection a client came on: its streams, and how to end it */
class Port(val via: String, val name: String, val input: InputStream, val output: OutputStream, val close: () -> Unit)
/**
* The modem's DTE handed to one client at a time, as a serial cable
* would: what the modem sends goes to the client, what the client sends
* to the modem (through [Telnet] when the connection speaks it). The
* client going (or dropping DTR, with RFC 2217) is DTR dropped: the call
* hung up, if [hangUpOnClose].
*/
class SerialBridge(
private val dte: TerminalLink,
private val signals: StateFlow<LineSignals>,
/** the call hung up (the modem online or off hook): blocks for the guard times */
private val hangUp: () -> Unit,
@Volatile var hangUpOnClose: Boolean = true,
) {
private val _client = MutableStateFlow<BridgeClient?>(null)
/** who has the modem now, through which bridge */
val client: StateFlow<BridgeClient?> = _client.asStateFlow()
private val lock = Any()
private var current: Port? = null
/** another client has it: [p] turned away (true: it got the modem) */
fun tryClaim(p: Port): Boolean = synchronized(lock) {
if (current != null) return false
current = p
_client.value = BridgeClient(p.via, p.name)
true
}
/** the client off (its connection closed: the other side sees it end) */
fun kick() {
synchronized(lock) { current }?.let { runCatching { it.close() } }
}
/**
* [p] served until it ends (claimed first with [tryClaim]); [telnet]: it
* speaks Telnet (and maybe RFC 2217)
*/
fun serve(p: Port, telnet: Telnet?) {
val out = LinkedBlockingQueue<ByteArray>()
val listener = TerminalLink.Listener { data, n ->
val b = data.copyOf(n)
out.put(telnet?.encode(b) ?: b)
}
val on = java.util.concurrent.atomic.AtomicBoolean(true)
val writer = Thread({
try {
while (on.get()) {
val b = out.poll(250, TimeUnit.MILLISECONDS) ?: continue
p.output.write(b)
// (what else is waiting, in the same write)
while (true) p.output.write(out.poll() ?: break)
p.output.flush()
}
} catch (_: IOException) {
runCatching { p.close() }
}
}, "bridge-out-${p.via}").apply { isDaemon = true; start() }
// RFC 2217: the modem's lines as they change
val watcher = telnet?.let { t ->
Thread({
while (on.get()) {
// (null unless they changed, or the client has just asked for RFC 2217)
t.modemState(signals.value)?.let { out.put(it) }
try { Thread.sleep(100) } catch (_: InterruptedException) { break }
}
}, "bridge-lines-${p.via}").apply { isDaemon = true; start() }
}
telnet?.onDtr = { on -> if (!on) dropDtr() }
telnet?.reply = { b -> out.put(b) }
dte.addListener(listener)
try {
telnet?.start()?.let { out.put(it) }
val buf = ByteArray(4096)
while (true) {
val n = try { p.input.read(buf) } catch (_: IOException) { -1 }
if (n < 0) break
if (n == 0) continue
val data = telnet?.decode(buf, n) ?: buf.copyOf(n)
if (data.isNotEmpty()) dte.write(data)
}
} finally {
dte.removeListener(listener)
on.set(false)
writer.join(1000)
watcher?.interrupt()
runCatching { p.close() }
synchronized(lock) {
if (current === p) {
current = null
_client.value = null
}
}
if (hangUpOnClose) dropDtr()
}
}
/** DTR off: the call over (as AT&D2 has it) */
private fun dropDtr() {
val s = signals.value
if (s.offhook || s.carrier) Thread({ hangUp() }, "bridge-hangup").apply { isDaemon = true; start() }
}
}
/**
* The server side of Telnet for a serial port: binary both ways, the
* echo the modem's (WILL ECHO, so the client doesn't), and RFC 2217's
* COM-PORT-OPTION: the speed and the character format kept (and
* answered: a modem on SIP has no speed of its own), DTR dropped as a
* hang-up, the modem's lines notified (DCD, RI, DSR, CTS).
*/
class Telnet {
/** DTR set by the client (RFC 2217 SET-CONTROL 8/9) */
var onDtr: (Boolean) -> Unit = {}
/** answers to the client (negotiation, RFC 2217's replies) */
var reply: (ByteArray) -> Unit = {}
var baud = 115_200
private set
var dataSize = 8
private set
var parity = 1
private set
var stopSize = 1
private set
var dtr = true
private set
/** the client said it does RFC 2217 */
var comPort = false
private set
private var modemMask = 0xff
/** the modem's lines as last told */
@Volatile private var lines = LineSignals()
private fun lineBits(s: LineSignals) =
(if (s.carrier) 0x80 else 0) or (if (s.ringing) 0x40 else 0) or (if (s.ready) 0x30 else 0)
private var lastModem = -1
private var state = 0
private var cmd = 0
private val sb = java.io.ByteArrayOutputStream()
private var crPending = false
private val ours = HashSet<Int>()
private val theirs = HashSet<Int>()
private var started = false
/** what's sent first: the options we'll have (once: empty after) */
fun start(): ByteArray {
if (started) return ByteArray(0)
started = true
ours.addAll(listOf(BINARY, ECHO, SGA))
theirs.addAll(listOf(BINARY, SGA))
return byteArrayOf(
IAC, WILL, BINARY.toByte(), IAC, DO, BINARY.toByte(),
IAC, WILL, ECHO.toByte(), IAC, WILL, SGA.toByte(), IAC, DO, SGA.toByte(),
)
}
/** the modem's octets, IAC doubled */
fun encode(b: ByteArray): ByteArray {
if (b.none { it == IAC }) return b
val o = java.io.ByteArrayOutputStream(b.size + 8)
for (x in b) { o.write(x.toInt()); if (x == IAC) o.write(0xff) }
return o.toByteArray()
}
/** the client's octets: the data in them, the commands acted on */
fun decode(b: ByteArray, n: Int): ByteArray {
val o = java.io.ByteArrayOutputStream(n)
for (i in 0 until n) {
val c = b[i].toInt() and 0xff
when (state) {
0 -> when {
c == 0xff -> state = 1
// (CR NUL, CR LF in NVT: a CR, when the client isn't binary)
crPending -> { crPending = false; if (!(c == 0 && BINARY !in theirs)) o.write(c) }
c == 13 && BINARY !in theirs -> { crPending = true; o.write(c) }
else -> o.write(c)
}
1 -> when (c) {
0xff -> { o.write(0xff); state = 0 }
WILL_I, WONT_I, DO_I, DONT_I -> { cmd = c; state = 2 }
SB_I -> { sb.reset(); state = 3 }
else -> state = 0 // NOP, BRK, AYT…
}
2 -> { negotiate(cmd, c); state = 0 }
3 -> if (c == 0xff) state = 4 else sb.write(c)
4 -> when (c) {
0xff -> { sb.write(0xff); state = 3 }
SE_I -> { subnegotiation(sb.toByteArray()); state = 0 }
else -> state = 3
}
}
}
return o.toByteArray()
}
private fun negotiate(cmd: Int, opt: Int) {
when (cmd) {
DO_I -> if (opt in OFFER) {
if (ours.add(opt)) send(WILL, opt)
if (opt == COM_PORT) comPort = true
} else send(WONT, opt)
DONT_I -> if (ours.remove(opt)) send(WONT, opt)
WILL_I -> if (opt in ACCEPT) {
if (theirs.add(opt)) send(DO, opt)
if (opt == COM_PORT) comPort = true
} else send(DONT, opt)
WONT_I -> if (theirs.remove(opt)) send(DONT, opt)
}
}
private fun send(verb: Byte, opt: Int) = reply(byteArrayOf(IAC, verb, opt.toByte()))
private fun subnegotiation(s: ByteArray) {
if (s.isEmpty() || (s[0].toInt() and 0xff) != COM_PORT || s.size < 2) return
comPort = true
val c = s[1].toInt() and 0xff
val v = s.copyOfRange(2, s.size)
fun u8() = if (v.isNotEmpty()) v[0].toInt() and 0xff else 0
when (c) {
SIGNATURE -> answer(c, "D-Modem".toByteArray())
SET_BAUDRATE -> {
if (v.size >= 4) {
val b = ((v[0].toInt() and 0xff) shl 24) or ((v[1].toInt() and 0xff) shl 16) or
((v[2].toInt() and 0xff) shl 8) or (v[3].toInt() and 0xff)
if (b != 0) baud = b
}
answer(c, byteArrayOf((baud ushr 24).toByte(), (baud ushr 16).toByte(), (baud ushr 8).toByte(), baud.toByte()))
}
SET_DATASIZE -> { if (u8() in 5..8) dataSize = u8(); answer(c, byteArrayOf(dataSize.toByte())) }
SET_PARITY -> { if (u8() in 1..5) parity = u8(); answer(c, byteArrayOf(parity.toByte())) }
SET_STOPSIZE -> { if (u8() in 1..3) stopSize = u8(); answer(c, byteArrayOf(stopSize.toByte())) }
SET_CONTROL -> {
val r = when (val x = u8()) {
0 -> 1 // flow control: none
4 -> 6 // BREAK: off
7 -> if (dtr) 8 else 9 // DTR
8, 9 -> {
val on = x == 8
if (on != dtr) { dtr = on; onDtr(on) }
x
}
10 -> 11 // RTS: on
13 -> 14 // inbound flow control: none
else -> x // (the rest as asked)
}
answer(c, byteArrayOf(r.toByte()))
}
SET_LINESTATE_MASK -> answer(c, byteArrayOf(u8().toByte()))
SET_MODEMSTATE_MASK -> { modemMask = u8(); answer(c, byteArrayOf(modemMask.toByte())); lastModem = -1 }
PURGE_DATA -> answer(c, byteArrayOf(u8().toByte()))
// (asked for, as pyserial polls them: the lines now; the line's state: nothing waiting to go)
NOTIFY_MODEMSTATE -> answer(c, byteArrayOf((lineBits(lines) and modemMask).toByte()))
NOTIFY_LINESTATE -> answer(c, byteArrayOf(0x60))
FLOWCONTROL_SUSPEND, FLOWCONTROL_RESUME -> {}
}
}
private fun answer(c: Int, v: ByteArray) = reply(subneg(c + 100, v))
private fun subneg(c: Int, v: ByteArray): ByteArray {
val o = java.io.ByteArrayOutputStream()
o.write(0xff); o.write(SB_I); o.write(COM_PORT); o.write(c)
for (x in v) { o.write(x.toInt() and 0xff); if (x == IAC) o.write(0xff) }
o.write(0xff); o.write(SE_I)
return o.toByteArray()
}
/** the modem's lines for the client (RFC 2217 NOTIFY-MODEMSTATE), when it does RFC 2217 and they changed */
fun modemState(s: LineSignals): ByteArray? {
lines = s
if (!comPort) return null
var v = lineBits(s)
if (lastModem >= 0) {
if ((v xor lastModem) and 0x80 != 0) v = v or 0x08
if (lastModem and 0x40 != 0 && v and 0x40 == 0) v = v or 0x04
if ((v xor lastModem) and 0x20 != 0) v = v or 0x02
if ((v xor lastModem) and 0x10 != 0) v = v or 0x01
}
val same = (v and 0xf0) == (lastModem and 0xf0)
lastModem = v and 0xf0
if (same) return null
return subneg(NOTIFY_MODEMSTATE + 100, byteArrayOf((v and modemMask).toByte()))
}
companion object {
const val IAC: Byte = -1
const val WILL: Byte = -5
const val WONT: Byte = -4
const val DO: Byte = -3
const val DONT: Byte = -2
const val WILL_I = 251
const val WONT_I = 252
const val DO_I = 253
const val DONT_I = 254
const val SB_I = 250
const val SE_I = 240
const val BINARY = 0
const val ECHO = 1
const val SGA = 3
const val COM_PORT = 44
val OFFER = setOf(BINARY, ECHO, SGA, COM_PORT)
val ACCEPT = setOf(BINARY, SGA, COM_PORT)
// RFC 2217's commands (client to server; the server's answers 100 more)
const val SIGNATURE = 0
const val SET_BAUDRATE = 1
const val SET_DATASIZE = 2
const val SET_PARITY = 3
const val SET_STOPSIZE = 4
const val SET_CONTROL = 5
const val NOTIFY_LINESTATE = 6
const val NOTIFY_MODEMSTATE = 7
const val FLOWCONTROL_SUSPEND = 8
const val FLOWCONTROL_RESUME = 9
const val SET_LINESTATE_MASK = 10
const val SET_MODEMSTATE_MASK = 11
const val PURGE_DATA = 12
}
}
@@ -0,0 +1,148 @@
// 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.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.security.MessageDigest
/**
* The modem as a serial port on TCP (as ser2net or tcpser have it): a
* client that connects has the modem's DTE, raw or in Telnet (with RFC
* 2217's port control) as [telnet] says. Only this phone's own programs
* can connect unless [anyAddress]; a [password], if set, is asked for
* first.
*/
class TcpBridge(
private val bridge: SerialBridge,
val port: Int,
val anyAddress: Boolean = false,
val telnet: Boolean = false,
private val password: String = "",
) {
sealed interface State {
data object Stopped : State
data class Listening(val port: Int) : State
data class Failed(val why: String) : State
}
private val _state = MutableStateFlow<State>(State.Stopped)
val state: StateFlow<State> = _state.asStateFlow()
@Volatile private var server: ServerSocket? = null
private var thread: Thread? = null
/** listening from now (false: the port couldn't be had; [state] says why) */
fun start(): Boolean {
if (server != null) return true
val s = try {
ServerSocket().apply {
reuseAddress = true
bind(InetSocketAddress(if (anyAddress) null else InetAddress.getLoopbackAddress(), port), 4)
}
} catch (e: IOException) {
_state.value = State.Failed("port $port: ${e.message}")
return false
}
server = s
_state.value = State.Listening(s.localPort)
thread = Thread({ accept(s) }, "tcp-bridge-$port").apply { isDaemon = true; start() }
return true
}
/** the port the server got (when [port] was 0: any) */
val localPort: Int get() = server?.localPort ?: -1
fun stop() {
val s = server ?: return
server = null
runCatching { s.close() }
thread?.join(2000)
_state.value = State.Stopped
}
private fun accept(s: ServerSocket) {
while (!s.isClosed) {
val c = try { s.accept() } catch (_: IOException) { break }
Thread({ client(c) }, "tcp-bridge-client").apply { isDaemon = true; start() }
}
}
private fun client(c: Socket) {
c.tcpNoDelay = true
val name = c.inetAddress.hostAddress ?: "?"
val input = c.getInputStream()
val output = c.getOutputStream()
val t = if (telnet) Telnet() else null
try {
if (t != null) output.write(t.start())
if (password.isNotEmpty() && !login(input, output, t)) {
c.close()
return
}
val p = Port("tcp", name, input, output) { c.close() }
if (!bridge.tryClaim(p)) {
output.write("\r\nBUSY: the modem is in use\r\n".toByteArray())
output.flush()
c.close()
return
}
// (Telnet's replies from now go out through the bridge's writer)
bridge.serve(p, t)
} catch (_: IOException) {
runCatching { c.close() }
}
}
/** the password asked for, up to three times */
private fun login(input: InputStream, output: OutputStream, t: Telnet?): Boolean {
// (Telnet's answers while it's asked: straight out)
t?.reply = { b -> synchronized(output) { output.write(b); output.flush() } }
repeat(3) {
output.write("Password: ".toByteArray())
output.flush()
val line = readLine(input, t) ?: return false
if (same(line, password)) {
output.write("\r\n".toByteArray())
return true
}
Thread.sleep(2000)
output.write("\r\nWrong password\r\n".toByteArray())
}
return false
}
/** a line typed (no echo: the client was told we echo, and we don't) */
private fun readLine(input: InputStream, t: Telnet?): String? {
val sb = StringBuilder()
val one = ByteArray(1)
while (sb.length < 256) {
val n = input.read(one)
if (n < 0) return null
val d = t?.decode(one, 1) ?: one
for (b in d) {
val c = b.toInt() and 0xff
when (c) {
13, 10 -> if (sb.isNotEmpty() || c == 13) return sb.toString()
8, 127 -> if (sb.isNotEmpty()) sb.setLength(sb.length - 1)
0 -> {}
else -> sb.append(c.toChar())
}
}
}
return null
}
private fun same(a: String, b: String): Boolean {
val d = MessageDigest.getInstance("SHA-256")
return MessageDigest.isEqual(d.digest(a.toByteArray()), d.digest(b.toByteArray()))
}
}
@@ -21,6 +21,8 @@ import androidx.core.app.ServiceCompat
import com.neodesktop.dmodem.DModemApp
import com.neodesktop.dmodem.NativeModem
import com.neodesktop.dmodem.R
import com.neodesktop.dmodem.bridge.Bridges
import com.neodesktop.dmodem.settings.BridgeSettingsStore
import com.neodesktop.dmodem.settings.ModemSettings
import com.neodesktop.dmodem.settings.SettingsStore
import com.neodesktop.dmodem.ui.MainActivity
@@ -92,6 +94,13 @@ class ModemService : Service() {
override fun onCreate() {
super.onCreate()
store = SettingsStore(this)
// the TCP and Bluetooth bridges, as their settings are (now and as they change), while the modem is on
scope.launch {
combine(BridgeSettingsStore(this@ModemService).settings, ModemState.run) { b, r -> b to r }.collect { (b, r) ->
if (r == ModemState.Run.RUNNING) Bridges.apply(this@ModemService, b)
else if (r == ModemState.Run.STOPPED) Bridges.stopAll()
}
}
scope.launch {
combine(ModemState.run, ModemState.status) { r, s -> r to s }.collect { (r, s) ->
if (r != ModemState.Run.STOPPED) notify(notification(r, s))
@@ -215,6 +224,7 @@ class ModemService : Service() {
ModemState.setRun(ModemState.Run.STOPPING)
stopNative()
}
Bridges.stopAll()
unwatchNetwork()
releaseLocks()
restartPending = false
@@ -0,0 +1,87 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.settings
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
/** The modem's serial port for other programs and devices: on TCP, on Bluetooth. */
data class BridgeSettings(
val tcp: Boolean = false,
val tcpPort: Int = 2323,
/** other devices on the network may connect (else only this phone's programs) */
val tcpAnyAddress: Boolean = false,
/** Telnet, with RFC 2217's port control (else raw) */
val tcpTelnet: Boolean = false,
/** asked for first, if set */
val tcpPassword: String = "",
val bluetooth: Boolean = false,
/** a paired device's address to connect to (empty: the phone offers the port) */
val btConnectTo: String = "",
/** the client going hangs up the call (DTR dropped) */
val hangUpOnClose: Boolean = true,
)
private val Context.bridgeStore: DataStore<Preferences> by preferencesDataStore("bridges")
class BridgeSettingsStore(private val context: Context) {
private object K {
val tcp = booleanPreferencesKey("tcp")
val tcpPort = intPreferencesKey("tcp_port")
val tcpAny = booleanPreferencesKey("tcp_any")
val tcpTelnet = booleanPreferencesKey("tcp_telnet")
val tcpPassword = stringPreferencesKey("tcp_password")
val bt = booleanPreferencesKey("bt")
val btConnectTo = stringPreferencesKey("bt_connect_to")
val hangUp = booleanPreferencesKey("hang_up_on_close")
}
val settings: Flow<BridgeSettings> = context.bridgeStore.data.map { from(it) }
private fun from(p: Preferences): BridgeSettings {
val d = BridgeSettings()
return BridgeSettings(
tcp = p[K.tcp] ?: d.tcp,
tcpPort = p[K.tcpPort] ?: d.tcpPort,
tcpAnyAddress = p[K.tcpAny] ?: d.tcpAnyAddress,
tcpTelnet = p[K.tcpTelnet] ?: d.tcpTelnet,
tcpPassword = p[K.tcpPassword] ?: d.tcpPassword,
bluetooth = p[K.bt] ?: d.bluetooth,
btConnectTo = p[K.btConnectTo] ?: d.btConnectTo,
hangUpOnClose = p[K.hangUp] ?: d.hangUpOnClose,
)
}
suspend fun current(): BridgeSettings = settings.first()
/** a change made to what's stored now (two quick changes don't undo each other) */
suspend fun update(change: (BridgeSettings) -> BridgeSettings) {
context.bridgeStore.edit { p -> write(p, change(from(p))) }
}
suspend fun save(s: BridgeSettings) {
context.bridgeStore.edit { p -> write(p, s) }
}
private fun write(p: androidx.datastore.preferences.core.MutablePreferences, s: BridgeSettings) {
run {
p[K.tcp] = s.tcp
p[K.tcpPort] = s.tcpPort.coerceIn(1, 65535)
p[K.tcpAny] = s.tcpAnyAddress
p[K.tcpTelnet] = s.tcpTelnet
p[K.tcpPassword] = s.tcpPassword
p[K.bt] = s.bluetooth
p[K.btConnectTo] = s.btConnectTo.trim()
p[K.hangUp] = s.hangUpOnClose
}
}
}
@@ -0,0 +1,206 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.ui
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
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
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.neodesktop.dmodem.bridge.BluetoothBridge
import com.neodesktop.dmodem.bridge.Bridges
import com.neodesktop.dmodem.bridge.TcpBridge
import com.neodesktop.dmodem.modem.ModemState
import com.neodesktop.dmodem.settings.BridgeSettings
import com.neodesktop.dmodem.settings.BridgeSettingsStore
import kotlinx.coroutines.launch
import java.net.Inet4Address
import java.net.NetworkInterface
/** The modem's serial port for other programs and devices: on TCP and on Bluetooth. */
@Composable
fun BridgeSection() {
val context = LocalContext.current
val store = remember { BridgeSettingsStore(context.applicationContext) }
val scope = rememberCoroutineScope()
val current by store.settings.collectAsStateWithLifecycle(initialValue = null)
val s = current ?: return
fun change(f: (BridgeSettings) -> BridgeSettings) {
scope.launch { store.update(f) }
}
val run by ModemState.run.collectAsStateWithLifecycle()
val tcpState by Bridges.tcpState.collectAsStateWithLifecycle()
val btState by Bridges.btState.collectAsStateWithLifecycle()
val client by Bridges.serial.client.collectAsStateWithLifecycle()
var hasBt by remember { mutableStateOf(BluetoothBridge.hasPermission(context)) }
var paired by remember { mutableStateOf(BluetoothBridge.paired(context)) }
var pickDevice by remember { mutableStateOf(false) }
val askBt = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
hasBt = BluetoothBridge.hasPermission(context)
paired = BluetoothBridge.paired(context)
if (hasBt) change { it.copy(bluetooth = true) }
}
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Serial port for other devices", style = MaterialTheme.typography.titleMedium)
Text(
"Programs and computers use the modem as if on a serial cable, one at a time, while the modem is on." +
if (run == ModemState.Run.STOPPED) " (The modem is off now.)" else "",
style = MaterialTheme.typography.bodySmall,
)
client?.let { c ->
Row(verticalAlignment = Alignment.CenterVertically) {
Text("In use: ${c.name} (${c.via})", Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = { Thread { Bridges.serial.kick() }.start() }) { Text("Disconnect") }
}
}
// TCP
Toggle("On TCP (ser2net, emulators, socat)", s.tcp) { v -> change { it.copy(tcp = v) } }
if (s.tcp) {
Text(tcpText(tcpState, s), style = MaterialTheme.typography.bodySmall)
Applied("Port", s.tcpPort.toString(), number = true) { v ->
v.toIntOrNull()?.takeIf { it in 1024..65535 }?.let { p -> change { it.copy(tcpPort = p) } }
}
Toggle("Telnet, with RFC 2217 port control (else raw)", s.tcpTelnet) { v -> change { it.copy(tcpTelnet = v) } }
Toggle("Other devices on the network can connect", s.tcpAnyAddress) { v -> change { it.copy(tcpAnyAddress = v) } }
if (s.tcpAnyAddress) {
Text(
"Anyone on the same network can then dial out on your SIP account: set a password." +
addresses().takeIf { it.isNotEmpty() }?.let { "\nThis phone: " + it.joinToString(", ") { a -> "$a:${s.tcpPort}" } }.orEmpty(),
style = MaterialTheme.typography.bodySmall,
color = if (s.tcpPassword.isEmpty()) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
Applied("Password (empty: none)", s.tcpPassword, password = true) { v -> change { it.copy(tcpPassword = v) } }
}
// Bluetooth
Toggle("On Bluetooth (serial port profile)", s.bluetooth) { v ->
if (v && !hasBt) askBt.launch(BluetoothBridge.permissions()) else change { it.copy(bluetooth = v) }
}
if (s.bluetooth) {
Text(btText(btState), style = MaterialTheme.typography.bodySmall)
Choice("Other devices connect to this phone", s.btConnectTo.isEmpty()) { change { it.copy(btConnectTo = "") } }
Choice(
"Connect to a paired device" + (s.btConnectTo.takeIf { it.isNotEmpty() }?.let { a ->
": " + (paired.firstOrNull { it.second == a }?.first ?: a)
} ?: ""),
s.btConnectTo.isNotEmpty(),
) {
paired = BluetoothBridge.paired(context)
pickDevice = true
}
if (s.btConnectTo.isEmpty()) {
OutlinedButton(onClick = {
runCatching {
context.startActivity(
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE)
.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
}) { Text("Make the phone visible for pairing") }
}
if (pickDevice) {
Column(Modifier.padding(start = 16.dp)) {
if (paired.isEmpty()) Text("No paired devices: pair one in Android's Bluetooth settings", style = MaterialTheme.typography.bodySmall)
for ((name, address) in paired) {
Text(
"$name ($address)",
Modifier.fillMaxWidth().clickable {
pickDevice = false
change { it.copy(btConnectTo = address) }
}.padding(vertical = 8.dp),
)
}
TextButton(onClick = { pickDevice = false }) { Text("Cancel") }
}
}
}
Toggle("Hang up when the client disconnects (drops DTR)", s.hangUpOnClose) { v -> change { it.copy(hangUpOnClose = v) } }
}
}
private fun tcpText(st: TcpBridge.State, s: BridgeSettings): String = when (st) {
TcpBridge.State.Stopped -> "Starts with the modem"
is TcpBridge.State.Listening -> "Listening on " + (if (s.tcpAnyAddress) "port" else "localhost port") + " ${st.port}" +
if (s.tcpTelnet) " (Telnet)" else " (raw)"
is TcpBridge.State.Failed -> "Can't listen: ${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}\""
is BluetoothBridge.State.Connecting -> "Connecting to ${st.device}…"
is BluetoothBridge.State.Connected -> "Connected to ${st.device}"
is BluetoothBridge.State.Failed -> st.why
}
/** the phone's IPv4 addresses (not the loopback) */
private fun addresses(): List<String> = runCatching {
NetworkInterface.getNetworkInterfaces().toList().filter { it.isUp && !it.isLoopback }
.flatMap { it.inetAddresses.toList() }.filterIsInstance<Inet4Address>().mapNotNull { it.hostAddress }
}.getOrDefault(emptyList())
@Composable
private fun Toggle(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(label, Modifier.weight(1f))
Switch(checked = value, onCheckedChange = onChange)
}
}
@Composable
private fun Choice(label: String, selected: Boolean, onClick: () -> Unit) {
Row(Modifier.fillMaxWidth().clickable(onClick = onClick), verticalAlignment = Alignment.CenterVertically) {
RadioButton(selected = selected, onClick = onClick)
Text(label)
}
}
/** a field whose value is used when Set is pressed (a port half typed isn't listened on) */
@Composable
private fun Applied(label: String, value: String, number: Boolean = false, password: Boolean = false, onSet: (String) -> Unit) {
var text by remember(value) { mutableStateOf(value) }
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedTextField(
value = text,
onValueChange = { text = if (number) it.filter(Char::isDigit).take(5) else it },
label = { Text(label) },
singleLine = true,
visualTransformation = if (password) PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None,
keyboardOptions = KeyboardOptions(keyboardType = if (number) KeyboardType.Number else if (password) KeyboardType.Password else KeyboardType.Text),
modifier = Modifier.weight(1f),
)
Button(onClick = { onSet(text) }, enabled = text != value) { Text("Set") }
}
}
@@ -104,6 +104,8 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {
}
}
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
BridgeSection()
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
AppearanceSection()
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
@@ -0,0 +1,133 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.bridge
import android.Manifest
import android.app.Application
import android.bluetooth.BluetoothManager
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.neodesktop.dmodem.terminal.TerminalLink
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
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.Shadows.shadowOf
import org.robolectric.annotation.Config
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
/**
* The modem as a Bluetooth serial port (Robolectric's Bluetooth): a
* device connecting to the phone's port, the phone connecting to a
* paired device's; the permission and Bluetooth being off said.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [35])
class BluetoothBridgeTest {
private class FakeModem : TerminalLink {
override val state: StateFlow<TerminalLink.State> = MutableStateFlow(TerminalLink.State.Open)
val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
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()) }
}
private val ctx: Context = ApplicationProvider.getApplicationContext()
private val modem = FakeModem()
private val signals = MutableStateFlow(LineSignals(ready = true))
private val hangUps = AtomicInteger()
private val serial = SerialBridge(modem, signals, { hangUps.incrementAndGet() })
private var bridge: BluetoothBridge? = null
private val adapter get() = ctx.getSystemService(BluetoothManager::class.java).adapter
@Before
fun setUp() {
shadowOf(ctx as Application).grantPermissions(Manifest.permission.BLUETOOTH_CONNECT)
shadowOf(adapter).setEnabled(true)
}
@After
fun tearDown() {
bridge?.stop()
}
private fun waitUntil(what: String, ok: () -> Boolean) {
val end = System.currentTimeMillis() + 5000
while (!ok() && System.currentTimeMillis() < end) Thread.sleep(20)
assertTrue(what, ok())
}
private fun readUntil(i: InputStream, want: String): String {
val sb = StringBuilder()
val end = System.currentTimeMillis() + 5000
while (!sb.contains(want) && System.currentTimeMillis() < end) {
if (i.available() > 0) sb.append(i.read().toChar()) else Thread.sleep(10)
}
assertTrue("\"$want\" in \"$sb\"", sb.contains(want))
return sb.toString()
}
@Test
fun aDeviceConnectsToThePhone() {
val b = BluetoothBridge(ctx, serial).also { bridge = it }
assertTrue(b.start())
waitUntil("offering the port") { b.state.value is BluetoothBridge.State.Listening && b.serverSocket != null }
val device = adapter.getRemoteDevice("00:11:22:33:44:55")
val s = shadowOf(b.serverSocket!!).deviceConnected(device)
waitUntil("connected") { b.state.value is BluetoothBridge.State.Connected }
assertEquals("bluetooth", serial.client.value?.via)
shadowOf(s).inputStreamFeeder.apply { write("ATZ\r".toByteArray()); flush() }
readUntil(shadowOf(s).outputStreamSink, "OK")
assertEquals("ATZ\r", modem.sent())
// online, then the device gone: hung up, and the port offered again
signals.value = LineSignals(ready = true, offhook = true, carrier = true)
shadowOf(s).inputStreamFeeder.close()
waitUntil("hung up") { hangUps.get() == 1 }
waitUntil("offered again") { b.state.value is BluetoothBridge.State.Listening }
assertEquals(null, serial.client.value)
}
@Test
fun thePhoneConnectsToAPairedDevice() {
val device = adapter.getRemoteDevice("66:77:88:99:AA:BB")
shadowOf(adapter).setBondedDevices(setOf(device))
assertEquals(listOf("66:77:88:99:AA:BB"), BluetoothBridge.paired(ctx).map { it.second })
val b = BluetoothBridge(ctx, serial, connectTo = "66:77:88:99:AA:BB").also { bridge = it }
assertTrue(b.start())
waitUntil("connected") { b.state.value is BluetoothBridge.State.Connected && b.connection != null }
val s = b.connection!!
shadowOf(s).inputStreamFeeder.apply { write("AT&F\r".toByteArray()); flush() }
readUntil(shadowOf(s).outputStreamSink, "OK")
assertEquals("AT&F\r", modem.sent())
}
@Test
fun offOrNotAllowedSaysSo() {
shadowOf(adapter).setEnabled(false)
val b = BluetoothBridge(ctx, serial)
assertTrue(!b.start())
assertEquals(BluetoothBridge.State.Failed("Bluetooth is off"), b.state.value)
shadowOf(adapter).setEnabled(true)
shadowOf(ctx as Application).denyPermissions(Manifest.permission.BLUETOOTH_CONNECT)
assertTrue(!b.start())
assertTrue((b.state.value as BluetoothBridge.State.Failed).why.contains("permission"))
}
}
@@ -0,0 +1,212 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.bridge
import com.neodesktop.dmodem.terminal.TerminalLink
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.io.File
import java.net.InetSocketAddress
import java.net.Socket
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
/**
* The modem as a serial port on TCP: raw and Telnet clients, one at a
* time, a password, RFC 2217 (pyserial's rfc2217:// client): the speed
* set, the carrier seen, DTR dropped hanging up.
*/
class TcpBridgeTest {
/** a modem: what it was sent, and "OK" for each AT command */
private class FakeModem : TerminalLink {
override val state: StateFlow<TerminalLink.State> = MutableStateFlow(TerminalLink.State.Open)
val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
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) }
val s = String(data, offset, length, Charsets.ISO_8859_1)
if (s.contains("AT") && s.endsWith("\r")) emit("\r\nOK\r\n".toByteArray())
return true
}
fun emit(b: ByteArray) = listeners.forEach { it.onData(b, b.size) }
fun sent(): ByteArray = synchronized(got) { got.toByteArray() }
}
private val modem = FakeModem()
private val signals = MutableStateFlow(LineSignals(ready = true))
private val hangUps = AtomicInteger()
private val serial = SerialBridge(modem, signals, { hangUps.incrementAndGet() })
private val bridges = ArrayList<TcpBridge>()
@After
fun tearDown() = bridges.forEach { it.stop() }
private fun bridge(telnet: Boolean = false, password: String = ""): TcpBridge =
TcpBridge(serial, 0, telnet = telnet, password = password).also { assertTrue(it.start()); bridges.add(it) }
private fun connect(b: TcpBridge) = Socket().apply {
connect(InetSocketAddress("127.0.0.1", b.localPort), 2000)
soTimeout = 5000
}
/** what comes until [want] is in it */
private fun readUntil(s: Socket, want: String): String {
val sb = StringBuilder()
val buf = ByteArray(1024)
val end = System.currentTimeMillis() + 5000
while (!sb.contains(want) && System.currentTimeMillis() < end) {
val n = s.getInputStream().read(buf)
if (n < 0) break
sb.append(String(buf, 0, n, Charsets.ISO_8859_1))
}
assertTrue("\"$want\" in \"$sb\"", sb.contains(want))
return sb.toString()
}
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 rawBothWaysEveryByte() {
val b = bridge()
connect(b).use { s ->
waitUntil("claimed") { serial.client.value != null }
assertEquals("tcp", serial.client.value!!.via)
s.getOutputStream().write("ATDT5551212\r".toByteArray())
readUntil(s, "OK")
// every byte value, as it is, each way (no Telnet: 0xff isn't special)
val all = ByteArray(256) { it.toByte() }
modem.emit(all)
val got = ByteArrayOutputStream()
val buf = ByteArray(512)
while (got.size() < 256) got.write(buf, 0, s.getInputStream().read(buf))
assertArrayEquals(all, got.toByteArray())
s.getOutputStream().write(all)
waitUntil("the modem got them") { modem.sent().size >= 12 + 256 }
assertArrayEquals(all, modem.sent().copyOfRange(12, 12 + 256))
}
// the client gone: the client off the bridge; not off hook, so no hang-up
waitUntil("released") { serial.client.value == null }
assertEquals(0, hangUps.get())
}
@Test
fun oneClientAtATimeAndTheCallHungUpWhenItGoes() {
val b = bridge()
val first = connect(b)
waitUntil("claimed") { serial.client.value != null }
connect(b).use { second -> readUntil(second, "BUSY") }
signals.value = LineSignals(ready = true, offhook = true, carrier = true)
first.close()
waitUntil("hung up") { hangUps.get() == 1 }
// free again
connect(b).use { waitUntil("claimed again") { serial.client.value != null } }
}
@Test
fun aPasswordFirst() {
val b = bridge(password = "s3cret")
connect(b).use { s ->
readUntil(s, "Password: ")
s.getOutputStream().write("wrong\r".toByteArray())
// (the next prompt with it)
assertTrue(readUntil(s, "\r\nWrong password\r\nPassword: ").isNotEmpty())
assertEquals(null, serial.client.value)
s.getOutputStream().write("s3cret\r".toByteArray())
waitUntil("claimed") { serial.client.value != null }
s.getOutputStream().write("AT\r".toByteArray())
readUntil(s, "OK")
// (the password never reached the modem)
assertFalse(String(modem.sent()).contains("s3cret"))
}
}
@Test
fun telnetDoublesIacAndNegotiates() {
val b = bridge(telnet = true)
connect(b).use { s ->
val i = s.getInputStream()
// the server's offer: WILL BINARY, DO BINARY, WILL ECHO, WILL SGA, DO SGA
val offer = ByteArray(15)
var n = 0
while (n < 15) n += i.read(offer, n, 15 - n)
assertEquals(0xff, offer[0].toInt() and 0xff)
assertEquals(Telnet.ECHO, offer[8].toInt())
// our answers, then data with an IAC doubled in it, and CR NUL as a client not in binary has it
val o = s.getOutputStream()
o.write(byteArrayOf(-1, -3, 0, -1, -5, 0, -1, -3, 1, -1, -3, 3, -1, -5, 3)) // DO BIN, WILL BIN, DO ECHO, DO SGA, WILL SGA
o.write(byteArrayOf('A'.code.toByte(), -1, -1, 'B'.code.toByte()))
waitUntil("the modem got A 0xff B") { modem.sent().size >= 3 }
assertArrayEquals(byteArrayOf('A'.code.toByte(), -1, 'B'.code.toByte()), modem.sent())
// the modem's 0xff, doubled to the client
modem.emit(byteArrayOf(1, -1, 2))
val got = ByteArray(4)
n = 0
while (n < 4) n += i.read(got, n, 4 - n)
assertArrayEquals(byteArrayOf(1, -1, -1, 2), got)
}
}
@Test
fun rfc2217WithPyserial() {
assumeTrue("python3 with pyserial", runCatching {
ProcessBuilder("python3", "-c", "import serial.rfc2217").start().waitFor() == 0
}.getOrDefault(false))
val b = bridge(telnet = true)
val script = File.createTempFile("rfc2217", ".py").apply {
writeText(
"""
import serial, sys, time
s = serial.serial_for_url('rfc2217://127.0.0.1:${b.localPort}', baudrate=9600, timeout=3)
print('baud', s.baudrate, flush=True)
s.write(b'ATI\r')
r = s.read_until(b'OK')
print('reply', r.strip().decode(), flush=True)
# the carrier comes (the test's cue: 'carrier?')
print('carrier?', flush=True)
end = time.time() + 5
while not s.cd and time.time() < end:
time.sleep(0.1)
print('cd', s.cd, 'dsr', s.dsr, flush=True)
s.dtr = False
time.sleep(1)
print('dtr off', flush=True)
s.close()
""".trimIndent(),
)
deleteOnExit()
}
val p = ProcessBuilder("python3", script.path).redirectErrorStream(true).start()
val out = p.inputStream.bufferedReader()
val lines = ArrayList<String>()
while (true) {
val l = out.readLine() ?: break
lines.add(l)
if (l == "carrier?") signals.value = LineSignals(ready = true, offhook = true, carrier = true)
}
assertTrue(p.waitFor(30, TimeUnit.SECONDS))
val all = lines.joinToString("\n")
assertEquals(all, 0, p.exitValue())
assertTrue(all, lines.contains("baud 9600"))
assertTrue(all, lines.contains("reply OK"))
assertTrue(all, lines.contains("cd True dsr True"))
// the speed the client set, kept; DTR dropped while online: the call hung up
assertTrue(all, hangUps.get() >= 1)
assertTrue(String(modem.sent()).startsWith("ATI\r"))
}
}