Carry pending Modbus RTU replies across client replacement
This commit is contained in:
parent
d83d1750d1
commit
12b51e0ca2
@ -29,8 +29,14 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
|
||||
private RtuSession _session;
|
||||
private string _openPortName;
|
||||
private readonly Dictionary<string, Dictionary<byte, RtuResponseReader>> _pendingByPort =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
// 未决应答属于物理总线。不同配置创建的客户端也必须共用该状态。
|
||||
private sealed class PortState
|
||||
{
|
||||
internal bool InUse;
|
||||
internal readonly Dictionary<byte, RtuResponseReader> Pending = [];
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, PortState> Ports = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly Func<string, RtuSession> _openSession;
|
||||
|
||||
@ -63,10 +69,17 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
try
|
||||
{
|
||||
var portName = IP_SerialPort;
|
||||
PortState state;
|
||||
lock (Ports)
|
||||
{
|
||||
if (!Ports.TryGetValue(portName, out state))
|
||||
Ports.Add(portName, state = new PortState());
|
||||
if (state.InUse) throw new IOException($"串口 {portName} 已被其他 RTU 客户端占用");
|
||||
state.InUse = true;
|
||||
_openPortName = portName;
|
||||
}
|
||||
_session = _openSession(portName);
|
||||
_openPortName = portName;
|
||||
if (_pendingByPort.Remove(portName, out var pending))
|
||||
_session.Resume(pending);
|
||||
_session.Resume(state.Pending);
|
||||
Connected = true;
|
||||
Log($"串口 {IP_SerialPort} 已打开");
|
||||
}
|
||||
@ -85,9 +98,6 @@ 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;
|
||||
@ -96,6 +106,16 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
finally
|
||||
{
|
||||
_port = null;
|
||||
lock (Ports)
|
||||
{
|
||||
if (_openPortName != null)
|
||||
{
|
||||
var state = Ports[_openPortName];
|
||||
state.InUse = false;
|
||||
if (state.Pending.Count == 0) Ports.Remove(_openPortName);
|
||||
_openPortName = null;
|
||||
}
|
||||
}
|
||||
Connected = false;
|
||||
}
|
||||
}
|
||||
@ -105,11 +125,14 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
{
|
||||
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;
|
||||
var portName = IP_SerialPort;
|
||||
lock (Ports)
|
||||
{
|
||||
if (_session != null || portName == null || !Ports.TryGetValue(portName, out var state)
|
||||
|| state.InUse || !state.Pending.Remove(unit)) return false;
|
||||
if (state.Pending.Count == 0) Ports.Remove(portName);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -6,14 +6,14 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu;
|
||||
internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action discardInput, int frameGapMs)
|
||||
{
|
||||
// Execute、Open 和 Close 由客户端的同一把锁串行化。
|
||||
internal Dictionary<byte, RtuResponseReader> Pending { get; private set; } = [];
|
||||
private Dictionary<byte, RtuResponseReader> _pending = [];
|
||||
private RtuResponseReader _partial;
|
||||
|
||||
private bool _awaitFrameGap;
|
||||
|
||||
internal void Resume(Dictionary<byte, RtuResponseReader> pending)
|
||||
{
|
||||
Pending = pending;
|
||||
_pending = pending;
|
||||
_awaitFrameGap = pending.Values.Any(reader => reader.HasReceivedBytes);
|
||||
}
|
||||
|
||||
@ -28,10 +28,10 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
_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);
|
||||
@ -40,7 +40,7 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
DrainBuffered(log);
|
||||
return null;
|
||||
}
|
||||
_partial = null; // 仅丢弃残帧进度,原站仍在 Pending 中
|
||||
_partial = null; // 仅丢弃残帧进度,原站仍在 _pending 中
|
||||
}
|
||||
else
|
||||
{
|
||||
@ -58,7 +58,7 @@ internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action
|
||||
}
|
||||
catch (Exception ex) when (ex is TimeoutException or IOException or InvalidDataException)
|
||||
{
|
||||
Pending[unit] = reply;
|
||||
_pending[unit] = reply;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@ -80,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();
|
||||
}
|
||||
@ -103,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;
|
||||
|
||||
@ -164,18 +164,20 @@ public class ModbusRtuTimeoutTests
|
||||
using var wire = new ScriptedPort();
|
||||
var client = wire.Client;
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
|
||||
client.IP_SerialPort = "COM2";
|
||||
client.IP_SerialPort = wire.PortName + "-other";
|
||||
client.Open();
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(1, 2, 17));
|
||||
client.IP_SerialPort = "com1";
|
||||
client.IP_SerialPort = wire.PortName.ToLowerInvariant();
|
||||
client.Open();
|
||||
Assert.Null(client.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.Equal(2, wire.Writes.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReopenWithInterruptedFrameDiscardsTailBeforePollingOtherStation()
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public void ReopenWithInterruptedFrameDiscardsTailBeforePollingOtherStation(bool replaceClient)
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
var client = wire.Client;
|
||||
@ -183,6 +185,7 @@ public class ModbusRtuTimeoutTests
|
||||
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
|
||||
client.Close();
|
||||
wire.Receive(Old[3..]);
|
||||
if (replaceClient) client = wire.CreateClient();
|
||||
client.Open();
|
||||
wire.OnWrite = _ => wire.Receive(AtStation(Fresh, 18));
|
||||
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 18));
|
||||
@ -219,6 +222,65 @@ public class ModbusRtuTimeoutTests
|
||||
Assert.Single(wire.Writes);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReplacementClientDiscardsPreviousClientsLateRead()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
Assert.Null(wire.Client.ReadHoldingRegisters(1, 2, 17));
|
||||
wire.Client.Close();
|
||||
|
||||
var replacement = wire.CreateClient();
|
||||
replacement.IP_SerialPort = wire.PortName.ToLowerInvariant();
|
||||
replacement.Open();
|
||||
wire.OnWrite = _ => wire.Receive(Old);
|
||||
Assert.Null(replacement.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.False(replacement.Successful);
|
||||
Assert.Null(replacement.ReceiveData);
|
||||
Assert.Single(wire.Writes);
|
||||
|
||||
wire.OnWrite = _ => wire.Receive([.. Old, .. AtStation(Fresh, 18)]);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, replacement.ReadHoldingRegisters(20, 2, 18));
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, replacement.ReadHoldingRegisters(20, 2, 17));
|
||||
Assert.Equal(new byte[] { 17, 18, 17 }, wire.Writes.Select(frame => frame[0]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FailedReplacementOpenPreservesPendingWriteForNextClient()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
Assert.False(wire.Client.WriteSingleRegister(1, 7, 17));
|
||||
wire.Client.Close();
|
||||
var failed = wire.CreateClient(_ => throw new IOException("open failed"));
|
||||
failed.Open();
|
||||
Assert.False(failed.Connected);
|
||||
|
||||
var replacement = wire.CreateClient();
|
||||
replacement.Open();
|
||||
wire.OnWrite = _ => wire.Receive(wire.Writes[0]);
|
||||
Assert.False(replacement.WriteSingleRegister(1, 7, 17));
|
||||
Assert.Single(wire.Writes);
|
||||
wire.Receive(wire.Writes[0]);
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, replacement.ReadHoldingRegisters(20, 2, 17));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClosedClientCanRecoverOnlyAnUnownedPortAfterReset()
|
||||
{
|
||||
using var wire = new ScriptedPort();
|
||||
var replacement = wire.CreateClient();
|
||||
Assert.Null(wire.Client.ReadHoldingRegisters(1, 2, 17));
|
||||
replacement.Open();
|
||||
Assert.False(replacement.Connected);
|
||||
Assert.False(replacement.ReleaseResetStation(17));
|
||||
wire.Client.Close();
|
||||
Assert.True(replacement.ReleaseResetStation(17));
|
||||
replacement.Open();
|
||||
wire.OnWrite = _ => wire.Receive(Fresh);
|
||||
Assert.Equal(new ushort[] { 42, 259 }, replacement.ReadHoldingRegisters(20, 2, 17));
|
||||
}
|
||||
|
||||
private sealed class ScriptedPort : Stream
|
||||
{
|
||||
private readonly Queue<byte> _input = new();
|
||||
@ -226,10 +288,27 @@ public class ModbusRtuTimeoutTests
|
||||
internal List<byte[]> Writes { get; } = [];
|
||||
internal Action<int>? OnWrite;
|
||||
|
||||
internal string PortName { get; } = $"RTU-{Guid.NewGuid():N}";
|
||||
private readonly List<ModbusRtuClient> _clients = [];
|
||||
|
||||
internal ModbusRtuClient CreateClient(Func<string, RtuSession>? open = null)
|
||||
{
|
||||
var client = new ModbusRtuClient(open ?? (_ => new RtuSession(this, () => _input.Count, _input.Clear, 0)))
|
||||
{ IP_SerialPort = PortName };
|
||||
_clients.Add(client);
|
||||
return client;
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
foreach (var client in _clients) client.Close();
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
internal ScriptedPort()
|
||||
{
|
||||
Client = new ModbusRtuClient(_ => new RtuSession(this, () => _input.Count, _input.Clear, 0))
|
||||
{ IP_SerialPort = "COM1" };
|
||||
Client = CreateClient();
|
||||
Client.Open();
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user