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#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2025 WenJY 保留所有权利。
* CLR版本4.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;
}
}
}