liubobuzhidao

android之usb串口开发

问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
I can't understand why onNewData() method catchs sometimes full frames, and
most of the time truncated frame.
Let me explain, in my application my serial device writes frames with the
following pattern:
[0x1][lenght][data][0x4].
On a pc terminal i can successfully read full frames starting with 0x1 and
ending with 0x4. Moreover an application from Google Play (free usb serial
terminal) can successfully read full frame at once.
But with the usb-serial-for-android library, onNewData catchs 70% times
frames into 2-3 pieces.
ex schematically:
full frame :
------------------------------------
byte[] data= A B C D E
------------------------------------
truncated:
-------------------------
byte[] data= A
-------------------------
byte[] data= B C
-------------------------
byte[] data= DE
解决方法很简答
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Override
public void onNewData(final byte[] data) {
String readMsg = new String(data, 0, data.length);
msg = msg + readMsg;
int newLineIndex = msg.indexOf('\n');
MLog.d(TAG, "index " + newLineIndex);
String msgReturn = "";
if (newLineIndex != -1) {
msgReturn = msg.substring(0, newLineIndex);
msg = msg.substring(newLineIndex + 1, msg.length());
}
MLog.d(TAG, msg);
if (msgReturn.trim().equals("") == false) {
final String finalMsgReturn = msgReturn;
mHandler.post(new Runnable() {
@Override
public void run() {
callbackfn.event(finalMsgReturn);
}
});
}
}
1
http://www.programcreek.com/java-api-examples/index.php?source_dir=Protocoder-master/protocoder/protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/api/boards/PSerial.java