From c42264064e4e9b1a236729b25c2e0c3f06d4bf23 Mon Sep 17 00:00:00 2001 From: dengboling Date: Wed, 29 Jul 2026 15:52:49 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=B2=E5=8F=A3=E5=9F=BA=E7=B1=BB=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E8=AF=BB=E5=86=99=E4=BA=8C=E8=BF=9B=E5=88=B6=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=B8=A7=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DeviceCommand/Base/Serial_Port.cs | 54 +++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) 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