库源码在https://github.com/F1ReKing/Android-SerialPort
前言
最近几个月一直有持续在做跟硬件串口数据通信的项目,一开始用的是谷歌官方串口库android-serialport-api,简单地封装了接口,但硬件部门要求配置做下流控测试,但该项目仅支持串口名称及波特率,所以在谷歌项目的基础上添加支持数据位、数据位、停止位、流控等配置,想想还是整理下开源出来做下贡献,帮助下有需要的人。
此项目没做协议解析,协议解析部分要根据协议做分包处理。
依赖引入
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Step 2. Add the dependency
dependencies {
implementation 'com.github.F1ReKing:Android-SerialPort:1.1'
}
使用
1. 查询串口列表
SerialPortFinder#getDrivers();
2. 配置串口参数
SerialPortHelper#Builder(String port, int baudRate).build(); //支持配置串口号,波特率(默认值115200)
setStopBits(int stopBits); // 支持设置停止位 默认值为2
setDataBits(int dataBits); // 支持设置数据位 默认值为8
setParity(int parity); // 支持设置检验位 默认值为0
setFlowCon(int flowCon); // 支持设置流控 默认值为0
setFlags(int flags); // 支持设置标志 默认值为0,O_RDWR 读写方式打开
3. 打开串口
SerialPortHelper#open();
4. 关闭串口
SerialPortHelper#close();
4. 发送数据
SerialPortHelper#sendBytes(byte[] bytes); // 支持发送byte[]
SerialPortHelper#sendHex(String hex); // 支持发送Hex
SerialPortHelper#sendTxt(String txt); // 支持发送ASCII码
5. 接收数据
public interface ISerialPortDataListener {
// 接收数据回调
void onDataReceived(byte[] bytes);
// 发送数据回调
void onDataSend(byte[] bytes);
}
6. 回调
// 串口打开状态监听
void setIOpenSerialPortListener(IOpenSerialPortListener IOpenSerialPortListener);
// 串口消息监听
void setISerialPortDataListener(ISerialPortDataListener ISerialPortDataListener);
网友评论