mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Dial-in internet for callers; back goes Home, then to the background
Dial-in (Settings, Dial-up internet): the phone as an ISP for whoever calls the modem, on SIP or any line. DialIn watches the modem's lines: a RING answered (unless the fax settings answer already), a CONNECT after it the caller's: the DTE taken, a PPP server on the call (10.64.64.2, DNS at 10.64.64.1) with the serial host's NAT on the phone's network. The caller's PPP over (or none started): +++ ATH, the DTE given back; the call dropped: PPP stopped. Home shows the caller online, bytes each way, Hang up. DialInLineTest: two of D-Modem's modems back to back (fax_line), our PPP client as the caller's: CONNECT 33600, the address, DNS and a ping through the phone, the hang-up. Back: from another tab to Home; on Home the task to the background (the modem keeps running), not the activity finished. BackNavigationTest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
8 files changed
+535
-2
No files matched your search
@@ -155,7 +155,20 @@ this line.
|
||||
- **Dial**: the dialing directory: each system's number (or SIP user), the
|
||||
AT commands it needs before ATD, its character set and backspace; one
|
||||
tap starts the modem if it is off and dials.
|
||||
- **Log**: the modem's and SIP's log.
|
||||
- **Log**: the modem's and SIP's log (Copy for all of it).
|
||||
- **Back**: from any other tab back to Home; on Home the app goes to the
|
||||
background (the modem keeps running), as the Home button would.
|
||||
- **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
|
||||
modem's DTE is taken and a PPP server on the call gives the caller
|
||||
10.64.64.2, DNS at 10.64.64.1 and the phone's network through the same
|
||||
NAT the serial bridges' internet host uses. When the caller's PPP ends,
|
||||
or none starts, the app hangs up; when the call drops, PPP stops. Home
|
||||
shows the caller online, with what has gone each way and a Hang up
|
||||
button. Tested over two of D-Modem's modems back to back
|
||||
(`DialInLineTest`: answer, CONNECT 33600, the address, DNS and a ping
|
||||
through the phone, the hang-up).
|
||||
|
||||
The modem runs in a foreground service (`ModemService`) with the CPU and
|
||||
Wi-Fi kept awake for the call's real-time audio. The SIP user agent binds
|
||||
|
||||
@@ -39,6 +39,8 @@ class DModemApp : Application() {
|
||||
Terminal.init(this)
|
||||
// fax calls: their settings and files, and calls that ring answered as faxes when they say so
|
||||
com.neodesktop.dmodem.fax.Fax.init(this)
|
||||
// dial-in: callers given the internet when the settings say so (after the fax's watch: its calls first)
|
||||
com.neodesktop.dmodem.ppp.DialIn.init(this)
|
||||
|
||||
// what the modem sends its DTE, as text, for the status screen's console
|
||||
ModemState.dte.addListener { data, length ->
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ppp
|
||||
|
||||
import android.content.Context
|
||||
import com.neodesktop.dmodem.bridge.Bridges
|
||||
import com.neodesktop.dmodem.fax.Fax
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.settings.FaxSettingsStore
|
||||
import com.neodesktop.dmodem.settings.IspSettingsStore
|
||||
import com.neodesktop.dmodem.terminal.TerminalLink
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import java.net.Inet4Address
|
||||
import java.net.InetAddress
|
||||
import java.net.InetSocketAddress
|
||||
import java.net.Socket
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
/**
|
||||
* Dial-in internet: the phone as an ISP for whoever calls the modem (on
|
||||
* SIP, or any line), as [PppHost] is for a computer on a serial bridge.
|
||||
* With it on, a call that rings is answered; once it's a data call
|
||||
* (CONNECT, after a RING) the modem's DTE is taken, and a PPP server on
|
||||
* the call gives the caller [peer], the DNS at [local] and the phone's
|
||||
* network through its NAT ([NatStack]). The caller's PPP over (or none
|
||||
* started), the call is hung up; the call over, PPP too.
|
||||
*/
|
||||
object DialIn {
|
||||
data class State(
|
||||
val phase: String,
|
||||
/** the modem's CONNECT line */
|
||||
val connect: String = "",
|
||||
/** the caller has its address */
|
||||
val online: Boolean = false,
|
||||
val since: Long = 0,
|
||||
/** why it ended (null while it goes) */
|
||||
val ended: String? = null,
|
||||
) {
|
||||
val running: Boolean get() = ended == null
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow<State?>(null)
|
||||
/** the last dial-in call: going, or how it ended (null: none yet) */
|
||||
val state: StateFlow<State?> = _state.asStateFlow()
|
||||
|
||||
/** callers get the internet (the settings' dial-in) */
|
||||
@Volatile var enabled = false
|
||||
/** answer each call that rings (unless the fax settings answer them already) */
|
||||
@Volatile var answers: () -> Boolean = { true }
|
||||
|
||||
/** the phone's DNS servers, its network's sockets: the app's (the tests' own) */
|
||||
@Volatile var dnsServers: () -> List<InetAddress> = { emptyList() }
|
||||
@Volatile var dnsPort = 53
|
||||
@Volatile var connect: (InetSocketAddress) -> Socket = { a -> Socket().apply { connect(a, 15_000) } }
|
||||
|
||||
val local: Inet4Address = InetAddress.getByName("10.64.64.1") as Inet4Address
|
||||
val peer: Inet4Address = InetAddress.getByName("10.64.64.2") as Inet4Address
|
||||
|
||||
private const val GUARD_MS = 1200L
|
||||
|
||||
/** a call rang since the modem was last idle: a CONNECT now is a caller's */
|
||||
@Volatile private var rang = false
|
||||
@Volatile private var answered = false
|
||||
@Volatile private var call: Call? = null
|
||||
private var watching = false
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
|
||||
private fun log(s: String) = ModemState.log.add("dial-in: $s")
|
||||
|
||||
/** the settings watched, the modem's calls too (the app's start) */
|
||||
fun init(context: Context) {
|
||||
val app = context.applicationContext
|
||||
dnsServers = { Bridges.phoneDns(app) }
|
||||
answers = {
|
||||
// (the fax settings' answering does it, adaptively: fax or data as each call turns out)
|
||||
runCatching { runBlocking { FaxSettingsStore(app).current() } }.getOrNull()?.answer != true
|
||||
}
|
||||
scope.launch { IspSettingsStore(app).settings.collect { enabled = it.dialIn } }
|
||||
watch()
|
||||
}
|
||||
|
||||
/** the modem's text watched for its calls (without the app's context: the tests') */
|
||||
@Synchronized
|
||||
fun watch() {
|
||||
if (watching) return
|
||||
watching = true
|
||||
ModemState.dte.addListener(TerminalLink.Listener { data, n -> modemText(data, n) })
|
||||
scope.launch {
|
||||
ModemState.status.collect { st ->
|
||||
if (!st.offhook) {
|
||||
rang = false
|
||||
answered = false
|
||||
call?.gone("the call ended")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** whether a call may be taken now: nothing else has the modem */
|
||||
private fun free(): Boolean = call == null && !ModemState.dte.claimed && !Internet.running && !Fax.running &&
|
||||
Bridges.serial.client.value == null
|
||||
|
||||
/** the modem's line being read (its results come in pieces) */
|
||||
private val line = StringBuilder()
|
||||
|
||||
private fun modemText(data: ByteArray, n: Int) {
|
||||
if (!enabled) {
|
||||
line.setLength(0)
|
||||
return
|
||||
}
|
||||
for (i in 0 until n) {
|
||||
val ch = (data[i].toInt() and 0xff).toChar()
|
||||
if (ch != '\n') {
|
||||
if (ch != '\r' && line.length < 128) line.append(ch)
|
||||
continue
|
||||
}
|
||||
val l = line.toString().trim()
|
||||
line.setLength(0)
|
||||
if (modemLine(l)) {
|
||||
// (what came after the CONNECT's line: the caller's PPP, perhaps)
|
||||
start(l, data.copyOfRange(i + 1, n))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** a line of the modem's: whether it's a caller's CONNECT to take */
|
||||
private fun modemLine(l: String): Boolean {
|
||||
when {
|
||||
l == "NO CARRIER" -> {
|
||||
rang = false
|
||||
answered = false
|
||||
}
|
||||
l == "RING" -> {
|
||||
rang = true
|
||||
if (!answered && free() && answers()) {
|
||||
answered = true
|
||||
log("a call rings: answered")
|
||||
Thread { ModemState.answer() }.start()
|
||||
}
|
||||
}
|
||||
// (a fax call's CONNECTs are the fax receiver's: it has the modem from its FAX)
|
||||
l == "FAX" -> rang = false
|
||||
l.startsWith("CONNECT") -> return rang && free()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/** the call's PPP server started, the DTE taken (what came after the CONNECT its first) */
|
||||
private fun start(connectLine: String, first: ByteArray) {
|
||||
val c = Call(connectLine)
|
||||
if (!c.begin(first)) return
|
||||
log("$connectLine: PPP for the caller")
|
||||
}
|
||||
|
||||
/** a call rang (the tests' line has no ring signal: its modems answer at once) */
|
||||
internal fun rings() {
|
||||
rang = true
|
||||
}
|
||||
|
||||
/** the caller's link given up (the app's Disconnect): the call hung up */
|
||||
fun disconnect() {
|
||||
call?.end("disconnected")
|
||||
}
|
||||
|
||||
/** the caller's bytes so far, each way (in, out) */
|
||||
fun bytes(): Pair<Long, Long> = call?.ppp?.let { it.bytesIn to it.bytesOut } ?: (0L to 0L)
|
||||
|
||||
fun dismiss() {
|
||||
if (call == null) _state.value = null
|
||||
}
|
||||
|
||||
private class Call(val connectLine: String) {
|
||||
val over = AtomicBoolean(false)
|
||||
lateinit var listener: TerminalLink.Listener
|
||||
var ppp: Ppp? = null
|
||||
var nat: NatStack? = null
|
||||
|
||||
fun begin(first: ByteArray): Boolean {
|
||||
val hub = ModemState.dte
|
||||
listener = TerminalLink.Listener { d, n -> ppp?.input(d, 0, n) }
|
||||
if (!hub.claim(listener)) return false
|
||||
call = this
|
||||
rang = false
|
||||
lateinit var n: NatStack
|
||||
val p = Ppp(
|
||||
send = { b -> hub.writeAs(listener, b) },
|
||||
events = object : Ppp.Events {
|
||||
override fun up(config: Ppp.IpConfig) {
|
||||
n.mss = config.mtu - 40
|
||||
DialIn.log("the caller is online: ${peer.hostAddress}")
|
||||
_state.value = State("Online", connectLine, online = true, since = System.currentTimeMillis())
|
||||
}
|
||||
override fun ip(packet: ByteArray) = n.input(packet)
|
||||
override fun down(reason: String) {
|
||||
// (off PPP's thread: the hang-up waits out the guard times)
|
||||
Thread { end(reason) }.start()
|
||||
}
|
||||
override fun log(line: String) = DialIn.log("ppp: $line")
|
||||
},
|
||||
server = Ppp.Server(local, peer, local),
|
||||
)
|
||||
n = NatStack({ pk -> p.sendIp(pk) }, local, dnsServers, connect, ::log, dnsPort)
|
||||
ppp = p
|
||||
nat = n
|
||||
_state.value = State("Starting PPP", connectLine)
|
||||
p.start()
|
||||
if (first.isNotEmpty()) p.input(first, 0, first.size)
|
||||
return true
|
||||
}
|
||||
|
||||
/** the link over: the call hung up (+++, ATH), the DTE given back */
|
||||
fun end(why: String) {
|
||||
if (!over.compareAndSet(false, true)) return
|
||||
ppp?.stop(why)
|
||||
nat?.close()
|
||||
val hub = ModemState.dte
|
||||
Thread.sleep(GUARD_MS)
|
||||
hub.writeAs(listener, "+++".toByteArray())
|
||||
Thread.sleep(GUARD_MS)
|
||||
hub.writeAs(listener, "ATH\r".toByteArray())
|
||||
finish(why)
|
||||
}
|
||||
|
||||
/** the call already over (the caller hung up): PPP stopped, the DTE given back */
|
||||
fun gone(why: String) {
|
||||
if (!over.compareAndSet(false, true)) return
|
||||
ppp?.stop(why)
|
||||
nat?.close()
|
||||
finish(why)
|
||||
}
|
||||
|
||||
private fun finish(why: String) {
|
||||
log("over: $why")
|
||||
ModemState.dte.release(listener)
|
||||
call = null
|
||||
answered = false
|
||||
_state.value = (_state.value ?: State("")).copy(phase = "", online = false, ended = why)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import android.content.Context
|
||||
import androidx.datastore.core.DataStore
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.booleanPreferencesKey
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
@@ -20,6 +21,8 @@ data class IspSettings(
|
||||
val initCommands: String = "",
|
||||
/** a login script for after the CONNECT, before PPP (chat's: "ogin: \\U assword: \\P"); empty: none */
|
||||
val script: String = "",
|
||||
/** dial-in: callers to the modem get the internet through the phone (DialIn) */
|
||||
val dialIn: Boolean = false,
|
||||
) {
|
||||
val complete: Boolean get() = number.isNotBlank()
|
||||
}
|
||||
@@ -33,10 +36,11 @@ class IspSettingsStore(private val context: Context) {
|
||||
val password = stringPreferencesKey("password")
|
||||
val init = stringPreferencesKey("init")
|
||||
val script = stringPreferencesKey("script")
|
||||
val dialIn = booleanPreferencesKey("dial_in")
|
||||
}
|
||||
|
||||
val settings: Flow<IspSettings> = context.ispStore.data.map { p ->
|
||||
IspSettings(p[K.number] ?: "", p[K.user] ?: "", p[K.password] ?: "", p[K.init] ?: "", p[K.script] ?: "")
|
||||
IspSettings(p[K.number] ?: "", p[K.user] ?: "", p[K.password] ?: "", p[K.init] ?: "", p[K.script] ?: "", p[K.dialIn] ?: false)
|
||||
}
|
||||
|
||||
suspend fun current(): IspSettings = settings.first()
|
||||
@@ -48,6 +52,7 @@ class IspSettingsStore(private val context: Context) {
|
||||
p[K.password] = s.password
|
||||
p[K.init] = s.initCommands.trim()
|
||||
p[K.script] = s.script.trim()
|
||||
p[K.dialIn] = s.dialIn
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.ppp.DialIn
|
||||
import com.neodesktop.dmodem.ppp.Internet
|
||||
import com.neodesktop.dmodem.ppp.PppVpnService
|
||||
import com.neodesktop.dmodem.settings.IspSettings
|
||||
@@ -64,8 +65,10 @@ fun InternetCard(onSetUp: () -> Unit) {
|
||||
if (r.resultCode == Activity.RESULT_OK) dial() else Toast.makeText(context, "The VPN wasn't allowed", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
val dialIn by DialIn.state.collectAsStateWithLifecycle()
|
||||
Card(Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
dialIn?.let { d -> DialInRows(d) }
|
||||
val st = state
|
||||
when {
|
||||
st == null || !st.running -> {
|
||||
@@ -115,6 +118,31 @@ fun InternetCard(onSetUp: () -> Unit) {
|
||||
}
|
||||
}
|
||||
|
||||
/** a caller on the internet through the phone (DialIn), or how its call ended */
|
||||
@Composable
|
||||
private fun DialInRows(d: DialIn.State) {
|
||||
if (d.running) {
|
||||
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
|
||||
LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
|
||||
Text("Dial-in: " + if (d.online) "a caller is online" else d.phase, style = MaterialTheme.typography.titleSmall)
|
||||
val (bIn, bOut) = remember(now) { DialIn.bytes() }
|
||||
if (d.online) {
|
||||
val secs = ((now - d.since) / 1000).coerceAtLeast(0)
|
||||
Text(
|
||||
"${DialIn.peer.hostAddress} · ${d.connect.removePrefix("CONNECT").trim().ifEmpty { "connected" }} · " +
|
||||
"%d:%02d · ↓ ${size(bIn)} ↑ ${size(bOut)}".format(secs / 60, secs % 60),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = { Thread { DialIn.disconnect() }.start() }) { Text("Hang up") }
|
||||
} else {
|
||||
Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
|
||||
Text("Dial-in call over: ${d.ended}", Modifier.weight(1f), style = MaterialTheme.typography.bodySmall)
|
||||
TextButton(onClick = { DialIn.dismiss() }) { Text("OK") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun size(n: Long) = when {
|
||||
n < 1024 -> "$n B"
|
||||
n < 1024 * 1024 -> "%.1f KB".format(n / 1024.0)
|
||||
@@ -160,6 +188,17 @@ fun IspSettingsSection() {
|
||||
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text("Dial-in", style = MaterialTheme.typography.titleSmall)
|
||||
Row(Modifier.fillMaxWidth(), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
|
||||
Text("Callers get the internet through this phone", Modifier.weight(1f))
|
||||
androidx.compose.material3.Switch(checked = s.dialIn, onCheckedChange = { s = s.copy(dialIn = it) })
|
||||
}
|
||||
Text(
|
||||
"The phone as an ISP for whoever calls the modem: a call that rings is answered, and once it connects " +
|
||||
"the caller's dialer gets PPP (no login), the address ${DialIn.peer.hostAddress} and the phone's " +
|
||||
"network. Calls in need the line to take them (on SIP: \"Take calls\", registered).",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Button(onClick = {
|
||||
scope.launch { store.save(s) }
|
||||
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show()
|
||||
|
||||
@@ -114,6 +114,9 @@ class MainActivity : ComponentActivity() {
|
||||
offerFax = !com.neodesktop.dmodem.modem.ModemState.adaptiveAnswer,
|
||||
)
|
||||
}
|
||||
// back: Home from another tab; on Home the app to the background, as Home's button would
|
||||
// (the modem going on), not closed. (Screens' own back, and full screen's below, come first.)
|
||||
BackHandler { if (tab != TAB_MODEM) tab = TAB_MODEM else moveTaskToBack(true) }
|
||||
BackHandler(enabled = full) { fullscreen = false }
|
||||
|
||||
PromptHost()
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ppp
|
||||
|
||||
import com.neodesktop.dmodem.fax.Class1
|
||||
import com.neodesktop.dmodem.modem.ModemState
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Assume.assumeTrue
|
||||
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.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.net.DatagramPacket
|
||||
import java.net.DatagramSocket
|
||||
import java.net.InetAddress
|
||||
import java.util.concurrent.ArrayBlockingQueue
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Dial-in internet ([DialIn]) on a modem call: the app's modem is modemA
|
||||
* of native-test's fax_line (two of D-Modem's modems back to back, paced
|
||||
* as a line), the caller's modemB with our PPP client as its dialer's. The
|
||||
* caller dials, the app answers; at the CONNECT the app's PPP server gives
|
||||
* the caller its address; DNS to the gateway and a ping through it; the
|
||||
* caller's PPP over, the app hangs up and has its DTE back.
|
||||
*/
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [28])
|
||||
class DialInLineTest {
|
||||
private var line: Process? = null
|
||||
private val log = CopyOnWriteArrayList<String>()
|
||||
private lateinit var a: String
|
||||
private lateinit var b: String
|
||||
private val closers = ArrayList<() -> Unit>()
|
||||
|
||||
private fun faxLine(): File? = listOfNotNull(System.getenv("DMODEM_FAX_LINE"), "../build-host/fax_line", "build-host/fax_line")
|
||||
.map { File(it) }.firstOrNull { it.canExecute() }
|
||||
|
||||
@Before
|
||||
fun setUp() {
|
||||
val fl = faxLine()
|
||||
assumeTrue("fax_line isn't built (native-test)", fl != null)
|
||||
val p = ProcessBuilder(fl!!.path).redirectErrorStream(true).start()
|
||||
line = p
|
||||
Thread { p.inputStream.bufferedReader().forEachLine { log.add(it) } }.apply { isDaemon = true; start() }
|
||||
val end = System.currentTimeMillis() + 10_000
|
||||
while (System.currentTimeMillis() < end && log.none { it.startsWith("created modemB: ") }) Thread.sleep(20)
|
||||
a = log.first { it.startsWith("created modemA: ") }.substringAfter(": ")
|
||||
b = log.first { it.startsWith("created modemB: ") }.substringAfter(": ")
|
||||
ProcessBuilder("stty", "-F", a, "raw", "-echo").start().waitFor()
|
||||
ModemState.dte.attach(FileInputStream(a), FileOutputStream(a))
|
||||
ModemState.setRun(ModemState.Run.RUNNING)
|
||||
}
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
File("build/dial-in-log.txt").writeText((ModemState.log.flow.value + listOf("----") + log).joinToString("\n"))
|
||||
val ctx = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
kotlinx.coroutines.runBlocking { com.neodesktop.dmodem.settings.IspSettingsStore(ctx).save(com.neodesktop.dmodem.settings.IspSettings()) }
|
||||
closers.forEach { runCatching { it() } }
|
||||
ModemState.dte.detach()
|
||||
ModemState.setRun(ModemState.Run.STOPPED)
|
||||
line?.destroy()
|
||||
line?.waitFor(5, TimeUnit.SECONDS)
|
||||
}
|
||||
|
||||
private fun dump() = (ModemState.log.flow.value.takeLast(40) + log.takeLast(40)).joinToString("\n")
|
||||
|
||||
@Test
|
||||
fun aCallerGetsTheInternet() {
|
||||
// the phone's "DNS server" (its answer: the query back with "A")
|
||||
val dns = DatagramSocket(0, InetAddress.getLoopbackAddress())
|
||||
closers.add { dns.close() }
|
||||
Thread {
|
||||
val d = DatagramPacket(ByteArray(512), 512)
|
||||
dns.receive(d)
|
||||
dns.send(DatagramPacket(d.data.copyOf(d.length) + "A".toByteArray(), d.length + 1, d.socketAddress))
|
||||
}.apply { isDaemon = true; start() }
|
||||
DialIn.dnsServers = { listOf(InetAddress.getLoopbackAddress()) }
|
||||
DialIn.dnsPort = dns.localPort
|
||||
// on in the settings, as the app has it (its DialIn watching them since the app started)
|
||||
val ctx = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()
|
||||
kotlinx.coroutines.runBlocking { com.neodesktop.dmodem.settings.IspSettingsStore(ctx).save(com.neodesktop.dmodem.settings.IspSettings(dialIn = true)) }
|
||||
val on = System.currentTimeMillis() + 5000
|
||||
while (!DialIn.enabled && System.currentTimeMillis() < on) Thread.sleep(20)
|
||||
assertTrue(DialIn.enabled)
|
||||
DialIn.watch()
|
||||
|
||||
// the caller's modem, then its PPP once the call is up
|
||||
ProcessBuilder("stty", "-F", b, "raw", "-echo").start().waitFor()
|
||||
val input = FileInputStream(b)
|
||||
val output = FileOutputStream(b)
|
||||
closers.add { input.close(); output.close() }
|
||||
val io = TransferIo { bytes -> output.write(bytes); output.flush() }
|
||||
val pppRef = java.util.concurrent.atomic.AtomicReference<Ppp?>(null)
|
||||
Thread {
|
||||
val buf = ByteArray(4096)
|
||||
while (true) {
|
||||
val n = try { input.read(buf) } catch (_: Exception) { -1 }
|
||||
if (n < 0) break
|
||||
pppRef.get()?.input(buf, 0, n) ?: io.feed(buf, 0, n)
|
||||
}
|
||||
}.apply { isDaemon = true; start() }
|
||||
val c = Class1(io) { log.add("caller: $it") }
|
||||
assertEquals("OK", c.command("E0"))
|
||||
// (the line has no dial tone: the caller dials blind)
|
||||
assertEquals("OK", c.command("X3"))
|
||||
|
||||
// the caller dials; the app's modem rings (the line has no ring signal: said so) and answers
|
||||
val dialled = ArrayBlockingQueue<String>(1)
|
||||
Thread { dialled.add(c.command("D5551000", 60_000) ?: "none") }.apply { isDaemon = true; start() }
|
||||
assertTrue(dump(), waitLog("modemB: run cmd: ATD5551000"))
|
||||
DialIn.rings()
|
||||
assertTrue(ModemState.answer())
|
||||
val r = dialled.poll(60, TimeUnit.SECONDS)
|
||||
assertTrue("$r\n${dump()}", r.orEmpty().startsWith("CONNECT"))
|
||||
|
||||
// the caller's PPP: an address from the app
|
||||
val up = ArrayBlockingQueue<Ppp.IpConfig>(1)
|
||||
val packets = LinkedBlockingQueue<ByteArray>()
|
||||
val p = Ppp({ f -> output.write(f); output.flush() }, events = object : Ppp.Events {
|
||||
override fun up(config: Ppp.IpConfig) { up.add(config) }
|
||||
override fun ip(packet: ByteArray) { packets.add(packet) }
|
||||
override fun down(reason: String) {}
|
||||
}, retryMs = 1000)
|
||||
pppRef.set(p)
|
||||
p.start()
|
||||
val cfg = up.poll(60, TimeUnit.SECONDS) ?: throw AssertionError("no link:\n${dump()}")
|
||||
assertEquals("10.64.64.2", cfg.address.hostAddress)
|
||||
assertEquals(listOf("10.64.64.1"), cfg.dns.map { it.hostAddress })
|
||||
val until = System.currentTimeMillis() + 5000
|
||||
while (DialIn.state.value?.online != true && System.currentTimeMillis() < until) Thread.sleep(20)
|
||||
assertTrue(DialIn.state.value.toString(), DialIn.state.value?.online == true)
|
||||
assertTrue(ModemState.dte.claimed)
|
||||
|
||||
// DNS to the gateway: the phone's server's answer; a ping to the gateway
|
||||
val me = byteArrayOf(10, 64, 64, 2)
|
||||
val gw = byteArrayOf(10, 64, 64, 1)
|
||||
p.sendIp(Ip.udp(me, gw, 5353, 53, "query".toByteArray()))
|
||||
val answer = packets.poll(20, TimeUnit.SECONDS) ?: throw AssertionError("no DNS answer:\n${dump()}")
|
||||
assertEquals("queryA", String(Ip.udpPayload(answer)))
|
||||
assertArrayEquals(gw, answer.copyOfRange(12, 16))
|
||||
p.sendIp(Ip.icmp(me, gw, 8, 0, byteArrayOf(0, 1, 0, 1) + "ping".toByteArray()))
|
||||
val pong = packets.poll(20, TimeUnit.SECONDS) ?: throw AssertionError("no pong:\n${dump()}")
|
||||
assertEquals(0, pong[20].toInt())
|
||||
assertEquals("ping", String(pong, 28, 4))
|
||||
|
||||
// the caller's PPP over: the app hangs up, its DTE free again
|
||||
p.stop("the caller is done")
|
||||
val end = System.currentTimeMillis() + 20_000
|
||||
while (DialIn.state.value?.running == true && System.currentTimeMillis() < end) Thread.sleep(100)
|
||||
assertTrue(DialIn.state.value.toString(), DialIn.state.value?.ended != null)
|
||||
assertTrue(!ModemState.dte.claimed)
|
||||
assertTrue(dump(), waitLog("modemA: run cmd: ATH"))
|
||||
}
|
||||
|
||||
private fun waitLog(what: String, secs: Int = 30): Boolean {
|
||||
val end = System.currentTimeMillis() + secs * 1000L
|
||||
while (System.currentTimeMillis() < end) {
|
||||
if (log.any { it.contains(what) }) return true
|
||||
Thread.sleep(5)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ui
|
||||
|
||||
import androidx.compose.ui.test.junit4.createAndroidComposeRule
|
||||
import androidx.compose.ui.test.onNodeWithText
|
||||
import androidx.compose.ui.test.performClick
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
/** Back: to Home from the other tabs; on Home, the app to the background (not closed). */
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [35])
|
||||
class BackNavigationTest {
|
||||
@get:Rule
|
||||
val compose = createAndroidComposeRule<MainActivity>()
|
||||
|
||||
private fun back() {
|
||||
compose.activityRule.scenario.onActivity { it.onBackPressedDispatcher.onBackPressed() }
|
||||
compose.waitForIdle()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backGoesHomeThenToTheBackground() {
|
||||
// (Home: no SIP account yet)
|
||||
compose.onNodeWithText("Set up SIP").assertExists()
|
||||
for (tab in listOf("Terminal", "Dial", "Settings", "Log")) {
|
||||
compose.onNode(
|
||||
androidx.compose.ui.test.hasText(tab) and androidx.compose.ui.test.SemanticsMatcher.expectValue(
|
||||
androidx.compose.ui.semantics.SemanticsProperties.Role, androidx.compose.ui.semantics.Role.Tab,
|
||||
),
|
||||
).performClick()
|
||||
compose.waitForIdle()
|
||||
compose.onNodeWithText("Set up SIP").assertDoesNotExist()
|
||||
back()
|
||||
compose.onNodeWithText("Set up SIP").assertExists()
|
||||
}
|
||||
// on Home: the task to the back, the activity still there
|
||||
back()
|
||||
compose.activityRule.scenario.onActivity { a ->
|
||||
assertFalse(a.isFinishing)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user