超时bug修改
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
using Model.Models;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
@@ -7,7 +8,7 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace DeviceCommand.Base
|
||||
{
|
||||
public class Serial_Port : ISerialPort
|
||||
public class Serial_Port : ISerialPort, IDisposable
|
||||
{
|
||||
public string PortName { get; set; } = "COM1";
|
||||
public int BaudRate { get; set; } = 9600;
|
||||
@@ -58,8 +59,10 @@ namespace DeviceCommand.Base
|
||||
_serialPort.DataBits = DataBits;
|
||||
_serialPort.StopBits = StopBits;
|
||||
_serialPort.Parity = Parity;
|
||||
_serialPort.ReadTimeout = ReadTimeout;
|
||||
_serialPort.WriteTimeout = WriteTimeout;
|
||||
|
||||
// 允许底层保留默认设置,控制权交给外层 WaitAsync
|
||||
_serialPort.ReadTimeout = SerialPort.InfiniteTimeout;
|
||||
_serialPort.WriteTimeout = SerialPort.InfiniteTimeout;
|
||||
|
||||
_serialPort.Open();
|
||||
return true;
|
||||
@@ -72,19 +75,33 @@ namespace DeviceCommand.Base
|
||||
|
||||
public virtual void Close()
|
||||
{
|
||||
if (_serialPort.IsOpen) _serialPort.Close();
|
||||
if (_serialPort?.IsOpen == true) _serialPort.Close();
|
||||
}
|
||||
|
||||
// 内部无锁发送方法,供原子组合操作调用
|
||||
private async Task LoglessSendAsync(string data, CancellationToken ct)
|
||||
{
|
||||
if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。");
|
||||
|
||||
byte[] bytes = Encoding.UTF8.GetBytes(data);
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (WriteTimeout > 0) cts.CancelAfter(WriteTimeout);
|
||||
|
||||
await _serialPort.BaseStream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
|
||||
try
|
||||
{
|
||||
if (WriteTimeout > 0)
|
||||
{
|
||||
// 核心修改:使用 WaitAsync 精准控制写入超时
|
||||
await _serialPort.BaseStream.WriteAsync(bytes, 0, bytes.Length, ct)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(WriteTimeout), ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
await _serialPort.BaseStream.WriteAsync(bytes, 0, bytes.Length, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (TimeoutException ex)
|
||||
{
|
||||
throw new TimeoutException($"串口写入数据超时({WriteTimeout} ms)", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SendAsync(string data, CancellationToken ct = default)
|
||||
@@ -100,7 +117,6 @@ namespace DeviceCommand.Base
|
||||
}
|
||||
}
|
||||
|
||||
// 内部无锁读取方法,利用 BaseStream 挂起线程,高性能不吃 CPU
|
||||
private async Task<string> LoglessReadAsync(string delimiter, CancellationToken ct)
|
||||
{
|
||||
if (!_serialPort.IsOpen) throw new InvalidOperationException("串口未打开。");
|
||||
@@ -109,24 +125,44 @@ namespace DeviceCommand.Base
|
||||
var sb = new StringBuilder();
|
||||
byte[] buffer = new byte[1024];
|
||||
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
if (ReadTimeout > 0) cts.CancelAfter(ReadTimeout);
|
||||
|
||||
while (!cts.Token.IsCancellationRequested)
|
||||
try
|
||||
{
|
||||
// 核心优化:利用流异步挂起,替代原先的 BytesToRead 循环延时
|
||||
int bytesRead = await _serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length, cts.Token);
|
||||
if (bytesRead == 0) continue;
|
||||
|
||||
sb.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
|
||||
|
||||
int index = sb.ToString().IndexOf(delimiter, StringComparison.Ordinal);
|
||||
if (index >= 0)
|
||||
while (true)
|
||||
{
|
||||
return sb.ToString(0, index).Trim();
|
||||
ct.ThrowIfCancellationRequested();
|
||||
|
||||
int bytesRead;
|
||||
if (ReadTimeout > 0)
|
||||
{
|
||||
// 核心修改:使用 WaitAsync 精准控制单次异步读取超时
|
||||
bytesRead = await _serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length, ct)
|
||||
.WaitAsync(TimeSpan.FromMilliseconds(ReadTimeout), ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
bytesRead = await _serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (bytesRead == 0) continue;
|
||||
|
||||
sb.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
|
||||
|
||||
string currentText = sb.ToString();
|
||||
int index = currentText.IndexOf(delimiter, StringComparison.Ordinal);
|
||||
if (index >= 0)
|
||||
{
|
||||
return currentText.Substring(0, index).Trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new TimeoutException("读取数据超时");
|
||||
catch (TimeoutException ex)
|
||||
{
|
||||
// 关键防污染策略:串口发生命令错、超时不响应时,WaitAsync 会立功捕获异常
|
||||
// 我们直接清空串口驱动内部的输入缓冲区,把残余垃圾数据物理抹除,确保下一条指令安全、不掉线
|
||||
ClearHardwareBuffer();
|
||||
throw new TimeoutException($"串口读取超时(未收到结束符 '{delimiter}'),等待时间:{ReadTimeout} ms", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> ReadAsync(string delimiter = "\n", CancellationToken ct = default)
|
||||
@@ -142,12 +178,14 @@ namespace DeviceCommand.Base
|
||||
}
|
||||
}
|
||||
|
||||
// 核心优化:保证多线程环境下发送和等待回包是一个原子过程
|
||||
public async Task<string> WriteReadAsync(string command, string delimiter = "\n", CancellationToken ct = default)
|
||||
{
|
||||
await commLock.WaitAsync(ct);
|
||||
try
|
||||
{
|
||||
// 发送新命令前先冲洗一下缓冲区,双重保险
|
||||
ClearHardwareBuffer();
|
||||
|
||||
await LoglessSendAsync(command, ct);
|
||||
return await LoglessReadAsync(delimiter, ct);
|
||||
}
|
||||
@@ -157,9 +195,32 @@ namespace DeviceCommand.Base
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 物理强制清空串口驱动层及软件层的缓冲区
|
||||
/// </summary>
|
||||
private void ClearHardwareBuffer()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_serialPort?.IsOpen == true)
|
||||
{
|
||||
_serialPort.DiscardInBuffer(); // 清空硬件接收缓冲区
|
||||
_serialPort.DiscardOutBuffer(); // 清空硬件发送缓冲区
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 忽略清理异常
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_serialPort?.Dispose();
|
||||
if (_serialPort != null)
|
||||
{
|
||||
if (_serialPort.IsOpen) _serialPort.Close();
|
||||
_serialPort.Dispose();
|
||||
}
|
||||
commLock?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user