mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Add YMODEM-G, Skip file, transfer timing and text delays
The HyperTerminal gaps of phase B, as in the GUI: - YMODEM-G both ways. A G sender that is asked with C uses plain YMODEM. - Skip file when receiving by ZMODEM (ZSKIP) or Kermit (X in the ACK). - Elapsed time, remaining time and cps/bps on the progress (Android, iOS). - Line and character delays for a text file sent (Android settings). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01B82eRRekyRUhR43KbmGNXK
This commit is contained in:
17 files changed
+426
-50
No files matched your search
@@ -64,6 +64,9 @@ data class TerminalSettings(
|
||||
val answerback: String = "",
|
||||
/** box drawing and block characters drawn to fill their cells (no gaps in ANSI art) */
|
||||
val drawBoxes: Boolean = true,
|
||||
/** a text file sent (Send Text File): the wait after each line, and after each character, in ms (HyperTerminal's ASCII Setup) */
|
||||
val lineDelayMs: Int = 0,
|
||||
val charDelayMs: Int = 0,
|
||||
) {
|
||||
/** [terminalType]'s profile (the default for one not known) */
|
||||
val profile: TerminalProfile get() = TerminalProfiles.byId(terminalType) ?: TerminalProfiles.DEFAULT
|
||||
@@ -95,6 +98,8 @@ class TerminalSettingsStore(private val context: Context) {
|
||||
val extraKeys = booleanPreferencesKey("extra_keys")
|
||||
val answerback = stringPreferencesKey("answerback")
|
||||
val drawBoxes = booleanPreferencesKey("draw_boxes")
|
||||
val lineDelay = intPreferencesKey("line_delay_ms")
|
||||
val charDelay = intPreferencesKey("char_delay_ms")
|
||||
}
|
||||
|
||||
/** the [E] named [s], or [d] for none or one not known */
|
||||
@@ -128,6 +133,8 @@ class TerminalSettingsStore(private val context: Context) {
|
||||
extraKeys = p[K.extraKeys] ?: d.extraKeys,
|
||||
answerback = p[K.answerback] ?: d.answerback,
|
||||
drawBoxes = p[K.drawBoxes] ?: d.drawBoxes,
|
||||
lineDelayMs = p[K.lineDelay] ?: d.lineDelayMs,
|
||||
charDelayMs = p[K.charDelay] ?: d.charDelayMs,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -167,6 +174,8 @@ class TerminalSettingsStore(private val context: Context) {
|
||||
p[K.extraKeys] = s.extraKeys
|
||||
p[K.answerback] = s.answerback
|
||||
p[K.drawBoxes] = s.drawBoxes
|
||||
p[K.lineDelay] = s.lineDelayMs
|
||||
p[K.charDelay] = s.charDelayMs
|
||||
}
|
||||
|
||||
/** the font size [sp] stored alone (the pinch's) */
|
||||
|
||||
@@ -231,13 +231,19 @@ class TerminalSession(
|
||||
}
|
||||
|
||||
/** [files] to the remote (which must be receiving: its rz, rb, rx, kermit -r) */
|
||||
fun sendFiles(protocol: Protocol, files: List<Outgoing>): Boolean {
|
||||
fun sendFiles(protocol: Protocol, files: List<Outgoing>, lineDelayMs: Int = 0, charDelayMs: Int = 0): Boolean {
|
||||
if (files.isEmpty()) return false
|
||||
val t = startTransfer(protocol, sending = true) ?: return false
|
||||
t.send(files)
|
||||
// (the waits: a text file's only, HyperTerminal's ASCII Setup)
|
||||
t.send(files, lineDelayMs.toLong(), charDelayMs.toLong())
|
||||
return true
|
||||
}
|
||||
|
||||
/** the file being received skipped, the transfer on to the next (ZMODEM, Kermit) */
|
||||
fun skipTransfer() {
|
||||
transfer?.skip()
|
||||
}
|
||||
|
||||
/** the running transfer, if any, cancelled */
|
||||
fun cancelTransfer() {
|
||||
transfer?.cancel()
|
||||
|
||||
@@ -133,7 +133,7 @@ fun TerminalScreen(
|
||||
session.sendBytes((command + "\r").toByteArray())
|
||||
delay(800)
|
||||
}
|
||||
if (!session.sendFiles(proto, files)) Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
|
||||
if (!session.sendFiles(proto, files, s.lineDelayMs, s.charDelayMs)) Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
/** the app's PPP on the call the modem has now (logged in by hand), the phone's traffic through it; why not in a toast */
|
||||
@@ -295,6 +295,7 @@ fun TerminalScreen(
|
||||
TransferBanner(
|
||||
t, DownloadsIncoming.where(context),
|
||||
onCancel = { session.cancelTransfer() },
|
||||
onSkip = { session.skipTransfer() },
|
||||
onDismiss = { session.dismissTransfer() },
|
||||
modifier = Modifier.align(Alignment.BottomCenter),
|
||||
)
|
||||
|
||||
@@ -116,9 +116,36 @@ fun TerminalSettingsSection() {
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
// HyperTerminal's ASCII Setup: the waits when a text file is sent
|
||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
DelayField("Line delay (ms)", s.lineDelayMs, Modifier.weight(1f)) { set { t -> t.copy(lineDelayMs = it) } }
|
||||
DelayField("Character delay (ms)", s.charDelayMs, Modifier.weight(1f)) { set { t -> t.copy(charDelayMs = it) } }
|
||||
}
|
||||
Text(
|
||||
"The waits when a text file is sent (Text protocol): after each line, and after each character. " +
|
||||
"For a remote that loses characters when they come fast.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** a wait in ms, 0 to 9999 */
|
||||
@Composable
|
||||
private fun DelayField(label: String, value: Int, modifier: Modifier, onChange: (Int) -> Unit) {
|
||||
var text by remember(value) { mutableStateOf(value.toString()) }
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { v ->
|
||||
text = v.filter { it.isDigit() }.take(4)
|
||||
onChange(text.toIntOrNull() ?: 0)
|
||||
},
|
||||
label = { Text(label) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/** a labelled switch */
|
||||
@Composable
|
||||
private fun Flag(label: String, value: Boolean, onChange: (Boolean) -> Unit) {
|
||||
|
||||
@@ -20,6 +20,9 @@ import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -29,6 +32,8 @@ import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import kotlinx.coroutines.delay
|
||||
import org.dmodem.app.io.monotonicMs
|
||||
import org.dmodem.app.transfer.Protocol
|
||||
import org.dmodem.app.transfer.TransferState
|
||||
|
||||
@@ -89,6 +94,14 @@ fun TransferDialog(
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
if (protocol == Protocol.YMODEM_G) {
|
||||
Text(
|
||||
"YMODEM-G sends with no wait for each block's answer: fast, but for a line that corrects " +
|
||||
"its errors (a V.42 connection). An error on the line ends the transfer.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 4.dp),
|
||||
)
|
||||
}
|
||||
if (protocol.hexFormat != null) {
|
||||
Text(
|
||||
if (sending) "The file goes as ${protocol.label}, a line each (a file of them already goes as it is), " +
|
||||
@@ -108,9 +121,29 @@ fun TransferDialog(
|
||||
)
|
||||
}
|
||||
|
||||
/** a transfer as it goes (cancel it), or how it ended (dismissed) */
|
||||
/**
|
||||
* a transfer as it goes (cancel it; skip the file being received, where the protocol can), or
|
||||
* how it ended (dismissed); its times and speed as HyperTerminal shows them (a tap on them:
|
||||
* cps or bps)
|
||||
*/
|
||||
@Composable
|
||||
fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDismiss: () -> Unit, modifier: Modifier = Modifier) {
|
||||
fun TransferBanner(
|
||||
t: TransferState,
|
||||
savedTo: String,
|
||||
onCancel: () -> Unit,
|
||||
onSkip: () -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
var bps by rememberSaveable { mutableStateOf(false) }
|
||||
// (the times go on while no bytes come: a tick each second)
|
||||
var now by remember { mutableLongStateOf(monotonicMs()) }
|
||||
LaunchedEffect(t.running) {
|
||||
while (t.running) {
|
||||
now = monotonicMs()
|
||||
delay(1000)
|
||||
}
|
||||
}
|
||||
Surface(modifier.fillMaxWidth().padding(12.dp), tonalElevation = 6.dp, shape = RoundedCornerShape(12.dp), shadowElevation = 6.dp) {
|
||||
Column(Modifier.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 6.dp)) {
|
||||
val p = t.progress
|
||||
@@ -131,6 +164,14 @@ fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDi
|
||||
LinearProgressIndicator(Modifier.fillMaxWidth().padding(end = 8.dp))
|
||||
}
|
||||
}
|
||||
val timing = t.timing(bps, maxOf(now, if (t.running) monotonicMs() else 0))
|
||||
if (timing.isNotEmpty()) {
|
||||
Text(
|
||||
timing,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 4.dp).clickable { bps = !bps },
|
||||
)
|
||||
}
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
when {
|
||||
@@ -141,6 +182,7 @@ fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDi
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f),
|
||||
)
|
||||
if (t.running && !t.sending && t.protocol.canSkip && p.file.isNotEmpty()) TextButton(onClick = onSkip) { Text("Skip file") }
|
||||
if (t.running) TextButton(onClick = onCancel) { Text("Cancel") } else TextButton(onClick = onDismiss) { Text("OK") }
|
||||
}
|
||||
}
|
||||
|
||||
+18
-3
@@ -218,8 +218,20 @@
|
||||
then goes through it, as with the dial of the internet screen
|
||||
(`PppTakeoverTest`).
|
||||
|
||||
The terminal sends and receives files by ZMODEM, YMODEM, XMODEM(-1K) and
|
||||
Kermit. It also sends and receives Intel HEX or Motorola S-records for
|
||||
The terminal sends and receives files by ZMODEM, YMODEM, YMODEM-G,
|
||||
XMODEM(-1K) and Kermit:
|
||||
- YMODEM-G sends the blocks and does not wait for an ACK. Use it only on a
|
||||
line that corrects its errors (a V.42 connection). An error on the line
|
||||
stops the transfer, because YMODEM-G cannot send a block again. When the
|
||||
receiver asks with C, the sender uses plain YMODEM.
|
||||
- When you receive by ZMODEM or Kermit, **Skip file** stops the file that
|
||||
comes now and deletes it. The sender then sends the next file (ZMODEM
|
||||
sends ZSKIP, Kermit sends X in its ACK).
|
||||
- The progress shows the elapsed time, the remaining time and the speed of
|
||||
the file. Tap the speed to show it in cps (characters a second) or in bps
|
||||
(10 bits a character).
|
||||
|
||||
It also sends and receives Intel HEX or Motorola S-records for
|
||||
EPROM programmers, monitors and boot loaders:
|
||||
- When it sends a file as records, it uses S1/S2/S3 by the size of the
|
||||
image, and Intel extended addresses above 64 KB. If the file already
|
||||
@@ -228,7 +240,10 @@
|
||||
binary image that they hold (gaps are 0xFF).
|
||||
|
||||
Plain text is also available. The app sends the bytes of a file without
|
||||
change, as if you typed them (to an editor, a BBS, `cat > file`). It saves
|
||||
change, as if you typed them (to an editor, a BBS, `cat > file`). On
|
||||
Android, the terminal settings have a line delay and a character delay (in
|
||||
ms), as the ASCII Setup of HyperTerminal has. The app waits for this time
|
||||
after each line end and after each character. It saves
|
||||
the received data without change until the line is silent for 10 s.
|
||||
- **Dial**: the dialing directory. Each entry has the number of the system
|
||||
(or the SIP user), the AT commands that are necessary before ATD, its
|
||||
|
||||
@@ -307,6 +307,12 @@ final class JobsModel: ObservableObject {
|
||||
/// the transfer cancelled
|
||||
func cancelTransfer() { transferJob?.cancel() }
|
||||
|
||||
/// the file being received skipped, the transfer on to the next (ZMODEM, Kermit)
|
||||
func skipTransfer() { transferJob?.skip() }
|
||||
|
||||
/// the transfer's times and speed, as HyperTerminal shows them ([bps]: bits a second)
|
||||
func transferTiming(bps: Bool) -> String { transferJob?.timing(bps: bps) ?? transfer?.timing(bps: bps) ?? "" }
|
||||
|
||||
/// the last transfer's outcome cleared (not while one's going)
|
||||
func dismissTransfer() { if transferJob == nil { transfer = nil } }
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ struct TransferView: View {
|
||||
@State private var error: String?
|
||||
@State private var received: [URL] = []
|
||||
@State private var preview: URL?
|
||||
@AppStorage("transferBps") private var bps = false
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
@@ -70,6 +71,7 @@ struct TransferView: View {
|
||||
switch proto {
|
||||
case "ZMODEM": return "sz file (it sends), rz (it receives; ZMODEM starts by itself either way)"
|
||||
case "YMODEM": return "sb file, rb"
|
||||
case "YMODEM_G": return "sb file (YMODEM-G is for a V.42 line: an error ends it), rb"
|
||||
case "XMODEM": return "sx file, rx -c file"
|
||||
case "XMODEM_1K": return "sx -k file, rx -c file"
|
||||
default: return "kermit -i -s file, kermit -i -r"
|
||||
@@ -91,10 +93,20 @@ struct TransferView: View {
|
||||
Text(bytes(p.bytes)).foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
// (the times and the speed, a second at a time; a tap: cps or bps)
|
||||
TimelineView(.periodic(from: .now, by: 1)) { _ in
|
||||
let timing = jobs.transferTiming(bps: bps)
|
||||
if !timing.isEmpty {
|
||||
Text(timing).foregroundStyle(.secondary).onTapGesture { bps.toggle() }
|
||||
}
|
||||
}
|
||||
if p.files > 0 { Text("\(p.files) file\(p.files == 1 ? "" : "s") done") }
|
||||
if p.errors > 0 { Text("\(p.errors) block\(p.errors == 1 ? "" : "s") sent again").foregroundStyle(.secondary) }
|
||||
if let r = t.result, !r.isEmpty { Text(r).foregroundStyle(.red) }
|
||||
if t.running {
|
||||
if !jobs.transferSending && !p.file.isEmpty && t.protocol.canSkip {
|
||||
Button("Skip file") { jobs.skipTransfer() }
|
||||
}
|
||||
Button("Cancel", role: .destructive) { jobs.cancelTransfer() }
|
||||
} else {
|
||||
Button("Dismiss") { jobs.dismissTransfer() }
|
||||
|
||||
@@ -12,7 +12,7 @@ import kotlin.concurrent.Volatile
|
||||
/**
|
||||
* A file transfer on the modem's line (the Android app's terminal's, for
|
||||
* iOS): files sent to the remote, or received from it, by [protocolName]'s
|
||||
* name (ZMODEM, YMODEM, XMODEM, XMODEM_1K, KERMIT).
|
||||
* name (ZMODEM, YMODEM, YMODEM_G, XMODEM, XMODEM_1K, KERMIT…).
|
||||
*/
|
||||
class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, changed) {
|
||||
private val transfer = Transfer(
|
||||
@@ -48,6 +48,12 @@ class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogO
|
||||
/** the transfer stopped */
|
||||
fun cancel() = transfer.cancel()
|
||||
|
||||
/** the file being received skipped, the transfer on to the next ([canSkip]'s protocols) */
|
||||
fun skip() = transfer.skip()
|
||||
|
||||
/** the times and the speed as HyperTerminal shows them ([bps]: bits a second, else characters) */
|
||||
fun timing(bps: Boolean): String = state.timing(bps)
|
||||
|
||||
companion object {
|
||||
/** the protocols' names (what each is called: [label]) */
|
||||
val protocols: List<String> = Protocol.entries.map { it.name }
|
||||
@@ -55,6 +61,9 @@ class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogO
|
||||
/** what the protocol [protocolName] is called */
|
||||
fun label(protocolName: String): String = Protocol.valueOf(protocolName).label
|
||||
|
||||
/** whether the file being received can be skipped ([skip]) */
|
||||
fun canSkip(protocolName: String): Boolean = Protocol.valueOf(protocolName).canSkip
|
||||
|
||||
/** whether it sends more than one file */
|
||||
fun batch(protocolName: String): Boolean = Protocol.valueOf(protocolName).batch
|
||||
|
||||
|
||||
@@ -529,6 +529,8 @@ class Kermit(
|
||||
// (a name sent "converted", all capitals, as C-Kermit does: back in lower case)
|
||||
if (n.any { it.isLetter() } && n.none { it.isLowerCase() }) n.lowercase() else n
|
||||
}
|
||||
// (a skip asked for before this file: not for it)
|
||||
io.takeSkip()
|
||||
val (o, actual) = into.create(name, -1)
|
||||
out = o.buffered()
|
||||
current = actual
|
||||
@@ -560,6 +562,9 @@ class Kermit(
|
||||
decode(r.data, counted)
|
||||
got += counted.n
|
||||
report { it.copy(bytes = got) }
|
||||
// the user's skip: X in the ACK (the sender ends the file with Z D, and
|
||||
// the file is dropped)
|
||||
if (io.takeSkip()) reply = "X".encodeToByteArray()
|
||||
}
|
||||
'Z' -> {
|
||||
val o = out
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package org.dmodem.app.transfer
|
||||
|
||||
import org.dmodem.app.io.IOException
|
||||
import org.dmodem.app.io.sleepMs
|
||||
|
||||
/**
|
||||
* A file as plain text: no protocol at all. Sending: its bytes as they
|
||||
@@ -17,8 +18,12 @@ class TextTransfer(
|
||||
/** the quiet that ends a receive (the tests' shorter) */
|
||||
private val quietMs: Long = QUIET_MS,
|
||||
) {
|
||||
/** [file] sent verbatim */
|
||||
fun send(file: Outgoing) {
|
||||
/**
|
||||
* [file] sent verbatim; paced, as HyperTerminal's ASCII Setup does it, with a wait of
|
||||
* [lineDelayMs] after each line end (CR, LF, or the LF of CR LF) and [charDelayMs] after
|
||||
* each character
|
||||
*/
|
||||
fun send(file: Outgoing, lineDelayMs: Long = 0, charDelayMs: Long = 0) {
|
||||
val buf = ByteArray(CHUNK)
|
||||
var sent = 0L
|
||||
file.open().use { src ->
|
||||
@@ -27,8 +32,25 @@ class TextTransfer(
|
||||
val n = src.read(buf, 0, buf.size)
|
||||
if (n < 0) break
|
||||
if (n == 0) continue
|
||||
io.write(buf.copyOf(n))
|
||||
sent += n
|
||||
if (lineDelayMs <= 0 && charDelayMs <= 0) {
|
||||
io.write(buf.copyOf(n))
|
||||
sent += n
|
||||
progress(Progress(file.name, sent, file.size))
|
||||
continue
|
||||
}
|
||||
for (i in 0 until n) {
|
||||
val c = buf[i].toInt() and 0xff
|
||||
io.write(c)
|
||||
sent++
|
||||
// (the LF of a CR LF ends the line, not the CR)
|
||||
val lineEnd = c == LF || (c == CR && (i + 1 >= n || buf[i + 1].toInt() != LF))
|
||||
val ms = charDelayMs + if (lineEnd) lineDelayMs else 0
|
||||
if (ms > 0) {
|
||||
progress(Progress(file.name, sent, file.size))
|
||||
sleepMs(ms)
|
||||
if (io.isCancelled) throw TransferCancelled("cancelled")
|
||||
}
|
||||
}
|
||||
progress(Progress(file.name, sent, file.size))
|
||||
}
|
||||
}
|
||||
@@ -74,6 +96,8 @@ class TextTransfer(
|
||||
|
||||
companion object {
|
||||
const val CHUNK = 1024
|
||||
private const val CR = 13
|
||||
private const val LF = 10
|
||||
/** how long the first byte may take to come, and the quiet that ends it */
|
||||
const val FIRST_MS = 60_000L
|
||||
const val QUIET_MS = 10_000L
|
||||
|
||||
@@ -4,6 +4,7 @@ package org.dmodem.app.transfer
|
||||
|
||||
import org.dmodem.app.io.IOException
|
||||
import org.dmodem.app.io.background
|
||||
import org.dmodem.app.io.monotonicMs
|
||||
import org.dmodem.app.io.sleepMs
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
@@ -11,6 +12,8 @@ import kotlin.concurrent.Volatile
|
||||
enum class Protocol(val label: String, val batch: Boolean) {
|
||||
ZMODEM("ZMODEM", true),
|
||||
YMODEM("YMODEM", true),
|
||||
/** YMODEM with no ACKs: for a line that corrects its errors (a modem's V.42); an error ends it */
|
||||
YMODEM_G("YMODEM-G", true),
|
||||
XMODEM("XMODEM", false),
|
||||
XMODEM_1K("XMODEM-1K", false),
|
||||
KERMIT("Kermit", true),
|
||||
@@ -26,6 +29,8 @@ enum class Protocol(val label: String, val batch: Boolean) {
|
||||
fun remoteCommand(remoteSends: Boolean): String = when (this) {
|
||||
ZMODEM -> if (remoteSends) "sz -b " else "rz -b"
|
||||
YMODEM -> if (remoteSends) "sb " else "rb"
|
||||
// (sb sends YMODEM-G when asked with G; lrzsz's rb asks with C, and gets plain YMODEM)
|
||||
YMODEM_G -> if (remoteSends) "sb " else "rb"
|
||||
XMODEM -> if (remoteSends) "sx " else "rx -c "
|
||||
XMODEM_1K -> if (remoteSends) "sx -k " else "rx -c "
|
||||
KERMIT -> if (remoteSends) "kermit -i -s " else "kermit -i -r"
|
||||
@@ -35,6 +40,9 @@ enum class Protocol(val label: String, val batch: Boolean) {
|
||||
TEXT -> if (remoteSends) "cat " else ""
|
||||
}
|
||||
|
||||
/** whether the file being received can be skipped (the protocol tells the sender) */
|
||||
val canSkip: Boolean get() = this == ZMODEM || this == KERMIT
|
||||
|
||||
/** the hex records' format, for the two that are */
|
||||
val hexFormat: HexRecords.Format?
|
||||
get() = when (this) {
|
||||
@@ -54,8 +62,56 @@ data class TransferState(
|
||||
val result: String? = null,
|
||||
/** the names the received files got */
|
||||
val received: List<String> = emptyList(),
|
||||
/** when it started ([monotonicMs]), and when it ended (0 while it runs) */
|
||||
val startedMs: Long = 0,
|
||||
val endedMs: Long = 0,
|
||||
/** when the file now going started ([monotonicMs]) */
|
||||
val fileStartedMs: Long = 0,
|
||||
) {
|
||||
val running: Boolean get() = result == null
|
||||
|
||||
/** how long it has taken, at [now] ([monotonicMs]) */
|
||||
fun elapsedMs(now: Long = monotonicMs()): Long = if (startedMs == 0L) 0 else ((if (endedMs > 0) endedMs else now) - startedMs).coerceAtLeast(0)
|
||||
|
||||
/** the file's bytes a second (its throughput), at [now]; 0 before a second has gone */
|
||||
fun cps(now: Long = monotonicMs()): Long {
|
||||
if (fileStartedMs == 0L) return 0
|
||||
val ms = (if (endedMs > 0) endedMs else now) - fileStartedMs
|
||||
return if (ms < 1000) 0 else progress.bytes * 1000 / ms
|
||||
}
|
||||
|
||||
/** the time the file still takes at its [cps], at [now]; -1 not known */
|
||||
fun remainingMs(now: Long = monotonicMs()): Long {
|
||||
val c = cps(now)
|
||||
if (!running || c <= 0 || progress.size <= 0) return -1
|
||||
return (progress.size - progress.bytes).coerceAtLeast(0) * 1000 / c
|
||||
}
|
||||
|
||||
/**
|
||||
* the times and the speed as HyperTerminal's progress shows them: "Elapsed 0:00:12,
|
||||
* Remaining 0:01:00, 2340 cps" ([bps]: bits a second, 10 to a character, as its cps/bps button gives)
|
||||
*/
|
||||
fun timing(bps: Boolean): String = timing(bps, monotonicMs())
|
||||
|
||||
/** [timing] at [now] ([monotonicMs]) */
|
||||
fun timing(bps: Boolean, now: Long): String {
|
||||
if (startedMs == 0L) return ""
|
||||
val parts = ArrayList<String>()
|
||||
parts.add("Elapsed " + clock(elapsedMs(now)))
|
||||
val left = remainingMs(now)
|
||||
if (left >= 0) parts.add("Remaining " + clock(left))
|
||||
val c = cps(now)
|
||||
if (c > 0) parts.add(if (bps) "${c * 10} bps" else "$c cps")
|
||||
return parts.joinToString(", ")
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** [ms] as HyperTerminal shows a time: 0:01:05 */
|
||||
fun clock(ms: Long): String {
|
||||
val s = ms.coerceAtLeast(0) / 1000
|
||||
return "${s / 3600}:" + "${s / 60 % 60}".padStart(2, '0') + ":" + "${s % 60}".padStart(2, '0')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,13 +139,18 @@ class Transfer(
|
||||
onState(s)
|
||||
}
|
||||
|
||||
private val progress: (Progress) -> Unit = { p -> update(state.copy(progress = p)) }
|
||||
private val progress: (Progress) -> Unit = { p ->
|
||||
// (a new file: its throughput from now)
|
||||
val fileStarted = if (p.file != state.progress.file || state.fileStartedMs == 0L) monotonicMs() else state.fileStartedMs
|
||||
update(state.copy(progress = p, fileStartedMs = fileStarted))
|
||||
}
|
||||
|
||||
/** files received into [into] ([name]: XMODEM's, which sends none) */
|
||||
fun receive(into: Incoming, name: String = "received.bin") = start {
|
||||
when (protocol) {
|
||||
Protocol.ZMODEM -> ZModem(io, progress).receive(into)
|
||||
Protocol.YMODEM -> XYModem(io, progress).receiveY(into)
|
||||
Protocol.YMODEM_G -> XYModem(io, progress).receiveY(into, g = true)
|
||||
Protocol.XMODEM, Protocol.XMODEM_1K -> listOf(XYModem(io, progress).receiveX(into, name))
|
||||
Protocol.KERMIT -> Kermit(io, progress).also { kermit = it }.receive(into)
|
||||
Protocol.INTEL_HEX, Protocol.SREC -> HexTransfer(io, protocol.hexFormat!!, progress).receive(into, name)
|
||||
@@ -97,23 +158,27 @@ class Transfer(
|
||||
}
|
||||
}
|
||||
|
||||
/** [files] sent ([files]' first only, for XMODEM) */
|
||||
fun send(files: List<Outgoing>) = start {
|
||||
/**
|
||||
* [files] sent ([files]' first only, for XMODEM); plain text with a wait of [lineDelayMs]
|
||||
* after each line and [charDelayMs] after each character (HyperTerminal's ASCII Setup)
|
||||
*/
|
||||
fun send(files: List<Outgoing>, lineDelayMs: Long = 0, charDelayMs: Long = 0) = start {
|
||||
when (protocol) {
|
||||
Protocol.ZMODEM -> ZModem(io, progress).send(files)
|
||||
Protocol.YMODEM -> XYModem(io, progress).sendY(files)
|
||||
Protocol.YMODEM_G -> XYModem(io, progress).sendY(files, g = true)
|
||||
Protocol.XMODEM -> XYModem(io, progress).sendX(files.first(), oneK = false)
|
||||
Protocol.XMODEM_1K -> XYModem(io, progress).sendX(files.first(), oneK = true)
|
||||
Protocol.KERMIT -> Kermit(io, progress).also { kermit = it }.send(files)
|
||||
Protocol.INTEL_HEX, Protocol.SREC -> HexTransfer(io, protocol.hexFormat!!, progress).send(files.first())
|
||||
Protocol.TEXT -> TextTransfer(io, progress).send(files.first())
|
||||
Protocol.TEXT -> TextTransfer(io, progress).send(files.first(), lineDelayMs, charDelayMs)
|
||||
}
|
||||
emptyList()
|
||||
}
|
||||
|
||||
/** [body] run on a thread of its own: its end (the files' names, or why it failed) the state's, then [onEnd] with what was left unread */
|
||||
private fun start(body: () -> List<String>) {
|
||||
update(state)
|
||||
update(state.copy(startedMs = monotonicMs()))
|
||||
background("transfer-${protocol.name.lowercase()}") {
|
||||
val end = try {
|
||||
val names = body()
|
||||
@@ -127,11 +192,17 @@ class Transfer(
|
||||
}
|
||||
// (what the other side still sends of the protocol settles first)
|
||||
if (end.result != "") sleepMs(300)
|
||||
update(end)
|
||||
onEnd(end, io.leftover())
|
||||
val done = end.copy(endedMs = monotonicMs())
|
||||
update(done)
|
||||
onEnd(done, io.leftover())
|
||||
}
|
||||
}
|
||||
|
||||
/** the file being received skipped, and the transfer on to the next (ZMODEM's ZSKIP, Kermit's X) */
|
||||
fun skip() {
|
||||
if (state.running && !sending && protocol.canSkip) io.requestSkip()
|
||||
}
|
||||
|
||||
/** stopped: the other side told (CANs; Kermit's E packet), the thread ends at its next read */
|
||||
fun cancel() {
|
||||
if (!state.running) return
|
||||
|
||||
@@ -80,6 +80,23 @@ class TransferIo(private val send: (ByteArray) -> Unit) {
|
||||
return out.toByteArray()
|
||||
}
|
||||
|
||||
@kotlin.concurrent.Volatile private var skip = false
|
||||
|
||||
/** the user's Skip file: the protocol takes it at its next look ([takeSkip]) */
|
||||
fun requestSkip() {
|
||||
skip = true
|
||||
}
|
||||
|
||||
/** whether the user asked to skip the file now (once) */
|
||||
fun takeSkip(): Boolean {
|
||||
if (!skip) return false
|
||||
skip = false
|
||||
return true
|
||||
}
|
||||
|
||||
/** whether a skip waits to be taken (it is not taken) */
|
||||
val skipWanted: Boolean get() = skip
|
||||
|
||||
/** cancelled for [why]: reads and writes throw TransferCancelled from now on */
|
||||
fun cancel(why: String) {
|
||||
cancelled = why
|
||||
|
||||
@@ -10,6 +10,12 @@ import org.dmodem.app.io.*
|
||||
* blocks, CRC, a batch of files each named and sized in block 0), both
|
||||
* ways. Errors are repeated (NAK) up to [MAX_ERRORS] times; CAN CAN
|
||||
* from the other side ends it.
|
||||
*
|
||||
* YMODEM-G ([receiveY], [sendY] with g): the receiver asks with G, and
|
||||
* the sender sends the blocks with no wait for an ACK (for a line that
|
||||
* corrects its errors, a modem's V.42). An error ends it, as no block can
|
||||
* be sent again; each file's EOT is still acknowledged. A sender asked
|
||||
* with C does plain YMODEM.
|
||||
*/
|
||||
class XYModem(
|
||||
private val io: TransferIo,
|
||||
@@ -54,12 +60,18 @@ class XYModem(
|
||||
}
|
||||
}
|
||||
|
||||
/** a YMODEM batch received: the names the files got */
|
||||
fun receiveY(into: Incoming): List<String> {
|
||||
/** YMODEM-G: no ACKs, no blocks again */
|
||||
private var g = false
|
||||
|
||||
/** a YMODEM batch received (YMODEM-G if [g]): the names the files got */
|
||||
fun receiveY(into: Incoming, g: Boolean = false): List<String> {
|
||||
this.g = g
|
||||
val names = ArrayList<String>()
|
||||
while (true) {
|
||||
// block 0: the file's name and size, or an empty one (the batch over)
|
||||
val b0 = startAndRead(ymodem = true) ?: throw IOException("the sender didn't start")
|
||||
// (lrzsz's sb in YMODEM-G ends with no empty block 0: the batch over when none comes)
|
||||
val b0 = startAndRead(ymodem = true, tries = if (g && names.isNotEmpty()) 2 else 10)
|
||||
?: if (g && names.isNotEmpty()) return names else throw IOException("the sender didn't start")
|
||||
if (b0.number != 0) throw IOException("no YMODEM header block")
|
||||
val data = b0.data
|
||||
if (data[0] == 0.toByte()) {
|
||||
@@ -71,12 +83,13 @@ class XYModem(
|
||||
val meta = latin1String(data, nul + 1, data.size - nul - 1).trimEnd('\u0000').split(' ')
|
||||
val size = meta.getOrNull(0)?.toLongOrNull() ?: -1
|
||||
val mtime = meta.getOrNull(1)?.toLongOrNull(8) ?: 0
|
||||
io.write(ACK)
|
||||
// (YMODEM-G: block 0 not acknowledged, G asks for the data)
|
||||
if (!g) io.write(ACK)
|
||||
val (out, actual) = into.create(name, size)
|
||||
report { it.copy(file = actual, bytes = 0, size = size) }
|
||||
try {
|
||||
out.use { o ->
|
||||
io.write(C)
|
||||
io.write(if (g) G else C)
|
||||
receiveFile(o, size, ymodem = true, first = null, holdLast = null)
|
||||
}
|
||||
into.done(actual, mtime)
|
||||
@@ -92,11 +105,14 @@ class XYModem(
|
||||
private class Block(val number: Int, val data: ByteArray)
|
||||
|
||||
/** the first block, asked for with C (CRC) and, for XMODEM, NAK (a checksum) when C isn't answered */
|
||||
private fun startAndRead(ymodem: Boolean): Block? {
|
||||
private fun startAndRead(ymodem: Boolean, tries: Int = 10): Block? {
|
||||
var crc = true
|
||||
for (attempt in 0 until 10) {
|
||||
bad = false
|
||||
for (attempt in 0 until tries) {
|
||||
if (attempt == 4 && !ymodem) crc = false
|
||||
io.write(if (crc) C else NAK)
|
||||
// (a damaged block 0 asked for again with NAK: a C could be taken for its ACK and a
|
||||
// request for the data)
|
||||
io.write(if (g) G else if (crc && !(ymodem && bad)) C else NAK)
|
||||
val b = readBlock(crc, 3000) ?: continue
|
||||
this.crc = crc
|
||||
return b
|
||||
@@ -109,6 +125,9 @@ class XYModem(
|
||||
/** the sender's EOT came instead of a block ([readBlock]) */
|
||||
private var eot = false
|
||||
|
||||
/** a damaged block came ([readBlock]) */
|
||||
private var bad = false
|
||||
|
||||
/**
|
||||
* a block within [waitMs], its CRC or checksum checked: (number, data);
|
||||
* null on a timeout, a bad block (the line purged) or EOT (which sets
|
||||
@@ -116,6 +135,7 @@ class XYModem(
|
||||
*/
|
||||
private fun readBlock(useCrc: Boolean, waitMs: Long): Block? {
|
||||
eot = false
|
||||
bad = false
|
||||
// (what isn't a block's start let go by: the sender's own messages, line noise)
|
||||
val deadline = monotonicMs() + waitMs
|
||||
var size = 0
|
||||
@@ -155,6 +175,7 @@ class XYModem(
|
||||
private fun badBlock(): Block? {
|
||||
// (what's left of the bad block: let it go by)
|
||||
while (io.read(200) >= 0) { /* drop */ }
|
||||
bad = true
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -174,15 +195,17 @@ class XYModem(
|
||||
block = readBlock(crc, timeoutMs)
|
||||
if (block == null) {
|
||||
if (eot) {
|
||||
// YMODEM: the first EOT answered NAK, the second ACK (to be sure it was one)
|
||||
// YMODEM: the first EOT answered NAK, the second ACK (to be sure it was
|
||||
// one); YMODEM-G: ACK
|
||||
eots++
|
||||
if (ymodem && eots == 1) {
|
||||
if (ymodem && eots == 1 && !g) {
|
||||
io.write(NAK)
|
||||
continue
|
||||
}
|
||||
io.write(ACK)
|
||||
break
|
||||
}
|
||||
if (g) gFail()
|
||||
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
|
||||
report { it.copy(errors = it.errors + 1) }
|
||||
io.write(NAK)
|
||||
@@ -204,7 +227,7 @@ class XYModem(
|
||||
written += data.size
|
||||
expect++
|
||||
errors = 0
|
||||
io.write(ACK)
|
||||
if (!g) io.write(ACK)
|
||||
report { it.copy(bytes = written) }
|
||||
}
|
||||
(expect - 1) and 0xff -> io.write(ACK) // a repeat of one already had (our ACK lost)
|
||||
@@ -217,34 +240,43 @@ class XYModem(
|
||||
held?.let { holdLast?.write(it) }
|
||||
}
|
||||
|
||||
/** YMODEM-G's end on an error: no block can come again */
|
||||
private fun gFail(): Nothing {
|
||||
io.write(CAN, CAN, CAN, CAN, CAN)
|
||||
throw IOException("an error on the line (YMODEM-G cannot send a block again)")
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// sending
|
||||
|
||||
/** one file by XMODEM (1K blocks if [oneK]) */
|
||||
fun sendX(file: Outgoing, oneK: Boolean) {
|
||||
val useCrc = waitForStart() ?: throw IOException("the receiver didn't start")
|
||||
val start = waitForStart(g = false) ?: throw IOException("the receiver didn't start")
|
||||
report { it.copy(file = file.name, bytes = 0, size = file.size) }
|
||||
file.open().use { sendData(it, if (oneK) 1024 else 128, useCrc, ymodem = false) }
|
||||
file.open().use { sendData(it, if (oneK) 1024 else 128, start == START_CRC, ymodem = false, streaming = false) }
|
||||
report { it.copy(files = it.files + 1) }
|
||||
}
|
||||
|
||||
/** a YMODEM batch */
|
||||
fun sendY(files: List<Outgoing>) {
|
||||
/** a YMODEM batch (YMODEM-G if [g] and the receiver asks with G; asked with C, plain YMODEM) */
|
||||
fun sendY(files: List<Outgoing>, g: Boolean = false) {
|
||||
for (f in files) {
|
||||
if (waitForStart() != true) throw IOException("the receiver didn't start")
|
||||
val start = waitForStart(g)
|
||||
if (start == null || start == START_CHECKSUM) throw IOException("the receiver didn't start")
|
||||
val streaming = start == START_G
|
||||
val head = ByteArray(128)
|
||||
val meta = (f.name.substringAfterLast('/').encodeToByteArray() + 0) +
|
||||
("${if (f.size >= 0) f.size else 0} ${(f.mtime.coerceAtLeast(0)).toString(8)} 0").encodeToByteArray()
|
||||
val block0 = if (meta.size > 128) ByteArray(1024) else head
|
||||
meta.copyInto(block0, 0, 0, minOf(meta.size, block0.size))
|
||||
sendBlock(0, block0, true)
|
||||
if (streaming) io.write(blockBytes(0, block0, true)) else sendBlock(0, block0, true)
|
||||
report { it.copy(file = f.name, bytes = 0, size = f.size) }
|
||||
if (waitForStart() != true) throw IOException("the receiver didn't ask for the data")
|
||||
f.open().use { sendData(it, 1024, useCrc = true, ymodem = true) }
|
||||
if (waitForStart(g) != start) throw IOException("the receiver didn't ask for the data")
|
||||
f.open().use { sendData(it, 1024, useCrc = true, ymodem = true, streaming = streaming) }
|
||||
report { it.copy(files = it.files + 1) }
|
||||
}
|
||||
// the batch over: an empty block 0
|
||||
if (waitForStart() != true) throw IOException("the receiver didn't ask for the end")
|
||||
val end0 = waitForStart(g)
|
||||
if (end0 == null || end0 == START_CHECKSUM) throw IOException("the receiver didn't ask for the end")
|
||||
// (rb exits as it takes it: its ACK can be lost with it, and every file is in)
|
||||
val end = blockBytes(0, ByteArray(128), true)
|
||||
for (attempt in 0 until 3) {
|
||||
@@ -253,21 +285,25 @@ class XYModem(
|
||||
}
|
||||
}
|
||||
|
||||
/** C (CRC: true) or NAK (checksum: false) from the receiver; null if neither came */
|
||||
private fun waitForStart(): Boolean? {
|
||||
/** C ([START_CRC]), NAK ([START_CHECKSUM]) or, when [g], G ([START_G]) from the receiver; null if none came */
|
||||
private fun waitForStart(g: Boolean): Int? {
|
||||
val end = monotonicMs() + 60_000
|
||||
while (monotonicMs() < end) {
|
||||
when (io.read(timeoutMs)) {
|
||||
C -> return true
|
||||
NAK -> return false
|
||||
G -> if (g) return START_G
|
||||
C -> return START_CRC
|
||||
NAK -> return START_CHECKSUM
|
||||
CAN -> if (io.read(1000) == CAN) throw TransferCancelled("cancelled by the receiver")
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** the file's data sent in blocks of [blockSize] (a short last one in 128, padded with SUB), then EOT until acknowledged */
|
||||
private fun sendData(input: Source, blockSize: Int, useCrc: Boolean, ymodem: Boolean) {
|
||||
/**
|
||||
* the file's data sent in blocks of [blockSize] (a short last one in 128, padded with SUB),
|
||||
* then EOT until acknowledged; [streaming]: the blocks with no wait for an ACK (YMODEM-G)
|
||||
*/
|
||||
private fun sendData(input: Source, blockSize: Int, useCrc: Boolean, ymodem: Boolean, streaming: Boolean) {
|
||||
var n = 1
|
||||
var sent = 0L
|
||||
val buf = ByteArray(blockSize)
|
||||
@@ -283,7 +319,12 @@ class XYModem(
|
||||
val size = if (len <= 128) 128 else blockSize
|
||||
val data = buf.copyOf(size)
|
||||
for (i in len until size) data[i] = SUB.toByte()
|
||||
sendBlock(n, data, useCrc)
|
||||
if (streaming) {
|
||||
io.write(blockBytes(n, data, true))
|
||||
gCheck()
|
||||
} else {
|
||||
sendBlock(n, data, useCrc)
|
||||
}
|
||||
sent += len
|
||||
n++
|
||||
report { it.copy(bytes = sent) }
|
||||
@@ -298,6 +339,13 @@ class XYModem(
|
||||
}
|
||||
}
|
||||
|
||||
/** YMODEM-G: the receiver's CAN CAN, if it sent them (no wait) */
|
||||
private fun gCheck() {
|
||||
while (io.available()) {
|
||||
if (io.read(0) == CAN && io.read(1000) == CAN) throw TransferCancelled("cancelled by the receiver")
|
||||
}
|
||||
}
|
||||
|
||||
/** a block sent until it's acknowledged */
|
||||
private fun sendBlock(n: Int, data: ByteArray, useCrc: Boolean) {
|
||||
val bytes = blockBytes(n, data, useCrc)
|
||||
@@ -357,6 +405,10 @@ class XYModem(
|
||||
const val CAN = 0x18
|
||||
const val SUB = 0x1a
|
||||
const val C = 'C'.code
|
||||
const val G = 'G'.code
|
||||
const val START_CHECKSUM = 0
|
||||
const val START_CRC = 1
|
||||
const val START_G = 2
|
||||
const val MAX_ERRORS = 10
|
||||
}
|
||||
}
|
||||
@@ -285,6 +285,8 @@ class ZModem(
|
||||
fun zrinit() = sendHex(Header.flags(ZRINIT, CANFDX or CANOVIO or CANFC32))
|
||||
zrinit()
|
||||
var lastHeaderAt = monotonicMs()
|
||||
// (the last file skipped: its stream's ZEOF, if our ZSKIP was lost, answered again)
|
||||
var skipped = false
|
||||
while (true) {
|
||||
val h = try {
|
||||
readHeader()
|
||||
@@ -313,7 +315,11 @@ class ZModem(
|
||||
sendHex(Header(ZNAK))
|
||||
continue
|
||||
}
|
||||
val name = receiveFile(d.first, into) ?: continue
|
||||
// (a skip asked for before this file: not for it)
|
||||
io.takeSkip()
|
||||
val name = receiveFile(d.first, into)
|
||||
skipped = name == null
|
||||
if (name == null) continue
|
||||
names.add(name)
|
||||
report { it.copy(files = it.files + 1) }
|
||||
zrinit()
|
||||
@@ -331,6 +337,7 @@ class ZModem(
|
||||
sendHex(Header.pos(ZCOMPL, 0))
|
||||
}
|
||||
ZFREECNT -> sendHex(Header.pos(ZACK, 0))
|
||||
ZEOF -> if (skipped) sendHex(Header.pos(ZSKIP, 0))
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
@@ -363,6 +370,12 @@ class ZModem(
|
||||
out.use { o ->
|
||||
rpos()
|
||||
loop@ while (true) {
|
||||
// the user's skip: ZSKIP, and the file dropped (the sender goes on to its next)
|
||||
if (io.takeSkip()) {
|
||||
sendHex(Header.pos(ZSKIP, 0))
|
||||
io.purge()
|
||||
break@loop
|
||||
}
|
||||
// (8 KB of a stream with no header in it: ours, at pos, lost; asked for again)
|
||||
val h = readHeader(garbageMax = 8 * 1024, nullOnGarbage = true)
|
||||
if (h == null) {
|
||||
@@ -399,6 +412,7 @@ class ZModem(
|
||||
ZCRCE -> continue@loop
|
||||
// ZCRCG: more follows
|
||||
}
|
||||
if (io.skipWanted) continue@loop
|
||||
}
|
||||
}
|
||||
ZEOF -> {
|
||||
@@ -627,6 +641,7 @@ class ZModem(
|
||||
if (end == ZCRCQ) {
|
||||
sinceAck = 0
|
||||
val to = waitForAck(r.pos)
|
||||
if (to == SKIPPED) return
|
||||
if (to != null) {
|
||||
back(to)
|
||||
continue@resend
|
||||
@@ -652,13 +667,15 @@ class ZModem(
|
||||
}
|
||||
}
|
||||
|
||||
/** a ZCRCQ's answer: null for its ACK, else the position a ZRPOS asks for */
|
||||
/** a ZCRCQ's answer: null for its ACK, [SKIPPED] for a ZSKIP, else the position a ZRPOS asks for */
|
||||
private fun waitForAck(pos: Long): Long? {
|
||||
repeat(MAX_ERRORS) {
|
||||
val h = readHeaderOrNull() ?: return@repeat
|
||||
when (h.type) {
|
||||
ZACK -> return null
|
||||
ZRPOS -> return h.pos
|
||||
// (the receiver skipped the file)
|
||||
ZSKIP -> return SKIPPED
|
||||
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
|
||||
}
|
||||
}
|
||||
@@ -712,6 +729,8 @@ class ZModem(
|
||||
/** bytes between the sender's ZCRCQs (its window) */
|
||||
const val WINDOW = 16 * 1024
|
||||
const val MAX_ERRORS = 10
|
||||
/** [waitForAck]'s answer to a ZSKIP */
|
||||
const val SKIPPED = -2L
|
||||
/** after a ZRPOS, the time the sender's stream from before it may still take to stop coming */
|
||||
const val RPOS_GRACE_MS = 1000L
|
||||
|
||||
|
||||
@@ -77,4 +77,18 @@ class TextTransferTest {
|
||||
assertEquals(0, raw.size)
|
||||
assertTrue(!Protocol.TEXT.batch)
|
||||
}
|
||||
|
||||
/** the line and character delays: the bytes as they were, and the waits they add */
|
||||
@Test
|
||||
fun pacedByTheDelays() = runBlocking {
|
||||
val wire = Bytes()
|
||||
val a = TransferIo { bytes -> wire.write(bytes, 0, bytes.size) }
|
||||
// 4 line ends (CR LF, LF, CR, CR LF) in 14 characters: 4 × 40 + 14 × 5 = 230 ms at the least
|
||||
val paced = "ab\r\ncd\nef\rgh\r\n".encodeToByteArray()
|
||||
val t0 = org.dmodem.app.io.monotonicMs()
|
||||
TextTransfer(a, {}).send(outgoing("p.txt", paced), lineDelayMs = 40, charDelayMs = 5)
|
||||
val took = org.dmodem.app.io.monotonicMs() - t0
|
||||
assertContentEquals(paced, wire.toByteArray())
|
||||
assertTrue(took >= 4 * 40 + paced.size * 5 - 20, "took $took ms")
|
||||
}
|
||||
}
|
||||
@@ -12,11 +12,13 @@ import kotlin.random.Random
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* The transfers both ways in memory, the sender's line the receiver's
|
||||
* (common Kotlin: the JVM, and natively as iOS has it): XMODEM, YMODEM,
|
||||
* ZMODEM and Kermit, each file as it was sent; Kermit's dates.
|
||||
* YMODEM-G, ZMODEM and Kermit, each file as it was sent; a file skipped
|
||||
* (ZMODEM, Kermit); Kermit's dates.
|
||||
*/
|
||||
class TransferLoopbackTest {
|
||||
/** files in memory, and what came */
|
||||
@@ -97,6 +99,51 @@ class TransferLoopbackTest {
|
||||
assertContentEquals(small, m.files.getValue("small.txt").toByteArray())
|
||||
}
|
||||
|
||||
/** YMODEM-G: a batch of two streamed with no ACKs, each file whole */
|
||||
@Test
|
||||
fun ymodemG() {
|
||||
val m = Memory()
|
||||
val names = both({ XYModem(it).sendY(listOf(outgoing("g.bin", data), outgoing("g.txt", small)), g = true) }, { XYModem(it).receiveY(m, g = true) })
|
||||
assertEquals(listOf("g.bin", "g.txt"), names)
|
||||
assertContentEquals(data, m.files.getValue("g.bin").toByteArray())
|
||||
assertContentEquals(small, m.files.getValue("g.txt").toByteArray())
|
||||
}
|
||||
|
||||
/** a YMODEM-G sender asked with C (plain YMODEM): plain YMODEM, each file whole */
|
||||
@Test
|
||||
fun ymodemGSenderToYmodem() {
|
||||
val m = Memory()
|
||||
val names = both({ XYModem(it).sendY(listOf(outgoing("a.bin", data)), g = true) }, { XYModem(it).receiveY(m) })
|
||||
assertEquals(listOf("a.bin"), names)
|
||||
assertContentEquals(data, m.files.getValue("a.bin").toByteArray())
|
||||
}
|
||||
|
||||
/** ZMODEM: the first file skipped part way (ZSKIP), the second whole */
|
||||
@Test
|
||||
fun zmodemSkip() {
|
||||
val m = Memory()
|
||||
val names = both({ ZModem(it).send(listOf(outgoing("a.bin", data), outgoing("b.txt", small))) }, { io ->
|
||||
var asked = false
|
||||
ZModem(io, { p -> if (!asked && p.file == "a.bin" && p.bytes > 8000) { asked = true; io.requestSkip() } }).receive(m)
|
||||
})
|
||||
assertEquals(listOf("b.txt"), names)
|
||||
assertTrue("a.bin" !in m.files)
|
||||
assertContentEquals(small, m.files.getValue("b.txt").toByteArray())
|
||||
}
|
||||
|
||||
/** Kermit: the first file skipped part way (X in the ACK), the second whole */
|
||||
@Test
|
||||
fun kermitSkip() {
|
||||
val m = Memory()
|
||||
val names = both({ Kermit(it).send(listOf(outgoing("a.bin", data), outgoing("b.txt", small))) }, { io ->
|
||||
var asked = false
|
||||
Kermit(io, { p -> if (!asked && p.file == "a.bin" && p.bytes > 8000) { asked = true; io.requestSkip() } }).receive(m)
|
||||
})
|
||||
assertEquals(listOf("b.txt"), names)
|
||||
assertTrue("a.bin" !in m.files)
|
||||
assertContentEquals(small, m.files.getValue("b.txt").toByteArray())
|
||||
}
|
||||
|
||||
/** Kermit: a batch of two, each file whole, with its time there and back */
|
||||
@Test
|
||||
fun kermit() {
|
||||
|
||||
Reference in new issue
Block a user