1.添加依赖
Kotlin
implementation("io.github.xmaihh:serialport:2.1.1")
2.添加SerialHelper派生类
Kotlin
class SerialPortHelper(portName:String,baudRate:Int): SerialHelper(portName,baudRate) {
var receivedDataBuffer = mutableListOf<Byte>()
override fun onDataReceived(paraComBean: ComBean?) {
if(paraComBean!=null)
{
var temp:ByteArray = paraComBean.bRec;
receivedDataBuffer.addAll(temp.toList())
//receivedDataBuffer.addAll(paraComBean.toList())
}
}
init {
setStickPackageHelper (object : AbsStickPackageHelper {
override fun execute(isStream: InputStream?): ByteArray? {
try {
val available = isStream?.available()
if (available != null) {
if (available > 0) {
val buffer = ByteArray(available)
val size = isStream.read(buffer)
if (size > 0) {
return buffer
}
} else {
// 若没有数据,等待50毫秒
Thread.sleep(50)
}
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
return null
}
})
}
}
3.创建串口处理类
Kotlin
class SericalCommunicate {
var serialPort:SerialPortHelper? = null
//var outputSeriaPort = mutableStateOf("/dev/ttyS0")
var serialportName:MutableState<String> = mutableStateOf("/dev/ttyS0")
var serialBaud:MutableState<Int> = mutableStateOf(115200)
init {
initSerialport()
}
@OptIn(ExperimentalStdlibApi::class)
fun initSerialport()
{
try {
serialPort = SerialPortHelper(serialportName.value,serialBaud.value)//SerialPort(File(serialportName.value),serialBaud.value,'N',8,)
}catch (e:Exception)
{
e.printStackTrace()
}
GlobalScope.launch {
val buffer = ByteArray(1024)
while(serialPort!=null)
{
val reader = serialPort!!.receivedDataBuffer
if(reader!=null) {
var length = reader!!.size
if (length>0)
{
val data = String(buffer, 0, length)
var dataStr = data.toByteArray().toHexString()
Log.d("scoreInfo", dataStr)
}
serialPort!!.receivedDataBuffer.clear()
}
delay(50)
}
}
}
fun SetSerialPara(){
reConnectedSerial()
}
fun reConnectedSerial()
{
if(serialPort!=null) {
serialPort?.close()
serialPort = null
}
initSerialport()
}
fun sendDataFromSerialport(data:ByteArray)
{
if(serialPort!=null)
{
serialPort!!.send(data)
}
}
}