解码器拆分

This commit is contained in:
Guoqs
2024-11-27 14:32:51 +08:00
parent 9b95a07d8b
commit cd252d5ed1
8 changed files with 143 additions and 12 deletions

View File

@@ -0,0 +1,105 @@
package com.jsowell.netty.decoder;
import com.jsowell.common.util.BytesUtil;
import com.jsowell.common.util.CRC16Util;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.DecoderException;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
@Slf4j
public class YkcProtocolDecoder extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
log.info("YkcProtocolDecoder.decode");
// 检查起始标志是否为0x68
if (in.readableBytes() < 5) {
return; // 至少需要 起始标志 (1) + 数据长度 (1) + 序列号域 (2) + 帧校验域 (1)
}
in.markReaderIndex(); // 标记当前读取位置
byte startFlag = in.readByte();
log.info("startFlag: {}", BytesUtil.binary(new byte[]{startFlag}, 16));
if (startFlag != (byte) 0x68) {
throw new DecoderException("Invalid start flag: " + startFlag);
}
// 读取数据长度
byte dataLength = in.readByte();
if (in.readableBytes() < dataLength + 2) { // 消息体 + 帧校验域长度
in.resetReaderIndex();
return; // 数据不足,等待更多字节
}
// 读取其他字段
short serialNumber = in.readShort(); // 序列号域
log.info("serialNumber: {}", BytesUtil.printHexBinary(new byte[]{(byte) serialNumber}));
byte encryptFlag = in.readByte(); // 加密标志
log.info("encryptFlag: {}", BytesUtil.printHexBinary(new byte[]{encryptFlag}));
byte frameType = in.readByte(); // 帧类型标志
log.info("frameType: {}", BytesUtil.printHexBinary(new byte[]{frameType}));
// 读取消息体
byte[] messageBody = new byte[dataLength - 4]; // 消息体长度 = 数据长度 - 固定字段长度
log.info("messageBody: {}", BytesUtil.printHexBinary(messageBody));
in.readBytes(messageBody);
// 读取帧校验域
short receivedCrc = in.readShort();
// 计算 CRC
short calculatedCrc = CRC16Util.calculateCrc(serialNumber, encryptFlag, frameType, messageBody);
if (calculatedCrc != receivedCrc) {
throw new DecoderException("CRC check failed. Expected: " + receivedCrc + ", Calculated: " + calculatedCrc);
}
// 构造消息对象并传递给下一个处理器
ProtocolMessage message = new ProtocolMessage(startFlag, dataLength, serialNumber, encryptFlag, frameType, messageBody, receivedCrc);
out.add(message);
}
public static int bcdToDecimal(byte bcd1, byte bcd2) {
// BCD码转换为十进制
int high = (bcd1 >> 4) & 0x0F; // 高4位
int low = bcd1 & 0x0F; // 低4位
int high2 = (bcd2 >> 4) & 0x0F;
int low2 = bcd2 & 0x0F;
// 将BCD码拼接成十进制数
return (high * 1000) + (low * 100) + (high2 * 10) + low2;
}
// 自定义消息类
public static class ProtocolMessage {
private final byte startFlag;
private final byte dataLength;
private final short serialNumber;
private final byte encryptFlag;
private final byte frameType;
private final byte[] messageBody;
private final short crc;
public ProtocolMessage(byte startFlag, byte dataLength, short serialNumber, byte encryptFlag, byte frameType, byte[] messageBody, short crc) {
this.startFlag = startFlag;
this.dataLength = dataLength;
this.serialNumber = serialNumber;
this.encryptFlag = encryptFlag;
this.frameType = frameType;
this.messageBody = messageBody;
this.crc = crc;
}
// Getter methods...
public byte getStartFlag() { return startFlag; }
public byte getDataLength() { return dataLength; }
public short getSerialNumber() { return serialNumber; }
public byte getEncryptFlag() { return encryptFlag; }
public byte getFrameType() { return frameType; }
public byte[] getMessageBody() { return messageBody; }
public short getCrc() { return crc; }
}
}

View File

