MTK 串口在应用中的应用

作为一个工具篇,在后续工作中经常会用到串口测试工具,方便工作中作为测试工具使用。


资料参考

串口的原理基本一致的,没有特别的东西,无论在哪里使用,顶多一层封装。
这里可以参考一下之前的笔记,framework层的应用
串口在framework层的应用

或者 网上太多的demo 封装,可参考下。

串口应用场景

  • 串口,作为一种协议,使用场景无处不在。
  • 我接触的在Android平台上外挂的各种模组通讯用到了串口:功放模组、物联网模组、话筒模组、语音模块模组、各种传感器模组、各种外围设备通讯…

代码分析

串口so文件的载入和配置

在这里插入图片描述

在 build.gradle 文件中配置 .so 库文件


        ndk {
            abiFilters 'armeabi','armeabi-v7a'
        }

本地native 方法

使用到串口,核心三个方法,如下

  • 加载.so 文件
  • 打开串口
  • 关闭串口
   static {
        System.loadLibrary("serial_port");
    }

    private native static FileDescriptor open(String path, int baudrate);

    private native void close();

SerialPort 流封装方法

本地方法,最终通过流来和串口进行通讯的,下面给出 open 的具体操作,方法如下

  public SerialPort(File device, int baudate) throws IOException {
        if (!device.canRead() || !device.canWrite()) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                String cmd = "chmod 777 " + device.getAbsolutePath();
                su.getOutputStream().write(cmd.getBytes());
                su.getOutputStream().flush();
                int waitFor = su.waitFor();
                boolean canRead = device.canRead();
                boolean canWrite = device.canWrite();
                if (waitFor != 0 || !canRead || !canWrite) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mFd = open(device.getAbsolutePath(), baudate);
        if (mFd == null) {
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

其中 open 是native 方法,拿到了文件描述符,就可以进行 流操作了。

完整的SerialPort 代码如下:


import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 串口通信,打开串口,读写数据
 */
public class SerialPort {

    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    static {
        System.loadLibrary("serial_port");
    }

    /**
     * 打开串口
     * @param device
     * @param baudate
     */
    public SerialPort(File device, int baudate) throws IOException {
        if (!device.canRead() || !device.canWrite()) {
            try {
                Process su = Runtime.getRuntime().exec("su");
                String cmd = "chmod 777 " + device.getAbsolutePath();
                su.getOutputStream().write(cmd.getBytes());
                su.getOutputStream().flush();
                int waitFor = su.waitFor();
                boolean canRead = device.canRead();
                boolean canWrite = device.canWrite();
                if (waitFor != 0 || !canRead || !canWrite) {
                    throw new SecurityException();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mFd = open(device.getAbsolutePath(), baudate);
        if (mFd == null) {
            throw new IOException();
        }
        mFileInputStream = new FileInputStream(mFd);
        mFileOutputStream = new FileOutputStream(mFd);
    }

    public boolean isOpened() {
        return mFd == null;
    }

    /**
     * 关闭串口
     */
    public void closePort() {
        if (this.mFd != null) {
            try {
                this.close();
                this.mFd = null;
                this.mFileInputStream = null;
                this.mFileOutputStream = null;
            } catch (Exception var2) {
                var2.printStackTrace();
            }
        }
    }

    public InputStream getInputStream() {
        return mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return mFileOutputStream;
    }

    /**
     * JNI,设备地址和波特率
     */
    private native static FileDescriptor open(String path, int baudrate);

    private native void close();


}

PowerHelper 串口工具封装

这里举例使用一个工具类的封装
在上面已经对串口native 进行了一定的封装 SerialPort ,这里的PowerHelper 实际上是一个业务工具类的封装。 对外释放的方法或者接口类。

打开串口

    fun open() {
        Log.d(TAG," PowerHelper .open()")
        if (serialPort != null) {
            close();
        }
        try {
            serialPort = SerialPort(File("/dev/ttyS1"), 9600);
            Log.d(TAG," PowerHelper .startReadData()")
            startReadData();
        } catch (e: Exception) {
            e.printStackTrace();
            Log.e(TAG,"无法打开电池电量串口")
        }
    }

借助于SerialPort 的构造方法,传递串口的节点和波特率,在构造方法里面不就执行了open 方法,来打开串口的嘛。

读取数据

打开串口后,串口对应的流不就有了嘛,接下来要做的就是 对流的监听和读取了,如下读取串口数据

 private fun startReadData() {
        if (serialPort == null) {
            return;
        }
        isStop = false;
        DISK_IO.execute {
            while (!isStop) {
                val readData = ByteArray(1024)
                val size = serialPort!!.inputStream!!.read(readData)
                val byteList : List<Byte> = readData.slice(0 until size)
                val str = byteList.map { it.toInt().toChar() }.joinToString(separator = "")
                val temp : ByteArray = readData.slice(0 until size).toByteArray()
                if (size >= 18) {
                    val temp : ByteArray = readData.slice(0 until size).toByteArray()
                    val powerData=PowerDataBean(temp.contentToString(),readData[13].toInt(), readData[4].toInt())
                    Log.i(TAG, "result bytes=${temp.contentToString()}")
                    Log.d(TAG," powerLiveData.postValue(powerData) ")
                    powerLiveData.postValue(powerData)
                   /*  val powerData=PowerDataBean(str,readData[13].toInt(), readData[4].toInt())
                    Log.i(TAG, "result bytes=${temp.contentToString()}")
                    Log.d(TAG," powerLiveData.postValue(powerData) ")
                    powerLiveData.postValue(powerData)*/
                }/*else{
                    val powerData=PowerDataBean(str,0, 0)
                    Log.i(TAG, "result bytes=${temp.contentToString()}")
                    Log.i(TAG, "result 异常数据  =${str}")
                    Log.d(TAG," powerLiveData.postValue(powerData) ")
                    powerLiveData.postValue(powerData)
                }*/
                /* val temp : ByteArray = readData.slice(0 until size).toByteArray()
                 if (size >= 18) {
                     Log.d(TAG," temp:"+temp)
                     val powerData=PowerDataBean(temp.contentToString(),readData[13].toInt(), readData[4].toInt())
                     Log.i(TAG, "result bytes=${temp.contentToString()}")
                     Log.d(TAG," powerLiveData.postValue(powerData) ")
                     powerLiveData.postValue(powerData)
                 }else{
                     val powerData=PowerDataBean(temp.contentToString(),0, 0)
                     Log.i(TAG, "result bytes=${temp.contentToString()}")
                     Log.d(TAG," powerLiveData.postValue(powerData) ")
                     powerLiveData.postValue(powerData)
                 }*/
                //Thread.sleep(100)
            }
        }
    }

这里核心内容其实就只有一点,在死循环线程里面 读取 串口数据

 val size = serialPort!!.inputStream!!.read(readData)

拿到数据进行解析,然后针对自己的业务进行处理,比如封装自己数据,从数据里面根据对接的协议进行业务处理等。

停止读取串口数据-关闭串口

这里的逻辑就是关闭死循环读取数据和调用native 方法,关闭串口

private fun stopReadData() {
        isStop = true;
    }

    fun close() {
         powerLiveData.postValue(PowerDataBean());
        stopReadData();
        if (serialPort != null && serialPort!!.isOpened) {
            serialPort!!.closePort();
        }
        serialPort = null;
    }

工具类 如下


import android.serialport.SerialPort
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.fise.ttl.vo.PowerDataBean
import java.io.File
import java.util.concurrent.Executors
object PowerHelper {
    private   val TAG = "PowerHelper"
    var serialPort: SerialPort? = null;
    val powerLiveData = MutableLiveData<PowerDataBean>();
    private val DISK_IO = Executors.newSingleThreadExecutor();
    var isStop = false;
    fun open() {
        Log.d(TAG," PowerHelper .open()")
        if (serialPort != null) {
            close();
        }
        try {
            serialPort = SerialPort(File("/dev/ttyS1"), 9600);
            Log.d(TAG," PowerHelper .startReadData()")
            startReadData();
        } catch (e: Exception) {
            e.printStackTrace();
            Log.e(TAG,"无法打开电池电量串口")
        }
    }

    private fun startReadData() {
        if (serialPort == null) {
            return;
        }
        isStop = false;
        DISK_IO.execute {
            while (!isStop) {
                val readData = ByteArray(1024)
                val size = serialPort!!.inputStream!!.read(readData)
                val byteList : List<Byte> = readData.slice(0 until size)
                val str = byteList.map { it.toInt().toChar() }.joinToString(separator = "")
                val temp : ByteArray = readData.slice(0 until size).toByteArray()
                if (size >= 18) {
                    val temp : ByteArray = readData.slice(0 until size).toByteArray()
                    val powerData=PowerDataBean(temp.contentToString(),readData[13].toInt(), readData[4].toInt())
                    Log.i(TAG, "result bytes=${temp.contentToString()}")
                    Log.d(TAG," powerLiveData.postValue(powerData) ")
                    powerLiveData.postValue(powerData)
                   /*  val powerData=PowerDataBean(str,readData[13].toInt(), readData[4].toInt())
                    Log.i(TAG, "result bytes=${temp.contentToString()}")
                    Log.d(TAG," powerLiveData.postValue(powerData) ")
                    powerLiveData.postValue(powerData)*/
                }/*else{
                    val powerData=PowerDataBean(str,0, 0)
                    Log.i(TAG, "result bytes=${temp.contentToString()}")
                    Log.i(TAG, "result 异常数据  =${str}")
                    Log.d(TAG," powerLiveData.postValue(powerData) ")
                    powerLiveData.postValue(powerData)
                }*/
                /* val temp : ByteArray = readData.slice(0 until size).toByteArray()
                 if (size >= 18) {
                     Log.d(TAG," temp:"+temp)
                     val powerData=PowerDataBean(temp.contentToString(),readData[13].toInt(), readData[4].toInt())
                     Log.i(TAG, "result bytes=${temp.contentToString()}")
                     Log.d(TAG," powerLiveData.postValue(powerData) ")
                     powerLiveData.postValue(powerData)
                 }else{
                     val powerData=PowerDataBean(temp.contentToString(),0, 0)
                     Log.i(TAG, "result bytes=${temp.contentToString()}")
                     Log.d(TAG," powerLiveData.postValue(powerData) ")
                     powerLiveData.postValue(powerData)
                 }*/
                //Thread.sleep(100)
            }
        }
    }


    private fun stopReadData() {
        isStop = true;
    }

    fun close() {
         powerLiveData.postValue(PowerDataBean());
        stopReadData();
        if (serialPort != null && serialPort!!.isOpened) {
            serialPort!!.closePort();
        }
        serialPort = null;
    }

 }

串口工具使用

在上面已经对串口SerialPort 和 串口对外方法封装PowerHelper 进行了总结,剩下的就是在自己的业务中执行工具方法了。 比如在服务中直接打开串口 就可以了。

PowerHelper.open()

这里贴一个实际串口应用,显示串口电量数据,如下:
在这里插入图片描述

总结

  • 串口数据显示需求

上述分析,提供了两个工具类,就已经满足了绝大多数,通过串口获取数据,作为校验、显示的需求。适合所有平台的显示需求,快速接入验证。

  • 这里只有读取数据,为什么没有写入的总结
    本身串口是由读取和写入的,才能算一个完整的串口使用,实际上99% 的需求必须有读写操作才能叫串口通讯的, 这里应该写一个demo 来演示的。 但是通用的工具在MTK平台上是无法实现的,权限原因,无法写一个通用的write 工具方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

野火少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值