AndroidSerialPort
Android 串口通信,基于谷歌官方android-serialport-api編譯
項(xiàng)目github地址:https://github.com/AIlll/AndroidSerialPort
使用說明
- 在Module下的 build.gradle 中添加
//最新版本查看github項(xiàng)目
implementation 'com.aill:AndroidSerialPort:1.0.8'
- 打開串口
/**
* @param 1 串口路徑,根據(jù)你的設(shè)備不同,路徑也不同
* @param 2 波特率
* @param 3 flags 給0就好
*/
SerialPort serialPort = new SerialPort(new File("/dev/ttyS1"), 9600, 0);
- 往串口中寫入數(shù)據(jù)
//從串口對(duì)象中獲取輸出流
OutputStream outputStream = serialPort.getOutputStream();
//需要寫入的數(shù)據(jù)
byte[] data = new byte[x];
data[0] = ...;
data[1] = ...;
data[x] = ...;
//寫入數(shù)據(jù)
outputStream.write(data);
outputStream.flush();
- 讀取串口數(shù)據(jù)
讀取數(shù)據(jù)時(shí)很可能會(huì)遇到分包的情況,即不能一次性讀取正確的完整的數(shù)據(jù)
解決辦法:可以在讀取到數(shù)據(jù)時(shí),讓讀取數(shù)據(jù)的線程sleep一段時(shí)間,等待數(shù)據(jù)全部接收完,再一次性讀取出來。這樣應(yīng)該可以避免大部分的分包情況
//從串口對(duì)象中獲取輸入流
InputStream inputStream = serialPort.getInputStream();
//使用循環(huán)讀取數(shù)據(jù),建議放到子線程去
while (true) {
if (inputStream.available() > 0) {
//當(dāng)接收到數(shù)據(jù)時(shí),sleep 500毫秒(sleep時(shí)間自己把握)
Thread.sleep(500);
//sleep過后,再讀取數(shù)據(jù),基本上都是完整的數(shù)據(jù)
byte[] buffer = new byte[inputStream.available()];
int size = inputStream.read(buffer);
}
}
只接收一條數(shù)據(jù)的情況下,以上方法可以應(yīng)對(duì)數(shù)據(jù)分包,數(shù)據(jù)量多的情況下需要考慮是否會(huì)因?yàn)閟leep導(dǎo)致接收多條數(shù)據(jù),可以根據(jù)通信協(xié)議核對(duì)包頭包尾等參數(shù)。
- 修改設(shè)備
su路徑
打開串口時(shí),會(huì)檢測(cè)讀寫權(quán)限,當(dāng)沒有權(quán)限時(shí),會(huì)嘗試對(duì)其進(jìn)行提權(quán)
//默認(rèn)su路徑是/system/bin/su,有些設(shè)備su路徑是/system/xbin/su
//在new SerialPort();之前設(shè)置su路徑
SerialPort.setSuPath("/system/xbin/su");
- ByteUtil類:工具類,字符串轉(zhuǎn)字節(jié)數(shù)組,字節(jié)數(shù)組轉(zhuǎn)字符串
- SerialFinder類:用于查找設(shè)備下所有串口路徑