@@ -9,13 +9,16 @@ import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* 友电协议解码器
*/
@Slf4j
public class YouDianDecoder extends ByteToMessageDecoder {
public class YouDianProtocolDecoder extends ByteToMessageDecoder {
private static final int HEADER_LENGTH_DNY = 3; // "DNY" 包头的长度
private static final int HEADER_LENGTH_68 = 1; // 68 包头的长度
// 构造函数初始化起始标志
public YouDianDecoder() {}
public YouDianProtocolDecoder() {}
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception {

View File

@@ -1,6 +1,7 @@
package com.jsowell.netty.decoder;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.YKCDataProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
@@ -107,7 +108,12 @@ public class YunKuaiChongDecoder extends ByteToMessageDecoder {
// 读取 data 数据 最后+2是帧校验域长度
ByteBuf frame = buffer.retainedSlice(beginReader, HEADER_LENGTH_68 + 1 + length + 2);
buffer.readerIndex(beginReader + HEADER_LENGTH_68 + 1 + length + 2);
out.add(frame);
// 转为YKCDataProtocol对象
byte[] bytes = new byte[HEADER_LENGTH_68 + 1 + length + 2];
frame.readBytes(bytes);
YKCDataProtocol ykcDataProtocol = new YKCDataProtocol(bytes);
out.add(ykcDataProtocol);
}
// 处理DNY协议消息

View File

@@ -1,6 +1,6 @@
package com.jsowell.netty.server.electricbicycles;
import com.jsowell.netty.decoder.YouDianDecoder;
import com.jsowell.netty.decoder.YouDianProtocolDecoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
@@ -20,7 +20,7 @@ public class ElectricBicyclesServerChannelInitializer extends ChannelInitializer
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("frameDecoder", new YouDianDecoder());
pipeline.addLast("frameDecoder", new YouDianProtocolDecoder());
// pipeline.addLast("decoder", new MessageDecode());
// pipeline.addLast("encoder", new MessageEncode());
pipeline.addLast("decoder", new ByteArrayDecoder());

View File

@@ -20,8 +20,8 @@ public class NettyServerChannelInitializer extends ChannelInitializer<SocketChan
@Override
protected void initChannel(SocketChannel channel) throws Exception {
ChannelPipeline pipeline = channel.pipeline();
// pipeline.addLast("frameDecoder",new CustomDecoder());
pipeline.addLast("frameDecoder", new YunKuaiChongDecoder());
pipeline.addLast("frameDecoder",new YunKuaiChongDecoder());
// pipeline.addLast("frameDecoder", new YkcProtocolDecoder());
pipeline.addLast("decoder", new ByteArrayDecoder());
pipeline.addLast("encoder", new ByteArrayDecoder());
//读超时时间设置为10s0表示不监控

View File

@@ -1,6 +1,7 @@
package com.jsowell.netty.server.yunkuaichong;
import com.google.common.collect.Lists;
import com.jsowell.common.core.domain.ykc.YKCDataProtocol;
import com.jsowell.common.core.domain.ykc.YKCFrameTypeCode;
import com.jsowell.common.enums.ykc.PileChannelEntity;
import com.jsowell.common.util.BytesUtil;
@@ -68,9 +69,11 @@ public class NettyServerHandler extends ChannelInboundHandlerAdapter {
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
// log.info("channelRead-aClass:{}", message.getClass());
// log.info("加载客户端报文channelRead=== channelId:" + ctx.channel().id() + ", msg:" + message);
// 下面可以解析数据保存数据生成返回报文将需要返回报文写入write函数
byte[] msg = (byte[]) message;
YKCDataProtocol ykcDataProtocol = (YKCDataProtocol) message;
byte[] msg = ykcDataProtocol.getBytes();
// 获取帧类型
byte[] frameTypeBytes = BytesUtil.copyBytes(msg, 5, 1);

View File

@@ -37,10 +37,10 @@ public class YKCBusinessServiceImpl implements YKCBusinessService {
@Override
public byte[] process(byte[] msg, ChannelHandlerContext ctx) {
if (!YKCUtils.checkMsg(msg)) {
// 校验不通过,丢弃消息
return null;
}
// if (!YKCUtils.checkMsg(msg)) {
// // 校验不通过,丢弃消息
// return null;
// }
YKCDataProtocol ykcDataProtocol = new YKCDataProtocol(msg);
// 获取帧类型
String frameType = YKCUtils.frameType2Str(ykcDataProtocol.getFrameType());