Android串口通讯

所谓的安卓串口(Android Uart/Serial Port),通用异步接收和发送器(UART)是一种很常见的,简单的和有用的串行通信接口,常见的串口类型如RS232、RS485,测、常见波特率如9600,19200,38400,115200等

添加依赖

implementation 'com.aill:AndroidSerialPort:1.0.8'

打开串口

/**
 * @param 1 串口地址,这里以/dev/ttyS1为例
 * @param 2 波特率
 * @param 3 flags 给0就好
 */
SerialPort serialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);

代码示例

class SerialPortManager {

    /**串口操作对象*/
    private var serialPort: SerialPort? = null

    /**流读取*/
    private var outputStream: OutputStream? = null
    private var inputStream: InputStream? = null

    /**线程状态,为了安全终止线程*/
    var threadStatus = true

    /**串口读取数据线程*/
    private var redThread: ReadThread? = null

    /**读取数据回调*/
    private var onDataReceive: (data: String) -> Unit = {}

    /**
     * 打开串口
     */
    fun openSerialPort(
        path: String,
        baudrate: Int,
        onDataReceive: (data: String) -> Unit
    ): Boolean {
        try {
            serialPort = SerialPort(File(path), baudrate, 0)
            //获取打开的串口中的输入输出流,以便于串口数据的收发
            inputStream = serialPort?.inputStream
            outputStream = serialPort?.outputStream
            this.onDataReceive = onDataReceive
            //开启线程读取串口数据
            redThread = ReadThread().also {
                it.start()
            }
        } catch (e: IOException) {
            L.e("openSerialPort: 打开串口异常:$e")
            return false
        }
        L.e("$path 串口打开成功")
        return true
    }

    /**
     * 单开一线程,来读数据
     */
    private inner class ReadThread : Thread() {
        override fun run() {
            super.run()
            //判断进程是否在运行,更安全的结束进程
            while (threadStatus) {
                try {
                    SystemClock.sleep(800)
                    val buffer = ByteArray( 1024)
                    var size: Int
                    //读取数据的大小
                    size = inputStream!!.read(buffer)
                    if (size > 0) {
                        onDataReceive(
                            ConversionUtils.hexToString(
                                ConversionUtils.bytesToHexString(
                                    buffer
                                )
                            )
                        )
                    }
                } catch (e: IOException) {
                    L.e("run: 串口数据读取异常:$e")
                }
            }
        }
    }

    /**
     * 关闭串口
     */
    fun closeSerialPort() {
        try {
            inputStream?.close()
            outputStream?.close()
            threadStatus = false
            redThread?.interrupt()
            serialPort?.close()
        } catch (e: Exception) {
            L.e("关闭串口异常:${e.message}")
        }
    }
}