TProPCMonitor/LoraGamepad/Util/SerialPipeIN.cs

65 lines
1.8 KiB
C#
Raw Permalink Normal View History

2022-11-08 15:05:47 +08:00
/// 串口
///
///
/// FRAME:<ADDRESS><LENGTH><TYPE><PALOAD><CRC>
// ADDRESS: FLIGHT_CONTROL 0XC8
// LENGTH: CONTAIN TYPE,PALOAD,CRC
// TYPE: LINK STATE 0X14
// CHANNEL 0X16
// CRC: CRC8_DVB_S2 1BYTE
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[]>
{
2022-11-08 15:05:47 +08:00
private const int TpyeAndCrcLength = 2;
private const int HeaderAndLenLength = 2;
private const int FrameCrcLength = 1;
2022-11-06 20:13:24 +08:00
protected override void Process(ConcurrentQueue<byte> queue)
{
if (!queue.TryPeek(out var first))
{
SpinWait.SpinUntil(() => false, 1);
// 队列无数据
return;
}
2022-11-08 15:05:47 +08:00
if (0xC8 != first) {
2022-11-06 20:13:24 +08:00
// 未匹配到包头,扔掉继续
queue.TryDequeue(out _);
return;
}
2022-11-08 15:05:47 +08:00
if (queue.Count < 10) {
2022-11-06 20:13:24 +08:00
// 数据长度过低
return;
}
2022-11-08 15:05:47 +08:00
var packLength = queue.ElementAt(1);
if (queue.Count < packLength + HeaderAndLenLength)
{
return;
}
var pack = queue.Take(packLength + HeaderAndLenLength).ToArray();
var crc = pack[packLength + HeaderAndLenLength - FrameCrcLength];
if (crc != CrcUtil.CRC8_Calculate(pack.Skip(HeaderAndLenLength).SkipLast(FrameCrcLength).ToArray())) {
2022-11-06 20:13:24 +08:00
// crc校验失败砍头
queue.TryDequeue(out _);
return;
}
// 队列消除整包数据
2022-11-08 15:05:47 +08:00
for (var i = 0; i < packLength + HeaderAndLenLength; i++) {
2022-11-06 20:13:24 +08:00
queue.TryDequeue(out _);
}
// 输出数据,砍头砍尾
// Console.WriteLine(BitConverter.ToString(pack));
2022-11-08 15:05:47 +08:00
OnOut(pack.Skip(HeaderAndLenLength).SkipLast(FrameCrcLength).ToArray());
2022-11-06 20:13:24 +08:00
}
}