update 电单车协议

This commit is contained in:
Guoqs
2024-07-15 16:05:15 +08:00
parent 61b948aea9
commit b9ec56a202
5 changed files with 259 additions and 2 deletions

View File

@@ -0,0 +1,77 @@
package com.jsowell.netty.decoder;
import com.jsowell.netty.domain.ChargingPileMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
public class ChargingPileDecoder extends ByteToMessageDecoder {
private static final byte[] FRAME_HEADER = {'D', 'N', 'Y'}; // 包头为"DNY"
private static final int MIN_FRAME_LENGTH = 14; // 最小帧长度:包头(3)+长度(2)+物理ID(4)+消息ID(2)+命令(1)+校验(2)
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
while (in.readableBytes() >= MIN_FRAME_LENGTH) {
in.markReaderIndex();
// 检查包头
byte[] header = new byte[3];
in.readBytes(header);
if (!isValidHeader(header)) {
in.resetReaderIndex();
return;
}
// 读取长度
short length = in.readShort();
if (in.readableBytes() < length - 5) { // 5 = 包头(3) + 长度(2)
in.resetReaderIndex();
return;
}
// 读取物理ID
int physicalId = in.readInt();
// 读取消息ID
short messageId = in.readShort();
// 读取命令
byte command = in.readByte();
// 读取数据
int dataLength = length - 13; // 13 = 包头(3) + 长度(2) + 物理ID(4) + 消息ID(2) + 命令(1) + 校验(2)
byte[] data = new byte[dataLength];
in.readBytes(data);
// 读取校验和
short checksum = in.readShort();
// 验证校验和
short calculatedChecksum = calculateChecksum(in, length);
if (checksum != calculatedChecksum) {
System.out.println("校验和错误,丢弃此帧");
continue;
}
// 创建消息对象并添加到输出列表
ChargingPileMessage message = new ChargingPileMessage(physicalId, messageId, command, data);
out.add(message);
}
}
private boolean isValidHeader(byte[] header) {
return header[0] == FRAME_HEADER[0] && header[1] == FRAME_HEADER[1] && header[2] == FRAME_HEADER[2];
}
private short calculateChecksum(ByteBuf buf, int length) {
short sum = 0;
for (int i = 0; i < length - 2; i++) {
sum += buf.getByte(buf.readerIndex() - length + i) & 0xFF;
}
return sum;
}
}