Android 串口数据处理
private void getSerialPort() {
if (mReceiveThread == null) {
mReceiveThread = new ReceiveThread();
}
mReceiveThread.start();
}
//开始处理数据
private void startDecodeData() {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
if (mIsAnalyticalData) {
//解析数据
decodeData();
mIsAnalyticalData = !mIsAnalyticalData;
}
}
}
}).start();
}
//解析数据
private void decodeData() {
if (mIsHaveLeft) {
//添加数据 剩下的数据后移
for (int i = mBufferDataLength - 1; i >= 0; i--) {
mBuffer[i + mLeftLength] = mBuffer[i];
}
for (int i = 0; i < mLeftLength; i++) {
mBuffer[i] = mLeftBuffer[i];
}
mBufferDataLength += mLeftLength;
mIsHaveLeft = !mIsHaveLeft;
mLeftLength = 0;
}
String[] HexArr = DataUtils.ByteArr2HexArr(mBuffer, 0, mBufferDataLength);
int endIndex = 0;
for (int i = 0; i < HexArr.length; i++) {
if ((i < HexArr.length)
&& (i + 1 < HexArr.length)
&& (i + Integer.valueOf(HexArr[i + 1], 16) < HexArr.length)
&& (i + 1 + Integer.valueOf(HexArr[i + 1], 16) < HexArr.length)
&& HexArr[i].equals("5A") && HexArr[i + Integer.valueOf(HexArr[i + 1], 16)].equals("0D")
&& HexArr[i + 1 + Integer.valueOf(HexArr[i + 1], 16)].equals("0A")) {
endIndex = i + 1 + Integer.valueOf(HexArr[i + 1], 16);
StringBuffer stringBuffer = new StringBuffer();
for (int j = i + 4, k = 0; k < ((Integer.valueOf(HexArr[i + 1], 16)) - 4); j++, k++) {
stringBuffer.append(HexArr[j]);
}
DataBean dataBean = new DataBean(HexArr[i + 2], HexArr[i + 3], stringBuffer.toString());
decodeDataBean(dataBean);
i += Integer.valueOf(HexArr[i + 1], 16) + 1;
}
}
//有剩余的数据
if (endIndex != mBufferDataLength - 1) {
int j = 0;
for (int i = endIndex + 1; i < mBufferDataLength; i++, j++) {
mLeftBuffer[j] = mBuffer[i];
}
mLeftLength = j;
mIsHaveLeft = true;
}
}
//接收串口数据的线程
private class ReceiveThread extends Thread {
@Override
public void run() {
super.run();
//条件判断,只要条件为true,则一直执行这个线程
while (isStart) {
if (inputStream == null) {
return;
}
byte[] readData = new byte[8192];
try {
int size = inputStream.read(readData);
if (size > 0) {
String readString = DataUtils.ByteArrToHex(readData, 0, size);
for (int i = 0, j = mTempBufferStartPosition; i < size; i++, j++) {
mTempBuffer[j] = readData[i];
}
mTempBufferStartPosition += size;
mTempAddCount++;
//Log.e("LOG_TAG", "" + mTempAddCount);
if (mTempAddCount >= mReceiveMinAmount && (!mIsAnalyticalData)) {
//可以将临时缓冲区的数据copy到处理缓冲区
for (int i = 0; i < mTempBufferStartPosition; i++) {
mBuffer[i] = mTempBuffer[i];
}
mBufferDataLength = mTempBufferStartPosition;
mIsAnalyticalData = !mIsAnalyticalData;
//各种counter归零
mTempAddCount = 0;
mTempBufferStartPosition = 0;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}