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:
Claude committed 2026-11-20 22:36:30 +00:00
1 parent 29e5687685
commit a2c364d2b8
17 files changed
+426 -50

No files matched your search

@@ -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() {