From d699982f2e4f2cfd50e9a0f01fab83d2ec21f04a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 25 Oct 2026 07:25:04 +0000 Subject: [PATCH] File transfers: Intel HEX and Motorola S-records Two more ways to send and receive a file, for EPROM programmers, monitor ROMs and boot loaders on a plain serial line: HexRecords encodes an image as Intel HEX (16-byte data records, an extended linear address at each 64 KB, the end record) or S-records (an S0 header of the file's name, S1/S2/S3 by the image's end, S5's count, S7/S8/S9) and decodes them back, checksums and lengths checked, other lines (prompts, echoes) passed over, gaps as an erased EPROM's 0xFF. HexTransfer sends a file a record a line (a file of the format's records already, as it is), and receives the records until the end record (or a 10 s pause once they've come) into the image they hold. Protocol INTEL_HEX and SREC: the terminal's send and receive dialogs (with what each does), iOS's transfers too. A cancel sends nothing: there's no protocol to tell. HexRecordsTest (JVM and native): Intel's and the S-record examples, images there and back at three base addresses, address sizes, gaps, wrong checksums, and sent and received on a line through Transfer. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs --- README.md | 11 +- .../com/neodesktop/dmodem/ui/TransferUi.kt | 10 + .../neodesktop/dmodem/transfer/HexRecords.kt | 314 ++++++++++++++++++ .../neodesktop/dmodem/transfer/Transfer.kt | 18 + .../dmodem/transfer/HexRecordsTest.kt | 144 ++++++++ 5 files changed, 495 insertions(+), 2 deletions(-) create mode 100644 shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/HexRecords.kt create mode 100644 shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt diff --git a/README.md b/README.md index 730d5be..18ca2b5 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,12 @@ this line. Home/End/PgUp/PgDn, F1-F12), volume keys as font size or Ctrl/Alt, bell as vibration or flash, full screen, snippets, session capture to a file (shared to other apps), hang up (+++ with its guard times, ATH). + Files sent and received by ZMODEM, YMODEM, XMODEM(-1K) and Kermit, and + as Intel HEX or Motorola S-records for EPROM programmers, monitors and + boot loaders: a file sent as records (a file of them already, as it is: + S1/S2/S3 by the image's size, Intel's extended addresses past 64 KB), + records received with their checksums checked into the binary image + they hold (gaps 0xFF). - **Dial**: the dialing directory: each system's number (or SIP user), the AT commands it needs before ATD, its character set and backspace; one tap starts the modem if it is off and dials. @@ -269,7 +275,7 @@ Android's JNI), with D-Modem-RE, libre and Mbed TLS as one XCFramework: The Kotlin the two apps share is `shared/` (Kotlin Multiplatform: the JVM for Android, iOS's framework `DModemShared`; Linux native for its -tests): the terminal's emulator, the file transfers (X/Y/ZMODEM, Kermit), +tests): the terminal's emulator, the file transfers (X/Y/ZMODEM, Kermit, Intel HEX and S-records), PPP (its client and server, the chat scripts), fax (T.4, T.30, class 1, the PDF) and the line to another phone (PeerLine), on a small common I/O layer (`shared/.../io`). What stays each app's own: the UI, the modem @@ -285,7 +291,8 @@ offered and found with Bonjour (`_dmodem._tcp`, as Android's NSD). It has: hang up, stop, an AT command line, the log - the terminal (the shared emulator drawn in SwiftUI, CP437 and the VGA colours, Esc/Ctrl/Tab/arrows) and its file transfers (ZMODEM, YMODEM, - XMODEM, Kermit; a remote's `sz` or `kermit -s` starts one by itself) + XMODEM, Kermit, Intel HEX, S-records; a remote's `sz` or `kermit -s` + starts one by itself) - Fax: PDFs, images and text sent; a ringing call answered as a fax, by hand or each one; the received faxes as PDFs - Internet: dial-up to an ISP (its login script if it has one, PPP), the diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/TransferUi.kt b/app/src/main/java/com/neodesktop/dmodem/ui/TransferUi.kt index 92c22d8..0b2adbc 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/TransferUi.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/TransferUi.kt @@ -80,6 +80,16 @@ fun TransferDialog( 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), " + + "for an EPROM programmer, a monitor or a boot loader." + else "The records that come (their checksums checked) are saved as the binary image they hold, " + + "gaps as 0xFF: from the end record, or once they pause for 10 s.", + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 4.dp), + ) + } } }, confirmButton = { diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/HexRecords.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/HexRecords.kt new file mode 100644 index 0000000..0f8e38e --- /dev/null +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/HexRecords.kt @@ -0,0 +1,314 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.transfer + +import com.neodesktop.dmodem.io.IOException + +/** + * Intel HEX and Motorola S-records: a binary image as lines of text, each + * a record of an address, its data and a checksum, for EPROM programmers, + * monitor ROMs and boot loaders, which take them on a plain serial line. + * + * Intel HEX: ":" count, address, type, data, checksum (the two's + * complement of the bytes' sum); types 00 data, 01 the end, 02 an extended + * segment address (×16), 04 an extended linear address (the upper 16 + * bits), 03 and 05 a start address (taken, unused). + * + * S-records: "S" type, count (address, data and checksum's bytes), + * address, data, checksum (the one's complement of the bytes' sum); S0 a + * header, S1/S2/S3 data at 16/24/32-bit addresses, S5/S6 the count of + * data records, S7/S8/S9 the end (with a start address). + */ +object HexRecords { + enum class Format { INTEL, SREC } + + /** the data records' size */ + const val RECORD_BYTES = 16 + + /** [data] at [base] as [format]'s records, the end record last (S-records: a header of [name] first) */ + fun encode(data: ByteArray, format: Format, base: Long = 0, name: String = ""): List = + when (format) { + Format.INTEL -> intel(data, base) + Format.SREC -> srec(data, base, name) + } + + private fun intel(data: ByteArray, base: Long): List { + val out = ArrayList() + var upper = -1L + var i = 0 + while (i < data.size) { + val addr = base + i + // (a record doesn't cross a 64 KB boundary: its extended address first when it changes) + if (addr ushr 16 != upper) { + upper = addr ushr 16 + out.add(intelRecord(0, 4, byteArrayOf((upper ushr 8).toByte(), upper.toByte()))) + } + val room = (0x10000 - (addr and 0xffff)).toInt() + val n = minOf(RECORD_BYTES, data.size - i, room) + out.add(intelRecord((addr and 0xffff).toInt(), 0, data.copyOfRange(i, i + n))) + i += n + } + out.add(":00000001FF") + return out + } + + private fun intelRecord(addr: Int, type: Int, data: ByteArray): String { + val bytes = byteArrayOf(data.size.toByte(), (addr ushr 8).toByte(), addr.toByte(), type.toByte()) + data + val sum = bytes.sumOf { it.toInt() and 0xff } + return ":" + hex(bytes) + hex(byteArrayOf((-sum).toByte())) + } + + private fun srec(data: ByteArray, base: Long, name: String): List { + val last = base + maxOf(data.size, 1) - 1 + // (the smallest addresses that hold the image: S1 16 bits, S2 24, S3 32) + val (dataType, addrBytes, endType) = when { + last <= 0xffff -> Triple(1, 2, 9) + last <= 0xffffff -> Triple(2, 3, 8) + else -> Triple(3, 4, 7) + } + val out = ArrayList() + out.add(srecRecord(0, 2, 0, name.encodeToByteArray().take(60).toByteArray())) + var i = 0 + var count = 0 + while (i < data.size) { + val n = minOf(RECORD_BYTES, data.size - i) + out.add(srecRecord(dataType, addrBytes, base + i, data.copyOfRange(i, i + n))) + i += n + count++ + } + if (count <= 0xffff) out.add(srecRecord(5, 2, count.toLong(), ByteArray(0))) + out.add(srecRecord(endType, addrBytes, base, ByteArray(0))) + return out + } + + private fun srecRecord(type: Int, addrBytes: Int, addr: Long, data: ByteArray): String { + val a = ByteArray(addrBytes) { k -> (addr ushr (8 * (addrBytes - 1 - k))).toByte() } + val body = byteArrayOf((addrBytes + data.size + 1).toByte()) + a + data + val sum = body.sumOf { it.toInt() and 0xff } + return "S$type" + hex(body) + hex(byteArrayOf((sum.inv()).toByte())) + } + + private val DIGITS = "0123456789ABCDEF" + + private fun hex(b: ByteArray): String = buildString(b.size * 2) { + for (x in b) { + append(DIGITS[(x.toInt() ushr 4) and 15]) + append(DIGITS[x.toInt() and 15]) + } + } + + /** whether [text] is [format]'s records already (every line one, the end record among them): sent as it is */ + fun isRecords(text: String, format: Format): Boolean { + val d = Decoder(format) + for (raw in text.lineSequence()) { + val l = raw.trim() + if (l.isEmpty()) continue + val ok = try { d.line(l) } catch (_: IOException) { false } + if (!ok && !d.ended) return false + } + return d.ended + } + + /** + * Records read a line at a time ([line]): the data at their addresses, + * until the end record ([ended]). Lines that aren't records (a prompt, + * an echo) are passed over; a record whose checksum or length is wrong + * is an error. + */ + class Decoder(private val format: Format) { + /** the data, by address */ + private val chunks = ArrayList>() + var ended = false + private set + /** data records taken */ + var records = 0 + private set + /** the data's bytes so far */ + var bytes = 0L + private set + /** the S0 header's text, if any */ + var header = "" + private set + private var upper = 0L + + /** a line: true if it was a record of the format (an error if it's a bad one) */ + fun line(raw: String): Boolean { + val l = raw.trim() + if (ended || l.isEmpty()) return false + return when (format) { + Format.INTEL -> intel(l) + Format.SREC -> srec(l) + } + } + + private fun bytesOf(digits: String, what: String): ByteArray { + if (digits.length % 2 != 0 || digits.any { it !in '0'..'9' && it !in 'A'..'F' && it !in 'a'..'f' }) { + throw IOException("$what: not hex digits") + } + return ByteArray(digits.length / 2) { k -> digits.substring(2 * k, 2 * k + 2).toInt(16).toByte() } + } + + private fun intel(l: String): Boolean { + if (!l.startsWith(":")) return false + val b = bytesOf(l.substring(1), "Intel HEX record ${records + 1}") + if (b.size < 5 || b.size != (b[0].toInt() and 0xff) + 5) throw IOException("Intel HEX: a record's length is wrong: $l") + if ((b.sumOf { it.toInt() and 0xff } and 0xff) != 0) throw IOException("Intel HEX: a checksum is wrong: $l") + val n = b[0].toInt() and 0xff + val addr = ((b[1].toInt() and 0xff) shl 8) or (b[2].toInt() and 0xff) + val data = b.copyOfRange(4, 4 + n) + when (b[3].toInt() and 0xff) { + 0 -> put(upper + addr, data) + 1 -> ended = true + 2 -> upper = (((data[0].toInt() and 0xff) shl 8) or (data[1].toInt() and 0xff)).toLong() shl 4 + 4 -> upper = (((data[0].toInt() and 0xff) shl 8) or (data[1].toInt() and 0xff)).toLong() shl 16 + 3, 5 -> {} + else -> throw IOException("Intel HEX: an unknown record type: $l") + } + return true + } + + private fun srec(l: String): Boolean { + if (l.length < 2 || (l[0] != 'S' && l[0] != 's') || !l[1].isDigit()) return false + val type = l[1] - '0' + val b = bytesOf(l.substring(2), "S-record ${records + 1}") + if (b.isEmpty() || b.size != (b[0].toInt() and 0xff) + 1) throw IOException("S-record: a record's length is wrong: $l") + if ((b.sumOf { it.toInt() and 0xff } and 0xff) != 0xff) throw IOException("S-record: a checksum is wrong: $l") + val addrBytes = when (type) { + 0, 1, 5, 9 -> 2 + 2, 6, 8 -> 3 + 3, 7 -> 4 + else -> throw IOException("S-record: an unknown type: $l") + } + if (b.size < 1 + addrBytes + 1) throw IOException("S-record: too short: $l") + var addr = 0L + for (k in 0 until addrBytes) addr = (addr shl 8) or (b[1 + k].toLong() and 0xff) + val data = b.copyOfRange(1 + addrBytes, b.size - 1) + when (type) { + 0 -> header = data.decodeToString().trim { it <= ' ' } + 1, 2, 3 -> put(addr, data) + 5, 6 -> {} + else -> ended = true + } + return true + } + + private fun put(addr: Long, data: ByteArray) { + chunks.add(addr to data) + records++ + bytes += data.size + } + + /** the lowest address with data (0 for none) */ + val start: Long get() = chunks.minOfOrNull { it.first } ?: 0 + + /** + * the image from the lowest address to the end of the highest + * record, gaps as an erased EPROM has them (0xFF) + */ + fun image(): ByteArray { + if (chunks.isEmpty()) return ByteArray(0) + val first = chunks.minOf { it.first } + val end = chunks.maxOf { it.first + it.second.size } + if (end - first > MAX_IMAGE) throw IOException("the records span ${end - first} bytes: too many for an image") + val out = ByteArray((end - first).toInt()) { 0xff.toByte() } + // (in the order they came: a record written again wins) + for ((a, d) in chunks) d.copyInto(out, (a - first).toInt()) + return out + } + } + + /** the largest image put together (64 MB) */ + const val MAX_IMAGE = 64L shl 20 +} + +/** + * A hex records transfer on a line: no protocol but the records' own + * checksums. Sending: the file as records, a line each (CR LF), or as it + * is if it's the format's records already. Receiving: the records that + * come, until the end record (or a pause once some have come), as the + * binary image they hold. + */ +class HexTransfer( + private val io: TransferIo, + private val format: HexRecords.Format, + private val progress: (Progress) -> Unit, +) { + /** [file] sent */ + fun send(file: Outgoing) { + val data = readAll(file) + val text = data.decodeToString() + val lines = if (HexRecords.isRecords(text, format)) { + text.lineSequence().map { it.trim() }.filter { it.isNotEmpty() }.toList() + } else { + HexRecords.encode(data, format, 0, file.name) + } + val total = lines.sumOf { it.length + 2L } + var sent = 0L + for (l in lines) { + if (io.isCancelled) throw TransferCancelled("cancelled") + io.write((l + "\r\n").encodeToByteArray()) + sent += l.length + 2 + progress(Progress(file.name, sent, total)) + } + progress(Progress(file.name, sent, total, files = 1)) + } + + /** the records received, their image into [into] as [name]: its name there */ + fun receive(into: Incoming, name: String): List { + val d = HexRecords.Decoder(format) + val line = StringBuilder() + while (!d.ended) { + val c = io.read(if (d.records == 0) FIRST_MS else PAUSE_MS) + if (c < 0) { + if (d.records == 0) throw IOException("no ${label()} records came") + // (a sender that sends no end record: done once it pauses) + break + } + if (c == '\r'.code || c == '\n'.code) { + if (line.isNotEmpty()) { + d.line(line.toString()) + line.setLength(0) + progress(Progress(name, d.bytes)) + } + } else if (line.length < MAX_LINE) { + line.append(c.toChar()) + } + } + val image = d.image() + val (sink, got) = into.create(name, image.size.toLong()) + try { + sink.write(image) + sink.close() + } catch (e: IOException) { + into.abandon(got) + throw e + } + into.done(got, 0) + progress(Progress(got, image.size.toLong(), image.size.toLong(), files = 1)) + return listOf(got) + } + + private fun label() = if (format == HexRecords.Format.INTEL) "Intel HEX" else "S-record" + + private fun readAll(file: Outgoing): ByteArray { + val out = com.neodesktop.dmodem.io.Bytes() + file.open().use { src -> + val buf = ByteArray(8192) + while (true) { + val n = src.read(buf, 0, buf.size) + if (n < 0) break + out.write(buf, 0, n) + if (out.size > HexRecords.MAX_IMAGE) throw IOException("${file.name}: too big for ${label()}") + } + } + return out.toByteArray() + } + + companion object { + /** how long the first record may take to come (the other side started by hand), and a pause after */ + const val FIRST_MS = 60_000L + const val PAUSE_MS = 10_000L + /** a line longer than any record: the rest of it dropped */ + const val MAX_LINE = 600 + } +} diff --git a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/Transfer.kt b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/Transfer.kt index 366cfc4..53f997d 100644 --- a/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/Transfer.kt +++ b/shared/src/commonMain/kotlin/com/neodesktop/dmodem/transfer/Transfer.kt @@ -14,6 +14,10 @@ enum class Protocol(val label: String, val batch: Boolean) { XMODEM("XMODEM", false), XMODEM_1K("XMODEM-1K", false), KERMIT("Kermit", true), + /** an image as Intel HEX records (an EPROM programmer's, a monitor's): no protocol but their checksums */ + INTEL_HEX("Intel HEX", false), + /** the same as Motorola S-records */ + SREC("Motorola S-records", false), ; /** what to type at the remote's shell for it to send (the files' names after it), or to receive */ @@ -23,7 +27,17 @@ enum class Protocol(val label: String, val batch: Boolean) { 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" + // (a programmer or a monitor takes them as they come: nothing to type) + INTEL_HEX, SREC -> "" } + + /** the hex records' format, for the two that are */ + val hexFormat: HexRecords.Format? + get() = when (this) { + INTEL_HEX -> HexRecords.Format.INTEL + SREC -> HexRecords.Format.SREC + else -> null + } } /** A transfer's state as it goes, and how it ended. */ @@ -73,6 +87,7 @@ class Transfer( Protocol.YMODEM -> XYModem(io, progress).receiveY(into) 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) } } @@ -84,6 +99,7 @@ class Transfer( 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()) } emptyList() } @@ -115,6 +131,8 @@ class Transfer( sendRaw( when (protocol) { Protocol.KERMIT -> kermit?.cancelBytes() ?: ByteArray(0) + // (no protocol to tell: the records just stop) + Protocol.INTEL_HEX, Protocol.SREC -> ByteArray(0) else -> ZModem.CANCEL }, ) diff --git a/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt new file mode 100644 index 0000000..4e6e512 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/neodesktop/dmodem/transfer/HexRecordsTest.kt @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.transfer + +import com.neodesktop.dmodem.io.Bytes +import com.neodesktop.dmodem.io.IOException +import com.neodesktop.dmodem.io.Sink +import com.neodesktop.dmodem.io.Source +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Intel HEX and S-records ([HexRecords]): the published examples, images + * there and back (across 64 KB, at a base address), their checksums + * checked, other lines passed over; and sent on a line and received + * ([HexTransfer], through [Transfer]). + */ +class HexRecordsTest { + private fun decode(format: HexRecords.Format, lines: List): HexRecords.Decoder = + HexRecords.Decoder(format).apply { for (l in lines) line(l) } + + @Test + fun intelHexAsItsSpecHasIt() { + // (Intel's example: 3 bytes at 0030, then the end) + val lines = HexRecords.encode(byteArrayOf(0x02, 0x33, 0x7a), HexRecords.Format.INTEL, base = 0x30) + assertEquals(listOf(":020000040000FA", ":0300300002337A1E", ":00000001FF"), lines) + val d = decode(HexRecords.Format.INTEL, lines) + assertTrue(d.ended) + assertEquals(0x30L, d.start) + assertContentEquals(byteArrayOf(0x02, 0x33, 0x7a), d.image()) + } + + @Test + fun sRecordsAsTheirExampleHasThem() { + // (the well-known S1 example: 16 bytes at 7AF0) + val d = decode(HexRecords.Format.SREC, listOf("S00F000068656C6C6F202020202000003C", "S1137AF00A0A0D0000000000000000000000000061", "S9030000FC")) + assertTrue(d.ended) + assertEquals("hello", d.header) + assertEquals(0x7af0L, d.start) + assertContentEquals(byteArrayOf(0x0a, 0x0a, 0x0d) + ByteArray(13), d.image()) + } + + @Test + fun imagesThereAndBack() { + val data = Random(7).nextBytes(70_000) + for (format in HexRecords.Format.entries) { + for (base in listOf(0L, 0x8000L, 0x0123_4560L)) { + val lines = HexRecords.encode(data, format, base, "rom.bin") + val d = decode(format, lines) + assertTrue(d.ended, "$format at $base: ended") + assertEquals(base, d.start) + assertContentEquals(data, d.image(), "$format at $base") + assertTrue(HexRecords.isRecords(lines.joinToString("\r\n"), format)) + assertFalse(HexRecords.isRecords(lines.joinToString("\r\n"), HexRecords.Format.entries.first { it != format })) + } + } + // (S-records' address size by the image's end: S1, S2, S3) + assertTrue(HexRecords.encode(ByteArray(16), HexRecords.Format.SREC)[1].startsWith("S1")) + assertTrue(HexRecords.encode(ByteArray(16), HexRecords.Format.SREC, 0x10000)[1].startsWith("S2")) + assertTrue(HexRecords.encode(ByteArray(16), HexRecords.Format.SREC, 0x1000000)[1].startsWith("S3")) + } + + @Test + fun gapsAreErasedEpromAndOtherLinesPassedOver() { + val d = decode( + HexRecords.Format.INTEL, + listOf("> load", ":0100000041BE", "garbage", ":0100040042B9", ":00000001FF"), + ) + assertContentEquals(byteArrayOf(0x41, -1, -1, -1, 0x42), d.image()) + } + + @Test + fun aWrongChecksumIsAnError() { + assertFailsWith { decode(HexRecords.Format.INTEL, listOf(":0300300002337A1F")) } + assertFailsWith { decode(HexRecords.Format.SREC, listOf("S1137AF00A0A0D0000000000000000000000000062")) } + assertFailsWith { decode(HexRecords.Format.INTEL, listOf(":0400300002337A1E")) } + } + + /** files in memory */ + private class Memory : Incoming { + val files = LinkedHashMap() + override fun create(name: String, size: Long): Pair = Bytes().let { b -> files[name] = b; b to name } + } + + private fun outgoing(name: String, data: ByteArray) = Outgoing(name, data.size.toLong(), 0) { + object : Source { + var at = 0 + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (at >= data.size) return -1 + val n = minOf(len, data.size - at) + data.copyInto(b, off, at, at + n) + at += n + return n + } + } + } + + /** [file] sent by [protocol] on one end of a line, received on the other: what came, and the line's text */ + private fun sent(protocol: Protocol, file: Outgoing): Pair = runBlocking { + val mem = Memory() + val text = StringBuilder() + lateinit var b: Transfer + val done = kotlinx.coroutines.CompletableDeferred() + val sentDone = kotlinx.coroutines.CompletableDeferred() + val a = Transfer(protocol, true, { bytes -> text.append(bytes.decodeToString()); b.io.feed(bytes) }, {}, {}) { s, _ -> sentDone.complete(s) } + b = Transfer(protocol, false, { bytes -> a.io.feed(bytes) }, {}, {}) { s, _ -> done.complete(s) } + b.receive(mem, "image.bin") + a.send(listOf(file)) + val r = async(Dispatchers.Default) { done.await() } + assertEquals("", sentDone.await().result) + val end = r.await() + assertEquals("", end.result, "received: ${end.result}") + assertEquals(listOf("image.bin"), end.received) + // (the sender's thread done with it: its end awaited above) + mem to text.toString() + } + + @Test + fun sentAndReceivedOnALine() { + val data = Random(11).nextBytes(5000) + for (p in listOf(Protocol.INTEL_HEX, Protocol.SREC)) { + val (mem, text) = sent(p, outgoing("rom.bin", data)) + assertContentEquals(data, mem.files["image.bin"]!!.toByteArray(), p.label) + // (text records, a line each) + assertTrue(text.endsWith(if (p == Protocol.INTEL_HEX) ":00000001FF\r\n" else "S9030000FC\r\n"), text.takeLast(40)) + } + } + + @Test + fun aFileOfRecordsAlreadyIsSentAsItIs() { + val records = ":0300300002337A1E\n:00000001FF\n" + val (mem, text) = sent(Protocol.INTEL_HEX, outgoing("rom.hex", records.encodeToByteArray())) + assertEquals(":0300300002337A1E\r\n:00000001FF\r\n", text) + assertContentEquals(byteArrayOf(0x02, 0x33, 0x7a), mem.files["image.bin"]!!.toByteArray()) + } +}