diff --git a/DeviceCommand/Base/Serial_Port.cs b/DeviceCommand/Base/Serial_Port.cs index 1d73cb0..19f9b9c 100644 --- a/DeviceCommand/Base/Serial_Port.cs +++ b/DeviceCommand/Base/Serial_Port.cs @@ -223,5 +223,59 @@ namespace DeviceCommand.Base } commLock?.Dispose(); } + + // 在 Serial_Port 类中添加以下方法: + + /// + /// 发送原始二进制数据帧(无分隔符,用于IT6720等自定义二进制协议) + /// + 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(); + } + } + + /// + /// 读取指定长度的原始二进制数据帧(无分隔符) + /// + public async Task ReadBytesAsync(int count, CancellationToken ct = default) + { + await commLock.WaitAsync(ct); + try + { + if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。"); + if (count <= 0) return Array.Empty(); + + 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(); + } + } } } \ No newline at end of file