參考資料:
https://blog.csdn.net/xuanshao_/article/details/105722891 (分包處理)
https://www.jianshu.com/p/9249ed03e745
https://www.cnblogs.com/tangchun/p/10695894.html
GitHUb地址:
https://github.com/AIlll/AndroidSerialPort
AndroidSerialPort
Android 串口通信,基於谷歌官方android-serialport-api編譯
使用說明
- 在Module下的 build.gradle 中添加
implementation 'com.aill:AndroidSerialPort:1.0.8'
- 打開串口
/**
* @param 1 串口路徑 * @param 2 波特率 * @param 3 flags 給0就好 */ SerialPort serialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);
- 往串口中寫入數據
//從串口對象中獲取輸出流 OutputStream outputStream = serialPort.getOutputStream(); //需要寫入的數據 byte[] data = new byte[x]; data[0] = ...; data[1] = ...; data[x] = ...; //寫入數據 outputStream.write(data); outputStream.flush();
- 讀取串口數據
讀取數據時很可能會遇到分包的情況,即不能一次性讀取正確的完整的數據
解決辦法:可以在讀取到數據時,讓讀取數據的線程sleep一段時間,等待數據全部接收完,再一次性讀取出來。這樣應該可以避免大部分的分包情況
//從串口對象中獲取輸入流 InputStream inputStream = serialPort.getInputStream(); //使用循環讀取數據,建議放到子線程去 while (true) { if (inputStream.available() > 0) { //當接收到數據時,sleep 500毫秒(sleep時間自己把握) Thread.sleep(500); //sleep過后,再讀取數據,基本上都是完整的數據 byte[] buffer = new byte[inputStream.available()]; int size = inputStream.read(buffer); } }
- 修改設備
su
路徑
打開串口時,會檢測讀寫權限,當沒有權限時,會嘗試對其進行提權
//默認su路徑是/system/bin/su,有些設備su路徑是/system/xbin/su //在new SerialPort();之前設置su路徑 SerialPort.setSuPath("/system/xbin/su");
- ByteUtil類:工具類,字符串轉字節數組,字節數組轉字符串
- SerialFinder類:用於查找設備下所有串口路徑