定义串口对象、流对象、打开串口
private ByteBuffer mBuffer;
private SerialPort mSerialPort;
private OutputStream mOutputStream;
private InputStream mInputStream;
public boolean init() {
try {
mSerialPort = new android_serialport_api.SerialPort("/dev/ttyS4", 9600, 0);
mOutputStream = mSerialPort.getOutputStream();
mInputStream = mSerialPort.getInputStream();
} catch (Exception e) {
//logger.error("serial open exception.");
e.printStackTrace();
return false;
}
return true;
}
读卡线程
// 读卡信息接收
public byte[] read() {
try {
int len;
if (mInputStream == null) {
return null;
}
byte[] bt = new byte[16];
byte[] tmp = new byte[1];
int idx = 0;
int totalLen = 0;
byte sum = 0;
int ibyte = 0;
while (true) {
len = mInputStream.read(tmp);
if (len <= 0) {
break;
}
Log.d("facepad", "recv buf: " + Integer.toHexString(tmp[0] & 0xFF));
ibyte = (tmp[0] & 0xff);
if (idx == 0) {//起始位
if (ibyte == 0x02) {
bt[0] = tmp[0];
idx++;
sum += tmp[0];
} else {
// 首位不是0x02
Arrays.fill(bt, (byte) 0);
idx = 0;
sum = 0;
totalLen = 0;
}
} else if (idx == 1) {//长度
if (ibyte != 0x09 && ibyte != 0x0a) { // 长度不对,重来
Arrays.fill(bt, (byte) 0);
idx = 0;
sum = 0;
totalLen = 0;
}else {// 长度正确
totalLen = ibyte;
bt[idx] = tmp[0];
idx++;
sum += tmp[0];
}
/*if (ibyte == 0x66 || ibyte == 0x55) {
bt[idx] = tmp[0];
idx++;
sum += tmp[0];
} else {
// 次位不是0x66或0x55
Arrays.fill(bt, (byte) 0);
idx = 0;
sum = 0;
totalLen = 0;
}*/
} else if (idx == 2) {//卡片类型
bt[idx] = tmp[0];
idx++;
sum += tmp[0];
} else {
bt[idx] = tmp[0];
idx++;
if (idx == totalLen) {
byte[] cardMsg = new byte[idx];
System.arraycopy(bt, 0, cardMsg, 0, idx);
if (ibyte == 0x03&&bccCheck(cardMsg)) {
// 合法数据
break;
} else {
// 校验失败
Arrays.fill(bt, (byte) 0);
idx = 0;
sum = 0;
totalLen = 0;
}
}
sum += tmp[0];
}
}
return bt;
} catch (Exception e) {
Log.d("facepad", "serial read exception." + e.toString());
}
Log.d("facepad", "serial read failed");
return null;
}
bcc校验
private boolean bccCheck(byte[] data) {
String bcc = "";
byte BCC[] = new byte[1];
for (int i = 1; i < data.length - 2; i++) {
BCC[0] = (byte) (BCC[0] ^ data[i]);
}
String hex = Integer.toHexString(BCC[0] & 0xFF);
// if (hex.length() == 1) {
// hex = '0' + hex;
// }
bcc += hex.toUpperCase();
String flg = Integer.toHexString(data[data.length - 2] & 0xFF);
return flg.toUpperCase().equals(bcc);
}