@@ -8,6 +8,7 @@ import io.ktor.network.sockets.*
88import io.ktor.utils.io.*
99import kotlinx.coroutines.*
1010import kotlinx.coroutines.CancellationException
11+ import kotlinx.io.readUByte
1112import kotlinx.serialization.SerialName
1213import kotlinx.serialization.Serializable
1314import kotlinx.serialization.json.Json
@@ -21,6 +22,7 @@ import mindustry.world.blocks.logic.SwitchBlock.SwitchBuild
2122import kotlin.concurrent.thread
2223import kotlin.coroutines.resume
2324import kotlin.coroutines.resumeWithException
25+ import kotlin.math.min
2426
2527class ProcessorAccess (
2628 val build : LogicBuild ,
@@ -381,10 +383,11 @@ enum class UartDevice {
381383}
382384
383385@Serializable
384- @SerialName(" uart " )
385- data class UartRequest (
386+ @SerialName(" serial " )
387+ data class SerialRequest (
386388 val device : UartDevice ,
387- val stopOnHalt : Boolean = true ,
389+ val stopOnHalt : Boolean ,
390+ val overrun : Boolean ,
388391) : Request() {
389392 override suspend fun handle (processor : ProcessorAccess , rx : ByteReadChannel , tx : ByteWriteChannel ): Response {
390393 val uart = when (device) {
@@ -396,18 +399,28 @@ data class UartRequest(
396399 throw RuntimeException (" Client disconnected!" )
397400 }
398401
399- val toUart = 0 .until(rx.availableForRead).map { rx.readByte().toUByte() }
400- if (toUart.isNotEmpty()) Log .info(" Sending to $device : $toUart " )
401-
402402 var overflowCount = 0
403403
404404 val fromUart = runOnMainThread {
405405 if (stopOnHalt && processor.resetSwitch.enabled) {
406406 throw RuntimeException (" Processor stopped!" )
407407 }
408- for (byte in toUart) {
409- if (! uart.write(byte)) overflowCount++
408+
409+ rx.readAvailable(1 ) { buffer ->
410+ val bytes = if (overrun) {
411+ buffer.size.toInt()
412+ } else {
413+ min(buffer.size.toInt(), uart.availableForWrite)
414+ }
415+
416+ for (i in 0 .. < bytes) {
417+ val byte = buffer.readUByte()
418+ if (! uart.write(byte, signalOverflow = overrun)) overflowCount++
419+ }
420+
421+ bytes
410422 }
423+
411424 uart.readAll()
412425 }
413426
0 commit comments