You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
3.0 KiB

6 months ago
using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Utils;
using Service.Padar.Client;
using log4net;
using Newtonsoft.Json;
namespace Service.Padar.Codec;
public class Decoder : ByteToMessageDecoder
{
private readonly IByteBuffer[] _delimiters = { Unpooled.CopiedBuffer(PadarClient.StartChar) };
private static readonly ILog Log = LogManager.GetLogger(typeof(Decoder));
protected override void Decode(IChannelHandlerContext context, IByteBuffer buffer, List<object> output)
{
4 months ago
IByteBuffer delimiter = FindDelimiter(buffer);
6 months ago
if (delimiter != null)
{
5 months ago
//分隔符索引
6 months ago
int delimiterIndex = IndexOf(buffer, delimiter);
//帧长索引
int frameLengthIndex = delimiterIndex + delimiter.Capacity;
if (delimiterIndex > 0)
{
buffer.SkipBytes(delimiterIndex);
return;
}
if (buffer.ReadableBytes < frameLengthIndex + 2)
{
return;
}
5 months ago
// int frameLength = buffer.GetUnsignedShortLE(buffer.ReaderIndex + frameLengthIndex);
6 months ago
//总帧长
int totalFrameLength = delimiterIndex + delimiter.Capacity + 2;
6 months ago
// 最小总帧长过滤
if (totalFrameLength < 4)
6 months ago
{
return;
}
if (buffer.ReadableBytes < totalFrameLength)
{
// 数据不足,等待更多数据
return;
}
byte[] data = new byte[totalFrameLength];
5 months ago
try
{
buffer.ReadBytes(data);
4 months ago
if (PadarMgr._PadarClient!=null)
{
PadarMgr._PadarClient.CarState = data[3];
Log.Info($"receive {BitUtls.BytesToHexStr(data)}:{PadarMgr._PadarClient.CarState}");
}
6 months ago
5 months ago
}
4 months ago
catch (Exception e)
{
}
5 months ago
6 months ago
}
}
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;
}
private IByteBuffer? FindDelimiter(IByteBuffer buffer)
{
foreach (IByteBuffer delimiter in _delimiters)
{
int delimiterIndex = IndexOf(buffer, delimiter);
if (delimiterIndex >= 0)
{
return delimiter;
}
}
return null;
}
}