我正在开发一个 Android 应用程序,我必须通过串行链路发送和接收数据,准确地说是 UART。
我的 UART 处理类以这个函数为中心:
fun receive(expectedLength: Int, timeout: Int): ByteArray {
// println("Should receive $expectedLength bytes within $timeout ms")
var read_bytes = 0
var ret: Int
var readBuffer: ByteArray = byteArrayOf()
var start_millis: Long
start_millis = System.currentTimeMillis()
while (read_bytes < expectedLength && (System.currentTimeMillis() - start_millis < timeout) ) {
if (uart.inputStream.available() == 0) {
ret = -1
Thread.sleep(10)
} else {
ret = uart.inputStream.read()
}
if (ret >= 0 ) {
readBuffer = readBuffer.plus(ret.toByte())
read_bytes++
start_millis = System.currentTimeMillis()
}
}
return readBuffer
} // receive expected length with timeout
expectedLength在现实生活中,此功能存在几个问题,例如“消息”可能比更糟糕的是,反过来)或可能需要稍长的时间才能到达。
所有这些都转化为整个应用程序中的一连串错误,其中各种服务只能在通信/硬件错误下进行处理。即使重试也不安全。
有替代方法吗?