串口基类添加读写二进制数据帧方法

This commit is contained in:
2026-07-29 15:52:49 +08:00
parent 2d7f302bb9
commit c42264064e

View File

@@ -223,5 +223,59 @@ namespace DeviceCommand.Base
}
commLock?.Dispose();
}
// 在 Serial_Port 类中添加以下方法:
/// <summary>
/// 发送原始二进制数据帧无分隔符用于IT6720等自定义二进制协议
/// </summary>
public async Task WriteBytesAsync(byte[] data, CancellationToken ct = default)
{
await commLock.WaitAsync(ct);
try
{
if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。");
await _serialPort.BaseStream.WriteAsync(data, 0, data.Length, ct).ConfigureAwait(false);
}
finally
{
commLock.Release();
}
}
/// <summary>
/// 读取指定长度的原始二进制数据帧(无分隔符)
/// </summary>
public async Task<byte[]> ReadBytesAsync(int count, CancellationToken ct = default)
{
await commLock.WaitAsync(ct);
try
{
if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。");
if (count <= 0) return Array.Empty<byte>();
byte[] buffer = new byte[count];
int offset = 0;
while (offset < count)
{
ct.ThrowIfCancellationRequested();
int read = await _serialPort.BaseStream.ReadAsync(buffer, offset, count - offset, ct)
.WaitAsync(TimeSpan.FromMilliseconds(ReadTimeout), ct)
.ConfigureAwait(false);
if (read == 0) throw new EndOfStreamException("串口读取数据流意外终止");
offset += read;
}
return buffer;
}
catch (TimeoutException ex)
{
ClearHardwareBuffer();
throw new TimeoutException($"串口读取 {count} 字节二进制数据超时 ({ReadTimeout} ms)", ex);
}
finally
{
commLock.Release();
}
}
}
}