60 lines
1.5 KiB
Dart
60 lines
1.5 KiB
Dart
import 'dart:typed_data';
|
||
|
||
class RawPacket {
|
||
final int command; // 第三位指令位
|
||
final Uint8List payload; // 数据位
|
||
RawPacket({required this.command, required this.payload});
|
||
}
|
||
|
||
class ProtocolDecoder {
|
||
static const head = [0xAB, 0xAA];
|
||
static const tail = [0xAA, 0xAB];
|
||
final List<int> _buffer = [];
|
||
|
||
List<RawPacket> decode(List<int> newData) {
|
||
_buffer.addAll(newData);
|
||
List<RawPacket> packets = [];
|
||
|
||
while (_buffer.length >= 5) {
|
||
// 最小包长度:头2+指令1+尾2 = 5,加1位数据=6,但是心跳包是AB AA FF AA AB
|
||
// 1. 找头
|
||
int headIdx = -1;
|
||
for (int i = 0; i < _buffer.length - 1; i++) {
|
||
if (_buffer[i] == head[0] && _buffer[i + 1] == head[1]) {
|
||
headIdx = i;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (headIdx == -1) {
|
||
_buffer.clear(); // 没头,全是垃圾数据
|
||
break;
|
||
}
|
||
|
||
// 2. 找尾
|
||
int tailIdx = -1;
|
||
for (int i = headIdx + 2; i < _buffer.length - 1; i++) {
|
||
if (_buffer[i] == tail[0] && _buffer[i + 1] == tail[1]) {
|
||
tailIdx = i;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if (tailIdx != -1) {
|
||
// 3. 提取
|
||
int cmd = _buffer[headIdx + 2];
|
||
Uint8List payload = Uint8List.fromList(
|
||
_buffer.sublist(headIdx + 3, tailIdx),
|
||
);
|
||
packets.add(RawPacket(command: cmd, payload: payload));
|
||
|
||
// 4. 移除已处理部分
|
||
_buffer.removeRange(0, tailIdx + 2);
|
||
} else {
|
||
break; // 还没传完
|
||
}
|
||
}
|
||
return packets;
|
||
}
|
||
}
|