Preserve outstanding RTU replies across serial port reopen
This commit is contained in:
parent
114fd5d3e4
commit
d83d1750d1
@ -28,13 +28,30 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
private System.IO.Ports.SerialPort _port;
|
||||
|
||||
private RtuSession _session;
|
||||
private string _openPortName;
|
||||
private readonly Dictionary<string, Dictionary<byte, RtuResponseReader>> _pendingByPort =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public ModbusRtuClient() { }
|
||||
private readonly Func<string, RtuSession> _openSession;
|
||||
|
||||
internal ModbusRtuClient(RtuSession session)
|
||||
public ModbusRtuClient() => _openSession = OpenSerialSession;
|
||||
|
||||
internal ModbusRtuClient(Func<string, RtuSession> openSession) => _openSession = openSession;
|
||||
|
||||
private RtuSession OpenSerialSession(string portName)
|
||||
{
|
||||
_session = session;
|
||||
Connected = true;
|
||||
_port = new System.IO.Ports.SerialPort(portName, Params.BaudRate, Params.ParityValue, Params.DataBits, Params.StopBitsValue)
|
||||
{
|
||||
ReadTimeout = 5000,
|
||||
WriteTimeout = 2000
|
||||
};
|
||||
_port.Open();
|
||||
var port = _port;
|
||||
double stopBits = port.StopBits == System.IO.Ports.StopBits.OnePointFive ? 1.5 :
|
||||
port.StopBits == System.IO.Ports.StopBits.Two ? 2 : 1;
|
||||
double bits = 1 + port.DataBits + stopBits + (port.Parity == System.IO.Ports.Parity.None ? 0 : 1);
|
||||
int gapMs = port.BaudRate > 19200 ? 2 : (int)Math.Ceiling(3500 * bits / port.BaudRate);
|
||||
return new RtuSession(port.BaseStream, () => port.BytesToRead, port.DiscardInBuffer, gapMs);
|
||||
}
|
||||
|
||||
/// <summary>打开串口</summary>
|
||||
@ -45,18 +62,11 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
ClosePort();
|
||||
try
|
||||
{
|
||||
_port = new System.IO.Ports.SerialPort(IP_SerialPort, Params.BaudRate, Params.ParityValue, Params.DataBits, Params.StopBitsValue)
|
||||
{
|
||||
ReadTimeout = 5000,
|
||||
WriteTimeout = 2000
|
||||
};
|
||||
_port.Open();
|
||||
var port = _port;
|
||||
double stopBits = port.StopBits == System.IO.Ports.StopBits.OnePointFive ? 1.5 :
|
||||
port.StopBits == System.IO.Ports.StopBits.Two ? 2 : 1;
|
||||
double bits = 1 + port.DataBits + stopBits + (port.Parity == System.IO.Ports.Parity.None ? 0 : 1);
|
||||
int gapMs = port.BaudRate > 19200 ? 2 : (int)Math.Ceiling(3500 * bits / port.BaudRate);
|
||||
_session = new RtuSession(port.BaseStream, () => port.BytesToRead, port.DiscardInBuffer, gapMs);
|
||||
var portName = IP_SerialPort;
|
||||
_session = _openSession(portName);
|
||||
_openPortName = portName;
|
||||
if (_pendingByPort.Remove(portName, out var pending))
|
||||
_session.Resume(pending);
|
||||
Connected = true;
|
||||
Log($"串口 {IP_SerialPort} 已打开");
|
||||
}
|
||||
@ -75,7 +85,12 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
|
||||
private void ClosePort()
|
||||
{
|
||||
if (_session?.Pending.Count > 0)
|
||||
_pendingByPort[_openPortName] = _session.Pending;
|
||||
_openPortName = null;
|
||||
_session = null;
|
||||
Successful = false;
|
||||
ReceiveData = null;
|
||||
try { _port?.Dispose(); }
|
||||
catch (Exception ex) { Log($"关闭串口失败: {ex.Message}"); }
|
||||
finally
|
||||
@ -85,6 +100,19 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
}
|
||||
}
|
||||
|
||||
// 仅在操作员确认设备已复位、旧应答不会再到达后调用。
|
||||
internal bool ReleaseResetStation(byte unit)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_session != null || IP_SerialPort == null ||
|
||||
!_pendingByPort.TryGetValue(IP_SerialPort, out var pending) || !pending.Remove(unit))
|
||||
return false;
|
||||
if (pending.Count == 0) _pendingByPort.Remove(IP_SerialPort);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── CRC16-Modbus ───
|
||||
|
||||
internal static ushort CalcCrc(byte[] data, int offset, int count)
|
||||
@ -155,7 +183,7 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Log("ModbusRTU: 收发超时,等待丢弃迟到应答;若从站无应答,请确认从站及串口线路空闲后重新打开串口");
|
||||
Log("ModbusRTU: 收发超时,等待丢弃迟到应答;其他站继续轮询。如从站已复位,请关闭串口并在配置中恢复该站");
|
||||
return null;
|
||||
}
|
||||
catch (IOException ex)
|
||||
|
||||
@ -138,6 +138,7 @@
|
||||
|
||||
<!-- 显示日志复选框 -->
|
||||
<StackPanel Grid.Row="4" Margin="0,4" Orientation="Horizontal">
|
||||
<Button Margin="5,0" Content="复位后恢复指定站" ToolTip="使用上方的站号" Command="{Binding RecoverStationCommand}" />
|
||||
<CheckBox Margin="20,0,0,0" Content="显示日志" IsChecked="{Binding Client.LogSwitch}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
@ -94,6 +94,29 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
public DelegateCommand ClosePortCommand =>
|
||||
_ClosePortCommand ??= new DelegateCommand(() => Client?.Close());
|
||||
|
||||
private DelegateCommand _recoverStationCommand;
|
||||
public DelegateCommand RecoverStationCommand =>
|
||||
_recoverStationCommand ??= new DelegateCommand(RecoverStation);
|
||||
|
||||
private void RecoverStation()
|
||||
{
|
||||
if (Client == null) return;
|
||||
byte unit = Client.Params.UnitId;
|
||||
if (Client.Connected)
|
||||
{
|
||||
System.Windows.MessageBox.Show("请先关闭串口,再恢复指定从站。");
|
||||
return;
|
||||
}
|
||||
var answer = System.Windows.MessageBox.Show(
|
||||
$"确认 {Client.IP_SerialPort} 的站 {unit} 已复位、线路空闲且旧应答不会再到达?",
|
||||
"恢复从站轮询", System.Windows.MessageBoxButton.YesNo,
|
||||
System.Windows.MessageBoxImage.Question, System.Windows.MessageBoxResult.No);
|
||||
if (answer == System.Windows.MessageBoxResult.Yes)
|
||||
System.Windows.MessageBox.Show(Client.ReleaseResetStation(unit)
|
||||
? $"站 {unit} 已解除等待。打开串口即可恢复轮询。"
|
||||
: $"站 {unit} 没有待清除的超时请求,或串口已打开。");
|
||||
}
|
||||
|
||||
// ─── DataItems 管理 ───
|
||||
private DelegateCommand<string> _ConnectsManage;
|
||||
|
||||
|
||||
@ -6,16 +6,32 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu;
|
||||
internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action discardInput, int frameGapMs)
|
||||
{
|
||||
// Execute、Open 和 Close 由客户端的同一把锁串行化。
|
||||
private readonly Dictionary<byte, RtuResponseReader> _pending = [];
|
||||
internal Dictionary<byte, RtuResponseReader> Pending { get; private set; } = [];
|
||||
private RtuResponseReader _partial;
|
||||
|
||||
private bool _awaitFrameGap;
|
||||
|
||||
internal void Resume(Dictionary<byte, RtuResponseReader> pending)
|
||||
{
|
||||
Pending = pending;
|
||||
_awaitFrameGap = pending.Values.Any(reader => reader.HasReceivedBytes);
|
||||
}
|
||||
|
||||
internal byte[] Exchange(byte[] request, Action<string> log)
|
||||
{
|
||||
if (_awaitFrameGap)
|
||||
{
|
||||
// 串口驱动可能已丢弃半帧中的部分字节。重新取得帧边界后才解析应答。
|
||||
discardInput();
|
||||
Thread.Sleep(frameGapMs);
|
||||
if (bytesAvailable() > 0) return null;
|
||||
_awaitFrameGap = false;
|
||||
}
|
||||
byte unit = request[0];
|
||||
if (_pending.Count > 0)
|
||||
if (Pending.Count > 0)
|
||||
{
|
||||
DrainBuffered(log);
|
||||
if (_pending.ContainsKey(unit)) return null;
|
||||
if (Pending.ContainsKey(unit)) return null;
|
||||
|
||||
// 另一站的残帧不能占住总线。等候帧间隔,若仍在接收则留待下次轮询。
|
||||
Thread.Sleep(frameGapMs);
|
||||
@ -24,7 +40,7 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
DrainBuffered(log);
|
||||
return null;
|
||||
}
|
||||
_partial = null; // 仅丢弃残帧进度,原站仍在 _pending 中
|
||||
_partial = null; // 仅丢弃残帧进度,原站仍在 Pending 中
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -40,9 +56,9 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
int budget = int.MaxValue;
|
||||
return ReadFrames(reply, ref budget, log);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
catch (Exception ex) when (ex is TimeoutException or IOException or InvalidDataException)
|
||||
{
|
||||
_pending[unit] = reply;
|
||||
Pending[unit] = reply;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -64,7 +80,7 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
budget--;
|
||||
if (current?.UnitId == unit)
|
||||
_partial = current;
|
||||
else if (!_pending.TryGetValue((byte)unit, out _partial))
|
||||
else if (!Pending.TryGetValue((byte)unit, out _partial))
|
||||
throw new InvalidDataException($"ModbusRTU: 收到非预期站号 {unit}");
|
||||
_partial.BeginFrame();
|
||||
}
|
||||
@ -87,7 +103,7 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
if (frame == null) return null;
|
||||
_partial = null;
|
||||
if (reader == current) return frame;
|
||||
_pending.Remove(reader.UnitId);
|
||||
Pending.Remove(reader.UnitId);
|
||||
log($"ModbusRTU: 已丢弃站 {reader.UnitId} 的迟到应答");
|
||||
}
|
||||
return null;
|
||||
@ -101,6 +117,7 @@ internal sealed class RtuResponseReader(byte unitId, byte functionCode, byte[] r
|
||||
private int _received;
|
||||
|
||||
internal byte UnitId => unitId;
|
||||
internal bool HasReceivedBytes => _received > 0;
|
||||
|
||||
internal void BeginFrame()
|
||||
{
|
||||
|
||||
@ -139,6 +139,86 @@ public class ModbusRtuTimeoutTests
|
||||
Assert.Equal(new byte[] { 17, 18, 19, 17 }, wire.Writes.Select(r => r[0]));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public void ReopenDoesNotAcceptPreCloseReply(bool closeFirst)
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
var client = wire.Client;
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
|
||||
if (closeFirst) client.Close();
|
||||
client.Open();
|
||||
wire.OnWrite = _ => wire.Receive(Old);
|
||||
Assert.Null(client.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.Single(wire.Writes);
|
||||
wire.OnWrite = _ => wire.Receive([.. Old, .. AtStation(Fresh, 18)]);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 18));
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 17));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OutstandingReplyBelongsToOriginalPort()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
var client = wire.Client;
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
|
||||
client.IP_SerialPort = "COM2";
|
||||
client.Open();
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(1, 2, 17));
|
||||
client.IP_SerialPort = "com1";
|
||||
client.Open();
|
||||
Assert.Null(client.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.Equal(2, wire.Writes.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReopenWithInterruptedFrameDiscardsTailBeforePollingOtherStation()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
var client = wire.Client;
|
||||
wire.OnWrite = _ => wire.Receive(Old[..3]);
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
|
||||
client.Close();
|
||||
wire.Receive(Old[3..]);
|
||||
client.Open();
|
||||
wire.OnWrite = _ => wire.Receive(AtStation(Fresh, 18));
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 18));
|
||||
Assert.Null(client.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.Equal(2, wire.Writes.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ConfirmedResetReleasesOnlySelectedStationWhileClosed()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
var client = wire.Client;
|
||||
Assert.False(client.WriteSingleRegister(1, 7, 17));
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 18));
|
||||
Assert.False(client.ReleaseResetStation(17));
|
||||
client.Close();
|
||||
Assert.True(client.ReleaseResetStation(17));
|
||||
client.Open();
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 18));
|
||||
Assert.Equal(new byte[] { 6, 3, 3 }, wire.Writes.Select(r => r[1]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TransportFailureAfterWriteRemainsPendingAfterOpen()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
wire.OnWrite = _ => throw new IOException();
|
||||
Assert.False(wire.Client.WriteSingleRegister(1, 7, 17));
|
||||
Assert.False(wire.Client.Connected);
|
||||
wire.Client.Open();
|
||||
Assert.False(wire.Client.WriteSingleRegister(1, 7, 17));
|
||||
Assert.Single(wire.Writes);
|
||||
}
|
||||
|
||||
private sealed class ScriptedPort : Stream
|
||||
{
|
||||
private readonly Queue<byte> _input = new();
|
||||
@ -146,8 +226,12 @@ public class ModbusRtuTimeoutTests
|
||||
internal List<byte[]> Writes { get; } = [];
|
||||
internal Action<int>? OnWrite;
|
||||
|
||||
internal ScriptedPort() =>
|
||||
Client = new ModbusRtuClient(new RtuSession(this, () => _input.Count, _input.Clear, 0));
|
||||
internal ScriptedPort()
|
||||
{
|
||||
Client = new ModbusRtuClient(_ => new RtuSession(this, () => _input.Count, _input.Clear, 0))
|
||||
{ IP_SerialPort = "COM1" };
|
||||
Client.Open();
|
||||
}
|
||||
|
||||
internal void Receive(byte[] bytes)
|
||||
{
|
||||
|
||||
Loading…
Reference in New Issue
Block a user