private SerialPort _serialPort;
private byte[] _buffer = new byte[1024];
private int _bufferIndex = 0;
public void StartListening()
{
_serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
Task.Run(() => ReadDataLoop());
}
private void ReadDataLoop()
{
while (true)
{
int bytesAvailable = _serialPort.BytesToRead;
if (bytesAvailable > 0)
{
byte[] data = new byte[bytesAvailable];
_serialPort.Read(data, 0, bytesAvailable);
ProcessReceivedData(data);
}
Thread.Sleep(1); // 防止CPU占用过高
}
}
private void ProcessReceivedData(byte[] data)
{
foreach (var b in data)
{
_buffer[_bufferIndex++] = b;
if (_bufferIndex >= _buffer.Length || IsPacketComplete(_buffer))
{
ProcessCompletePacket(_buffer);
ClearBuffer();
}
}
}
private bool IsPacketComplete(byte[] buffer)
{
// 在这里检查数据包是否完整,例如寻找终止符
return false;
}
private void ProcessCompletePacket(byte[] packet)
{
// 在这里处理完整数据包
}
private void ClearBuffer()
{
_bufferIndex = 0;
} |