From 05143cb764ffcd165cbbf3fd0306839cb965042a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 19 Oct 2026 01:32:58 +0000 Subject: [PATCH] Adaptive answer: a call answered is a fax or data by what it sends D-Modem-RE up to 24e48f3: its adaptive answer (AT+FAA=1: the caller's CNG, a V.8 fax call or T.38 from the far end make it FAX, +FCLASS=1 and a class 1 answerer; a modem's handshake makes it DATA, then CONNECT) and its CNG detector widened to T.30's 1100 Hz +-38 Hz. The app turns it on as the modem starts (Settings: "Fax or data, as each call turns out", on by default). When the modem says FAX, the fax receiver takes the DTE at once, on its reader's thread before the CONNECT goes to the terminal, with no set-up commands (the modem is waiting for our first frames), and receives the pages as an answered fax always did. A data call stays the terminal's. With it on, the incoming call popup and notification offer Answer and Ignore (no "Answer as fax"), and the fax settings' auto-answer answers every call adaptively. Tests: FaxAppTest.aFaxMachinesCallAnsweredAdaptively (a fax machine dials, a plain ATA, the page received and saved), aDataCallAnsweredAdaptively (DATA, CONNECT, no fax). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs --- README.md | 12 ++- .../java/com/neodesktop/dmodem/fax/Fax.kt | 79 +++++++++++++++---- .../neodesktop/dmodem/modem/ModemService.kt | 10 ++- .../com/neodesktop/dmodem/modem/ModemState.kt | 3 + .../dmodem/settings/ModemSettings.kt | 8 ++ .../java/com/neodesktop/dmodem/ui/FaxUi.kt | 14 +++- .../neodesktop/dmodem/ui/IncomingCallUi.kt | 13 ++- .../com/neodesktop/dmodem/ui/MainActivity.kt | 1 + .../neodesktop/dmodem/ui/SettingsScreen.kt | 6 ++ .../com/neodesktop/dmodem/fax/FaxAppTest.kt | 65 +++++++++++++++ external/d-modem-re | 2 +- 11 files changed, 184 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index c178006..4bdf48c 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,12 @@ challenge and response: the PIN never goes over the connection). Class 1 fax (T.30, MH coding, V.27ter, V.29 and V.17 up to 14400 bit/s), sending PDFs and images and receiving into PDFs, on the SIP line (audio, or T.38 when the far end asks for it) and the line to another phone. +A call answered is a fax or a data call by what the caller sends +(D-Modem-RE's adaptive answer, `AT+FAA=1`, on unless the settings turn +it off): a fax machine's CNG, a V.8 fax call or T.38 from the far end +and the modem says FAX, and the app's fax receiver takes the call by +itself; a modem's handshake and it says DATA, then its CONNECT, for the +terminal and the bridges. Error correction mode (T.30 Annex A) when the other machine has it: the page in numbered HDLC frames, those a noisy line spoils sent again. Tested against efax, against D-Modem-RE's own T.30 machine (native-test's @@ -92,8 +98,10 @@ too, so the computer dropping DTR hangs up there as well. - **A call ringing in** (SIP, the other phone, a mobile call): the phone's incoming call notification (heads-up, over the lock screen, the ringtone) and a popup over the app, with who's calling when the - line says (the other phone's name): Answer (the terminal, ATA), Answer - as fax, or Ignore (it rings on, out of sight). Gone when the modem + line says (the other phone's name): Answer (ATA: a fax machine's call + goes to the fax receiver by itself, a modem's to the terminal), or + Ignore (it rings on, out of sight); Answer as fax too when adaptive + answer is off. Gone when the modem answers (here, a computer on a bridge, S0) or the caller gives up. - **Settings**: the SIP account (or paste `user:password@host`, as dmodemd's `SIP_LOGIN`), taking incoming calls, T.38, the AT commands diff --git a/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt b/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt index 4f39d84..2b8114b 100644 --- a/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt +++ b/app/src/main/java/com/neodesktop/dmodem/fax/Fax.kt @@ -132,21 +132,44 @@ object Fax { update(FaxProgress("Answering")) val r = c.command("A", 30_000) if (r != "CONNECT") throw FaxException(if (r == null) "no fax answered" else "no fax: $r") - val got = ArrayList() - val p = try { - T30.receive(c, s.ident, rates, { update(it) }, ecm = s.ecm) { pg, _ -> got.add(pg) } - } catch (e: IOException) { - // the pages that came are kept - if (got.isEmpty()) throw e - FaxProgress("Received part", pages = got.size) - } - val name = save(app, got) - record(app, false, "", p, "", name) - p to name + receive(app, c, s) } return null } + /** + * a call the modem answered and found to be a fax machine's (adaptive + * answer, AT+FAA=1: its FAX, +FCLASS=1, then CONNECT as after +FTH=3, + * for our first frames): the DTE taken now (on its reader's thread, + * before the CONNECT goes elsewhere), [first] what came after FAX, and + * the pages received + */ + fun answeredAdaptively(first: ByteArray) { + if (running) return + val app = contextOrNull() ?: return + start(sending = false, number = "", setUp = false, first = first) { c, s -> + update(FaxProgress("Answering")) + val r = c.result(10_000) + if (r != "CONNECT") throw FaxException(if (r == null) "the fax didn't start" else "no fax: $r") + receive(app, c, s) + } + } + + /** the pages received (on a call answered, the modem sending our frames), saved as a PDF and recorded */ + private fun receive(app: Context, c: Class1, s: FaxSettings): Pair { + val got = ArrayList() + val p = try { + T30.receive(c, s.ident, rates, { update(it) }, ecm = s.ecm) { pg, _ -> got.add(pg) } + } catch (e: IOException) { + // the pages that came are kept + if (got.isEmpty()) throw e + FaxProgress("Received part", pages = got.size) + } + val name = save(app, got) + record(app, false, "", p, "", name) + return p to name + } + /** the call stopped (hung up) */ fun cancel() { io?.cancel("cancelled") @@ -177,7 +200,15 @@ object Fax { } /** a call on the modem, its DTE ours while it lasts: [body] given the class 1 modem, set up */ - private fun start(sending: Boolean, number: String, body: (Class1, FaxSettings) -> Pair) { + private fun start( + sending: Boolean, + number: String, + /** the modem set up for fax first (false: it's in class 1 already, answering) */ + setUp: Boolean = true, + /** what the modem said before the line was ours */ + first: ByteArray? = null, + body: (Class1, FaxSettings) -> Pair, + ) { val hub = ModemState.dte lateinit var listener: TerminalLink.Listener val line = TransferIo { b -> if (!hub.writeAs(listener, b)) throw IOException("the modem has gone") } @@ -187,6 +218,7 @@ object Fax { return } io = line + first?.let { if (it.isNotEmpty()) line.feed(it, 0, it.size) } _state.value = State(sending, FaxProgress("Starting"), number = number) thread = Thread({ var result = "" @@ -196,8 +228,13 @@ object Fax { try { val s = runBlocking { FaxSettingsStore(contextOrThrow()).current() } // (X3: a SIP line has no dial tone to wait for) - if (c.command("E0V1X3") != "OK" || c.command("+FCLASS=1") != "OK") throw FaxException("the modem has no fax mode") - rates = T30.modemRates(c, s.maxBps) + if (setUp) { + if (c.command("E0V1X3") != "OK" || c.command("+FCLASS=1") != "OK") throw FaxException("the modem has no fax mode") + rates = T30.modemRates(c, s.maxBps) + } else { + // (no commands now: the modem's waiting for our frames. D-Modem-RE has every rate) + rates = T30.RATES.filter { it.bps <= s.maxBps } + } val (p, f) = body(c, s) last = p file = f @@ -234,16 +271,26 @@ object Fax { private fun contextOrThrow(): Context = app ?: throw FaxException("not set up") private fun contextOrNull(): Context? = app + /** adaptive answer's word for a fax call (ATV1), its line alone */ + private val FAX_RESULT = Regex("(?:^|[\\r\\n])FAX\\r\\n") + /** the application's context; ringing calls watched for (answered as faxes when the settings say so) */ fun init(context: Context) { app = context.applicationContext if (watching) return watching = true ModemState.dte.addListener(TerminalLink.Listener { data, n -> - if (String(data, 0, n, Charsets.ISO_8859_1).contains("RING") && !running) { + val text = String(data, 0, n, Charsets.ISO_8859_1) + // a call answered adaptively that's a fax machine's: ours, before its CONNECT goes to the terminal + FAX_RESULT.find(text)?.let { m -> + if (!running) answeredAdaptively(data.copyOfRange(m.range.last + 1, n)) + return@Listener + } + if (text.contains("RING") && !running) { val a = app ?: return@Listener val s = runCatching { runBlocking { FaxSettingsStore(a).current() } }.getOrNull() ?: return@Listener - if (s.answer) Thread { answer(a) }.start() + // (every call answered: adaptively, fax or data as it turns out; else as a fax) + if (s.answer) Thread { if (ModemState.adaptiveAnswer) ModemState.answer() else answer(a) }.start() } }) } diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt index 7304381..242fc10 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt @@ -248,6 +248,9 @@ class ModemService : Service() { if (settings.peer && !settings.noLine) com.neodesktop.dmodem.peer.Peers.start(this, settings, ::log) val start = settings.startCommands() if (start.isNotBlank()) ModemState.dte.write(start + "\r") + // (each call answered as fax or data by what it turns out to be: FAX, then the fax receiver) + ModemState.adaptiveAnswer = settings.adaptiveAnswer + if (settings.adaptiveAnswer) ModemState.dte.write("AT+FAA=1\r") return true } @@ -515,7 +518,7 @@ class ModemService : Service() { ) val who = c.from ?: callerOfLine() val person = androidx.core.app.Person.Builder().setName(who).setImportant(true).build() - val n = NotificationCompat.Builder(this, DModemApp.CHANNEL_CALLS) + val b = NotificationCompat.Builder(this, DModemApp.CHANNEL_CALLS) .setSmallIcon(R.drawable.ic_modem) .setStyle(NotificationCompat.CallStyle.forIncomingCall(person, ignore, answer)) .setContentTitle(who) @@ -526,8 +529,9 @@ class ModemService : Service() { .setOnlyAlertOnce(true) .setContentIntent(open) .setFullScreenIntent(open, true) - .addAction(0, "Answer as fax", fax) - .build() + // (with adaptive answer, Answer takes a fax machine's call to the fax receiver by itself) + if (!settings.adaptiveAnswer) b.addAction(0, "Answer as fax", fax) + val n = b.build() try { nm.notify(CALL_NOTIFICATION_ID, n) } catch (e: SecurityException) { diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt index dbbd93b..e6bd982 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemState.kt @@ -42,6 +42,9 @@ object ModemState { val tones = CallTones() val progress = CallProgress(tones) + /** calls answered as fax or data alike (AT+FAA=1): no "answer as fax" to offer */ + @Volatile var adaptiveAnswer = true + /** a call ringing in, for the notification and the popup */ val incoming = IncomingCalls() diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt index e5ea865..2608452 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/ModemSettings.kt @@ -47,6 +47,11 @@ data class ModemSettings( val speaker: Boolean = true, /** the country's call progress tones (dial, ringing, busy, congestion) where the line has none of its own */ val callTones: Boolean = true, + /** + * calls answered as fax or data by what they turn out to be (D-Modem-RE's adaptive answer, AT+FAA=1): + * a fax machine's to the fax receiver, a modem's to the terminal + */ + val adaptiveAnswer: Boolean = true, /** * the modulation on mobile calls (+MS): V_CVM (V.cvm, made for speech codecs: about 1200 bit/s * through AMR 12.2, to another D-Modem; V.22 or V.21 to other modems), V21 (300 bit/s), V22, V22B @@ -123,6 +128,7 @@ class SettingsStore(private val context: Context) { val peerPin = stringPreferencesKey("peer_pin") val speaker = booleanPreferencesKey("speaker") val callTones = booleanPreferencesKey("callTones") + val adaptiveAnswer = booleanPreferencesKey("adaptiveAnswer") val cellSpeed = stringPreferencesKey("cell_speed") } @@ -146,6 +152,7 @@ class SettingsStore(private val context: Context) { peerPin = p[Keys.peerPin] ?: d.peerPin, speaker = p[Keys.speaker] ?: d.speaker, callTones = p[Keys.callTones] ?: d.callTones, + adaptiveAnswer = p[Keys.adaptiveAnswer] ?: d.adaptiveAnswer, cellSpeed = p[Keys.cellSpeed] ?: d.cellSpeed, ) } @@ -171,6 +178,7 @@ class SettingsStore(private val context: Context) { p[Keys.peerPin] = s.peerPin.trim() p[Keys.speaker] = s.speaker p[Keys.callTones] = s.callTones + p[Keys.adaptiveAnswer] = s.adaptiveAnswer p[Keys.cellSpeed] = s.cellSpeed } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt b/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt index 56ef18f..44f0ae1 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/FaxUi.kt @@ -65,9 +65,12 @@ fun FaxSection() { state?.let { st -> FaxCallCard(st) } Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Button(onClick = { sendDialog = true }, enabled = on && state?.running != true) { Text("Send a fax…") } - OutlinedButton(onClick = { - Fax.answer(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } - }, enabled = on && state?.running != true) { Text("Answer as fax") } + // (with adaptive answer, a call answered is a fax by itself when a fax machine calls) + if (!ModemState.adaptiveAnswer) { + OutlinedButton(onClick = { + Fax.answer(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } + }, enabled = on && state?.running != true) { Text("Answer as fax") } + } } if (!on) Text("The modem is off: start it to fax", style = MaterialTheme.typography.bodySmall) for (r in history.sortedByDescending { it.time }.take(3)) FaxRow(r) @@ -201,7 +204,10 @@ fun FaxSettingsSection() { keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), modifier = Modifier.fillMaxWidth(), ) Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { - Text("Answer calls that ring as faxes", Modifier.weight(1f)) + Text( + if (ModemState.adaptiveAnswer) "Answer every call that rings (a fax machine's as a fax)" else "Answer calls that ring as faxes", + Modifier.weight(1f), + ) Switch(checked = s.answer, onCheckedChange = { v -> scope.launch { store.update { it.copy(answer = v) } } }) } Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/IncomingCallUi.kt b/app/src/main/java/com/neodesktop/dmodem/ui/IncomingCallUi.kt index 5dfbb43..57f1cf2 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/IncomingCallUi.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/IncomingCallUi.kt @@ -22,8 +22,10 @@ import com.neodesktop.dmodem.modem.IncomingCalls /** * A call ringing in, over whatever the app shows: who's calling (when the - * line says), and what to do: answer it (the terminal, ATA), answer it as a - * fax, or let it ring (out of sight until it's over). + * line says), and what to do: answer it (the terminal, ATA: with adaptive + * answer a fax machine's call goes to the fax receiver by itself), answer + * it as a fax (without adaptive answer), or let it ring (out of sight + * until it's over). */ @Composable fun IncomingCallDialog( @@ -33,6 +35,8 @@ fun IncomingCallDialog( onAnswer: () -> Unit, onFax: () -> Unit, onIgnore: () -> Unit, + /** answer as fax offered (adaptive answer off: a plain answer is a data call's) */ + offerFax: Boolean = true, ) { AlertDialog( onDismissRequest = onIgnore, @@ -45,12 +49,15 @@ fun IncomingCallDialog( "Calling the modem" + if (call.rings > 1) " (${call.rings} rings)" else "", style = MaterialTheme.typography.bodyMedium, ) + if (!offerFax) { + Text("A fax machine's call goes to the fax receiver by itself", style = MaterialTheme.typography.bodySmall) + } } }, confirmButton = { Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(4.dp)) { Button(onClick = onAnswer, Modifier.fillMaxWidth()) { Text("Answer") } - OutlinedButton(onClick = onFax, Modifier.fillMaxWidth()) { Text("Answer as fax") } + if (offerFax) OutlinedButton(onClick = onFax, Modifier.fillMaxWidth()) { Text("Answer as fax") } TextButton( onClick = onIgnore, Modifier.fillMaxWidth(), diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt b/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt index 006b1b1..cf8b6bd 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt @@ -111,6 +111,7 @@ class MainActivity : ComponentActivity() { }, onFax = { answerAsFax() }, onIgnore = { com.neodesktop.dmodem.modem.ModemState.incoming.ignore() }, + offerFax = !com.neodesktop.dmodem.modem.ModemState.adaptiveAnswer, ) } BackHandler(enabled = full) { fullscreen = false } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt index 9738219..637274a 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt @@ -98,6 +98,12 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = { Text("Modem", style = MaterialTheme.typography.titleMedium) Toggle("Speaker: hear the dialling and the handshake", s.speaker) { s = s.copy(speaker = it) } + Toggle("Fax or data, as each call turns out", s.adaptiveAnswer) { s = s.copy(adaptiveAnswer = it) } + Text( + "A call answered (ATA) is a fax machine's or a modem's by what it sends (adaptive answer, AT+FAA=1): " + + "a fax goes to the fax receiver by itself, a modem's call to the terminal.", + style = MaterialTheme.typography.bodySmall, + ) Text( "As a modem's speaker: on from off hook until CONNECT (ATM1). ATM0 keeps it quiet, ATM2 on all the call; " + "ATL1-3 its volume, on top of the phone's media volume.", diff --git a/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt b/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt index b54e46d..ad841ad 100644 --- a/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt +++ b/app/src/test/java/com/neodesktop/dmodem/fax/FaxAppTest.kt @@ -185,4 +185,69 @@ class FaxAppTest { assertTrue(!h.sending) assertEquals(st.file, h.file) } + + /** text from the app's modem (its DTE hub), as the terminal sees it */ + private fun hubText(): () -> String { + val sb = StringBuffer() + val l = com.neodesktop.dmodem.terminal.TerminalLink.Listener { d, n -> sb.append(String(d, 0, n, Charsets.ISO_8859_1)) } + ModemState.dte.addListener(l) + closers.add { ModemState.dte.removeListener(l) } + return { sb.toString() } + } + + private fun waitFor(what: String, secs: Int = 30, cond: () -> Boolean) { + val end = System.currentTimeMillis() + secs * 1000L + while (!cond()) { + if (System.currentTimeMillis() > end) throw AssertionError("no $what\n" + log.takeLast(40).joinToString("\n")) + Thread.sleep(20) + } + } + + @Test + fun aFaxMachinesCallAnsweredAdaptively() { + // the service's start: adaptive answer on (in data mode, as the terminal has it) + val seen = hubText() + ModemState.adaptiveAnswer = true + ModemState.dte.write("ATE0X3+FAA=1\r") + waitFor("OK to +FAA=1") { seen().contains("OK") } + val c = other() + assertEquals("OK", c.command("E0")) + assertEquals("OK", c.command("X3+FCLASS=1")) + val rates = T30.modemRates(c) + val pages = listOf(FaxTestPage.of(true, rows = 600, seed = 3)) + // a fax machine dials (its modem's CNG as it waits); the app's plain answer, as the popup's + c.send("D5550100") + // (fax_line's line doesn't ring: answered at once, as aFaxAnsweredAndSaved) + assertTrue(ModemState.answer()) + // FAX: the fax receiver takes it by itself + assertEquals("CONNECT", c.result(60_000)) + val sent = T30.send(c, pages, "+1 555 0199", rates) + assertEquals(1, sent.pages) + val st = waitDone(30) + assertEquals(st.toString(), "", st.result) + assertTrue(!st.sending) + assertEquals(1, st.progress.pages) + assertEquals("+1 555 0199", st.progress.remote) + assertTrue(seen().contains("FAX")) + assertTrue(File(ctx.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), st.file).isFile) + assertTrue(!ModemState.dte.claimed) + } + + @Test + fun aDataCallAnsweredAdaptively() { + val seen = hubText() + ModemState.adaptiveAnswer = true + ModemState.dte.write("ATE0X3+FAA=1\r") + waitFor("OK to +FAA=1") { seen().contains("OK") } + val c = other() + assertEquals("OK", c.command("E0X3")) + // a modem dials: DATA, its CONNECT, the terminal's call; no fax + c.send("D5550100") + // (fax_line's line doesn't ring: answered at once, as aFaxAnsweredAndSaved) + assertTrue(ModemState.answer()) + waitFor("DATA and CONNECT", 60) { seen().contains("DATA") && seen().contains("CONNECT") } + assertTrue(c.result(30_000)!!.startsWith("CONNECT")) + assertEquals(null, Fax.state.value?.takeIf { it.running }) + assertTrue(!ModemState.dte.claimed) + } } diff --git a/external/d-modem-re b/external/d-modem-re index 804e1aa..24e48f3 160000 --- a/external/d-modem-re +++ b/external/d-modem-re @@ -1 +1 @@ -Subproject commit 804e1aa400461cda870bc09361d8db291ae0c844 +Subproject commit 24e48f3c1d4ac0ad72c3678bee056fc93ea088ee