這段代碼是我的接收資料的代碼,外邊放了個執行緒回圈執行,但是在接收資料的時候出了問題,一條資料,總是被分成多段接收,而且分成幾段不固定,每段的長度也不固定。但是當我在這里加了個延遲500ms后,接收的資料就會被固定分成兩段,先接收了一個資料,然后剩下的資料在下一次接收時會一起傳過來。
我猜測,這是因為外部硬體發資料是一個一個發的,增加了延遲后,第二段資料就可以一起接收到了,而不會被分成多段接收。有沒有辦法在第一次接收的時候就接收到全部資料?
public byte[] receive() {
byteBuffer.clear();
byte[] retbyte = byteBuffer.array();
int ret = mDeviceConnection.bulkTransfer(usbEpIn, retbyte, mMaxTransferSize, readOutTime);
if (ret > 0) {
byteBuffer.position(ret);
byte[] retData = new byte[byteBuffer.position()];
System.arraycopy(byteBuffer.array(), 0, retData, 0, retData.length);
L.i(TAG, "接收資料:" + DataConvert.byte2HexString(retData));
return retData;
}
return null;
}
uj5u.com熱心網友回復:
mMaxTransferSize 是怎么獲取的?uj5u.com熱心網友回復:
位元組是流式的,只能按協議讀取,沒有完成的資料段只能等待。return retData; 這里不妥,應該是決議協議,看看是否滿足一幀,滿足了才return.uj5u.com熱心網友回復:
隨便貼一段我的代碼,注意位元組協議的斷句:
ArrayList<Byte> listBytes = new ArrayList<>();
byte[] buffer = new byte[maxPackageSize];
UsbEndpoint inEndpoint = usbInterface.getEndpoint(0);
mainHandler.obtainMessage(MainHandler.WHAT_READING, "讀取準備就緒,請刷卡").sendToTarget();
deviceReading = true;
while (!Thread.interrupted()) {
int ret = usbDeviceConnection.bulkTransfer(inEndpoint, buffer, buffer.length, 200);
if (ret > 0) {
byte[] reab = new byte[ret];
System.arraycopy(buffer, 0, reab, 0, ret);
//Log.d(tag, "讀取到:" + bytesToHexString(reab));
//位元組流斷句
for (byte ab : reab) {
if (ab == (byte) 0x28) {
if (listBytes.size() > 0) {
Byte[] lineBytes = listBytes.toArray(new Byte[0]);
getCarCodeBytes(ArrayUtils.toPrimitive(lineBytes));
listBytes.clear();
}
} else if (ab != (byte) 0x00) {
listBytes.add(ab);
}
}
}
}
listBytes.clear();
mainHandler.obtainMessage(MainHandler.WHAT_SHOW_MESSAGE, "停止讀取").sendToTarget();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/250947.html
標籤:Android
上一篇:公交車收費終端app的開發
