TProPCMonitor/LoraGamepad/Util/SerialPipeIN.cs

49 lines
1.2 KiB
C#
Raw Normal View History

2022-11-06 20:13:24 +08:00
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace LoraGamepad.Util;
public class SerialPipeIn: IAsyncPipe<byte,byte[]>
{
protected override void Process(ConcurrentQueue<byte> queue)
{
if (!queue.TryPeek(out var first))
{
SpinWait.SpinUntil(() => false, 1);
// 队列无数据
return;
}
if (0xFE != first) {
// 未匹配到包头,扔掉继续
queue.TryDequeue(out _);
return;
}
if (queue.Count < 14) {
// 数据长度过低
return;
}
var pack = queue.Take(14).ToArray();
if (pack[13] != CrcUtil.CRC8_Calculate(pack.Skip(1).SkipLast(1).ToArray())) {
// crc校验失败砍头
queue.TryDequeue(out _);
return;
}
// 队列消除整包数据
for (var i = 0; i < 14; i++) {
queue.TryDequeue(out _);
}
// 输出数据,砍头砍尾
// Console.WriteLine(BitConverter.ToString(pack));
OnOut(pack.Skip(1).SkipLast(1).ToArray());
}
}