You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Sln.Iot/Sln.Iot.Socket/Adapter/CustomDataHandlingAdapter.cs

117 lines
3.7 KiB
C#

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2025 WenJY
* CLR4.0.30319.42000
* Mr.Wen's MacBook Pro
* Sln.Iot.Socket.Adapter
* 50003A25-42CE-44A7-9940-FFDE3BD0A52A
*
* WenJY
*
* 2025-04-11 13:56:24
* V1.0.0
*
*
*--------------------------------------------------------------------
*
*
*
*
* V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using System;
using System.Text;
using TouchSocket.Core;
namespace Sln.Iot.Socket.Adapter
{
public class CustomDataHandlingAdapter:CustomDataHandlingAdapter<BufferRequestInfo>
{
protected override FilterResult Filter(in ByteBlock byteBlock, bool beCached, ref BufferRequestInfo request, ref int tempCapacity)
{
CacheTimeoutEnable = true;
CacheTimeout = new TimeSpan(0, 0, 0, 0, 5000);
int pos = byteBlock.Pos;
try
{
if (byteBlock.CanReadLen < 5)
{
return FilterResult.Cache;
}
byteBlock.Read(out byte[] header, 1);
byteBlock.Read(out byte[] deviceType, 1);
byteBlock.Read(out byte[] deviceId, 2);
string DeviceType = Encoding.ASCII.GetString(deviceType);
string collectEquipCode = DeviceType + this.ConverToString(deviceId);
byteBlock.Pos += 3;
byteBlock.Read(out byte[] dataType, 1);
byteBlock.Read(out byte[] lengthByte, 2);
string hexString = BitConverter.ToString(lengthByte).Replace("-", "");
int bodyLength = Convert.ToInt32(hexString, 16);
if (bodyLength > byteBlock.CanReadLen)
{
byteBlock.Pos = pos; //body数据不足。回退游标
return FilterResult.Cache;
}
else
{
byteBlock.Read(out byte[] body, bodyLength);
byteBlock.Read(out byte[] check, 1);
byteBlock.Read(out byte[] tail, 1);
request = new BufferRequestInfo()
{
header = header,
ColletEquipCode = collectEquipCode,
DataType = dataType[0],
BufferLength = bodyLength,
Body = body,
CheckBit = check[0],
Tail = tail,
buffer = byteBlock
};
return FilterResult.Success;
}
}catch (Exception ex)
{
Logger.Error("FilterResult"+ex.Message);
byteBlock.Pos = pos; //body数据不足。回退游标
return FilterResult.Cache;
}
}
private string ConverToString(byte[] data)
{
string str;
StringBuilder stb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
if ((int)data[i] > 15)
{
stb.Append(Convert.ToString(data[i], 16).ToUpper()); //添加字符串
}
else //如果是小于0F需要加个零
{
stb.Append("0" + Convert.ToString(data[i], 16).ToUpper());
}
}
str = stb.ToString();
return str;
}
}
}