desc:串口读取和写分不同线程

main
xiaowusky 1 year ago
parent 528202a9cb
commit 0fceb7129d

@ -38,7 +38,9 @@ object GasPortUtils {
listeners.forEach { listeners.forEach {
it.invoke(array) it.invoke(array)
} }
ParseHelper.parse(array) if (array[0].toInt() == 0x01 && array[1].toInt() == 0x03 && array[2].toInt() == 0x14) {
ParseHelper.parse(array)
}
} }
} }
} }

@ -10,7 +10,7 @@ class EasySerialPort<T>(
private val baudRate: Int, private val baudRate: Int,
private val helper: ISerialPortHelper<T>, private val helper: ISerialPortHelper<T>,
private val mReceiver: (ByteArray) -> Unit private val mReceiver: (ByteArray) -> Unit
) { ) : Runnable {
private var mStartReceiveMsg = true private var mStartReceiveMsg = true
private var mAutoRetryConnect = false private var mAutoRetryConnect = false
@ -24,6 +24,10 @@ class EasySerialPort<T>(
private fun openSerialPort() { private fun openSerialPort() {
val mPort = helper.openSerialPort(portPath, baudRate) val mPort = helper.openSerialPort(portPath, baudRate)
mPort?.let {
mStartReceiveMsg = true
Thread(this).start()
}
} }
/** /**
@ -34,6 +38,35 @@ class EasySerialPort<T>(
helper.closePort() helper.closePort()
} }
/**
* 循环读消息
*/
override fun run() {
while (mStartReceiveMsg) {
try {
val ips = helper?.inputStream()
val size = ips?.read(mReadBytes)
if (size != null) {
if (size > 0) {
Log.i("EasySerialPort", "read msg ${HexUtils.byteArrToHex(mReadBytes)}")
mReceiver.invoke(mReadBytes)
}
}
Thread.sleep(100L)
} catch (e: IOException) {
Log.e(
"EasySerialPort",
"read msg error; path = " + portPath + ", error msg = " + e.message
)
e.printStackTrace()
if (mAutoRetryConnect) {
closePort()
openSerialPort()
}
}
}
}
/** /**
* 写消息 * 写消息
*/ */
@ -44,25 +77,25 @@ class EasySerialPort<T>(
outputStream?.write(data) outputStream?.write(data)
outputStream?.flush() outputStream?.flush()
Log.i("EasySerialPort", "send msg ${HexUtils.byteArrToHex(data)}") Log.i("EasySerialPort", "send msg ${HexUtils.byteArrToHex(data)}")
var offset = 1 // var offset = 1
if (data[0] ==0xFF.toByte()){ // if (data[0] == 0xFF.toByte()) {
offset = 2 // offset = 2
} // }
val cmd = data[offset] // val cmd = data[offset]
// 写完之后读取数据 // // 写完之后读取数据
val ips = helper?.inputStream() // val ips = helper?.inputStream()
val size = ips?.read(mReadBytes) // val size = ips?.read(mReadBytes)
if (size != null) { // if (size != null) {
if (size > 0) { // if (size > 0) {
Log.i( // Log.i(
"EasySerialPort", // "EasySerialPort",
"cmd $cmd ;read msg ${HexUtils.byteArrToHex(mReadBytes)}" // "cmd $cmd ;read msg ${HexUtils.byteArrToHex(mReadBytes)}"
) // )
if (mReadBytes[0].toInt() == 0x01 && mReadBytes[1].toInt() == 0x03 && mReadBytes[2].toInt() == 0x14) { // if (mReadBytes[0].toInt() == 0x01 && mReadBytes[1].toInt() == 0x03 && mReadBytes[2].toInt() == 0x14) {
mReceiver.invoke(mReadBytes) // mReceiver.invoke(mReadBytes)
} // }
} // }
} // }
} catch (e: IOException) { } catch (e: IOException) {
Log.e( Log.e(
"EasySerialPort", "EasySerialPort",

Loading…
Cancel
Save