-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetStatusPacket.m
executable file
·128 lines (100 loc) · 2.5 KB
/
getStatusPacket.m
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
function [ statusPacket ] = getStatusPacket( s )
% read status packet from serial port buffer
try
packet=zeros(1,1024);
packet(4)=1018;
i=1;
% waiting time for first byte
byteTime=0.5;
% wait for the beginning of the packet
tic_wait=tic;
time=0;
while (s.BytesAvailable < 1 && time<byteTime)
time=toc(tic_wait);
end
% time out
if (time>=byteTime)
disp('Time out: first byte')
statusPacket=NaN;
return;
end
% waiting time for the whole packet
timeOut=0.8;
tic_wait=tic;
time=0;
% find the beginning of the packet
while packet(2)~=255 && time<timeOut
temp=fread(s,1);
if temp==255
packet(i)=temp;
i=i+1;
end
time=toc(tic_wait);
end
% time out
if (time>=timeOut)
statusPacket=NaN;
disp('Time out: beginning of the package')
return;
end
% read the rest of the packet
while i<packet(4)+6 && time<timeOut
if s.BytesAvailable > 0
packet(i)=fread(s,1);
i=i+1;
end
time=toc(tic_wait);
end
% time out
if (time>=timeOut)
statusPacket=NaN;
disp('Time out: whole package')
return;
end
statusPacket=packet(1:packet(4)+4);
catch e
disp(e)
end
end
%{
%OLD VERSION
% read status packet from serial port buffer
% waiting time for one byte
byteTime=0.10;
% wait for first four bytes (4th byte contains packet length)
tic_wait=tic;
time=0;
while (s.BytesAvailable<4 && time<4*byteTime)
time=toc(tic_wait);
end
% time out
if (time>=4*byteTime)
statusPacket=NaN;
return;
end
% read first four bytes (255,255,ID, length)
statusPacket=fread(s, 4)';
length=statusPacket(4);
% check start of the packet
if (statusPacket(1)~=255 && statusPacket(2)~=255)
statusPacket=NaN;
return;
end
% waiting time for one byte
byteTime=0.02;
% wait for the rest of the packet
tic_wait=tic;
time=0;
while (s.BytesAvailable<length && time<length*byteTime)
time=toc(tic_wait);
end
% time out
if (time>=length*byteTime)
statusPacket=NaN;
return;
end
% read the rest of the buffer
statusPacket=[ statusPacket, fread(s, s.BytesAvailable)'];
% terminating char '\n' at the end of the transmitted packet is removed
statusPacket=statusPacket(1:(length+4));
%}