✅ 操作成功!

串口协议

发布时间:2023-06-07 作者:admin 来源:文学

串口协议

串口协议

问卷调查表-后印象派

2023年2月21日发(作者:必应输入法官网)

android串⼝通信以及串⼝协议解析

2.协议解析

[java]

1.

1./**

2.*读取终端设备数据

3.*@authorAdministrator

4.*/

eclassReadThreadextendsThread{

6.

7.@Override

voidrun(){

();

10.

11.//定义⼀个包的最⼤长度

Length=2048;

[]buffer=newbyte[maxLength];

14.//每次收到实际长度

ilable=0;

16.//当前已经收到包的总长度

rentLength=0;

18.//协议头长度4个字节(开始符1,类型1,长度2)

derLength=4;

20.

(!isInterrupted()){

{

ble=ble();

(available>0){

25.//防⽌超出数组最⼤长度导致溢出

(available>maxLength-currentLength){

ble=maxLength-currentLength;

28.}

(buffer,currentLength,available);

tLength+=available;

31.}

32.

33.}

(Exceptione){

tackTrace();

36.}

37.

sor=0;

39.//如果当前收到包⼤于头的长度,则解析当前包

(currentLength>=headerLength){

41.//取到头部第⼀个字节

(buffer[cursor]!=0x0F){

43.--currentLength;

44.++cursor;

ue;

46.}

47.

tentLenght=parseLen(buffer,cursor,headerLength);

49.//如果内容包的长度⼤于最⼤内容长度或者⼩于等于0,则说明这个包有问题,丢弃

(contentLenghtmaxLength-5){

tLength=0;

;

53.}

54.//如果当前获取到长度⼩于整个包的长度,则跳出循环等待继续接收数据

tPackLen=contentLenght+5;

(currentLength

;

58.}

59.

60.//⼀个完整包即产⽣

61.//proceOnePacket(buffer,i,factPackLen);

Received(buffer,cursor,factPackLen);

tLength-=factPackLen;

+=factPackLen;

65.}

66.//残留字节移到缓冲区⾸

(currentLength>0&&cursor>0){

opy(buffer,cursor,buffer,0,currentLength);

69.}

70.}

71.}

72.}

73.

74./**

75.*获取协议内容长度

76.*@paramheader

77.*@return

78.*/

intparseLen(bytebuffer[],intindex,intheaderLength){

80.

81.//if(-index

81.//if(-index

=buffer[index+2];

=buffer[index+3];

=0;

(((a>>7)&0x1)==0x1){

=(((a&0x7f)<<8)|b);

87.}

{

[]tmp=newchar[2];

[0]=(char)a;

[1]=(char)b;

s=newString(tmp,0,2);

=nt(s,16);

94.}

95.

rlt;

97.}

98.

tedvoidonDataReceived(finalbyte[]buffer,finalintindex,finalintpacklen){

n("收到信息");

[]buf=newbyte[packlen];

opy(buffer,index,buf,0,packlen);

tance(myHandler).analyze(buf);

104.}

105.

👁️ 阅读量:0