using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Codecs; using DotNetty.Transport.Channels; using System; using System.Collections.Generic; using System.Net; using System.Numerics; using System.Text.RegularExpressions; using HybirdFrameworkEntity; using HybirdFrameworkServices.ChargerManage; using HybirdFrameworkServices.ChargerManage.Msg; namespace HybirdFrameworkServices { public class CustomFrameDecoder : ByteToMessageDecoder { private readonly IByteBuffer[] delimiters; private readonly bool stripDelimiter; private readonly bool failFast; public CustomFrameDecoder(IByteBuffer[] delimiters, bool stripDelimiter, bool failFast) { this.delimiters = delimiters; this.stripDelimiter = stripDelimiter; this.failFast = failFast; } protected override void Decode(IChannelHandlerContext ctx, IByteBuffer buffer, List output) { // 查找分隔符 IByteBuffer delimiter = FindDelimiter(buffer); if (delimiter != null) { int delimiterIndex = IndexOf(buffer, delimiter);//分隔符索引 int frameLengthIndex = delimiterIndex + delimiter.Capacity;//帧长度索引 if (delimiterIndex > 0) { buffer.SkipBytes(delimiterIndex); return; } if (buffer.ReadableBytes < frameLengthIndex + 7) { // 数据不足,等待更多数据 return; } // 读取长度字段 int frameLength = buffer.GetUnsignedShortLE(buffer.ReaderIndex + frameLengthIndex); if (buffer.ReadableBytes < frameLength) { // 数据不足,等待更多数据 return; } ; IPEndPoint remoteAddress = (IPEndPoint)ctx.Channel.RemoteAddress; string clientIP = remoteAddress.Address.ToString(); output.Add( this.Parse(buffer,clientIP)); } } //将消息给每个充电机对象 public BaseMsg Parse(IByteBuffer byteBuffer,string clientIp) { BaseMsg baseMsg = null; //将cmd解析出来 ushort cmd = byteBuffer.GetUnsignedShortLE(6); baseMsg = cmd switch { 206 => new CMD206(byteBuffer,clientIp), 202=> new CMD202(byteBuffer,clientIp), _ => new BaseMsg(byteBuffer,clientIp), }; baseMsg.Parse(); return baseMsg; } private IByteBuffer FindDelimiter(IByteBuffer buffer) { foreach (IByteBuffer delimiter in delimiters) { int delimiterIndex = IndexOf(buffer, delimiter); if (delimiterIndex >= 0) { return delimiter; } } return null; } private static int IndexOf(IByteBuffer haystack, IByteBuffer needle) { for (int i = haystack.ReaderIndex; i < haystack.WriterIndex; i++) { int num = i; int j; for (j = 0; j < needle.Capacity && haystack.GetByte(num) == needle.GetByte(j); j++) { num++; if (num == haystack.WriterIndex && j != needle.Capacity - 1) { return -1; } } if (j == needle.Capacity) { return i - haystack.ReaderIndex; } } return -1; } } }