diff --git a/PLCSharpWpf/VVMs/Connects/ModbusRtu/RtuSession.cs b/PLCSharpWpf/VVMs/Connects/ModbusRtu/RtuSession.cs index cd798e0..56c399b 100644 --- a/PLCSharpWpf/VVMs/Connects/ModbusRtu/RtuSession.cs +++ b/PLCSharpWpf/VVMs/Connects/ModbusRtu/RtuSession.cs @@ -6,42 +6,92 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu; internal sealed class RtuSession(Stream stream, Func bytesAvailable, Action discardInput, int frameGapMs) { // Execute、Open 和 Close 由客户端的同一把锁串行化。 - private RtuResponseReader _lateReply; + private readonly Dictionary _pending = []; + private RtuResponseReader _partial; internal byte[] Exchange(byte[] request, Action log) { - if (_lateReply != null) + byte unit = request[0]; + if (_pending.Count > 0) { - // 轮询只消费目前可读的字节;从站一直不应答时不阻塞其他串口的轮询。 - try - { - if (_lateReply.Read(stream, bytesAvailable()) == null) return null; - } - catch (InvalidDataException ex) - { - throw new IOException("迟到帧无法与超时请求匹配,请确认从站已空闲后重新打开串口", ex); - } - _lateReply = null; - log("ModbusRTU: 已丢弃上一笔请求的迟到应答"); + DrainBuffered(log); + if (_pending.ContainsKey(unit)) return null; + + // 另一站的残帧不能占住总线。等候帧间隔,若仍在接收则留待下次轮询。 Thread.Sleep(frameGapMs); + if (bytesAvailable() > 0) + { + DrainBuffered(log); + return null; + } + _partial = null; // 仅丢弃残帧进度,原站仍在 _pending 中 + } + else + { + discardInput(); } - discardInput(); - var reply = new RtuResponseReader(request[0], request[1], request[2..^2]); + var reply = new RtuResponseReader(unit, request[1], request[2..^2]); try { stream.Write(request); log($"ModbusTx [{BitConverter.ToString(request).Replace("-", " ")}]"); Thread.Sleep(frameGapMs + 50); - return reply.Read(stream, int.MaxValue); + int budget = int.MaxValue; + return ReadFrames(reply, ref budget, log); } catch (TimeoutException) { - // 写超时也可能已经送达从站;此处不重发命令。 - _lateReply = reply; + _pending[unit] = reply; throw; } } + + private void DrainBuffered(Action log) + { + int available = bytesAvailable(); + ReadFrames(null, ref available, log); + } + + private byte[] ReadFrames(RtuResponseReader current, ref int budget, Action log) + { + while (budget > 0) + { + if (_partial == null) + { + int unit = stream.ReadByte(); + if (unit < 0) throw new EndOfStreamException(); + budget--; + if (current?.UnitId == unit) + _partial = current; + else if (!_pending.TryGetValue((byte)unit, out _partial)) + throw new InvalidDataException($"ModbusRTU: 收到非预期站号 {unit}"); + _partial.BeginFrame(); + } + + var reader = _partial; + byte[] frame; + try + { + frame = reader.Read(stream, ref budget); + } + catch (InvalidDataException ex) when (reader != current) + { + throw new IOException($"站 {reader.UnitId} 迟到帧校验失败", ex); + } + catch (InvalidDataException) + { + _partial = null; + throw; + } + if (frame == null) return null; + _partial = null; + if (reader == current) return frame; + _pending.Remove(reader.UnitId); + log($"ModbusRTU: 已丢弃站 {reader.UnitId} 的迟到应答"); + } + return null; + } } // TimeoutException 可能发生在帧内任何位置。每次底层 Read 成功就保存进度。 @@ -50,7 +100,17 @@ internal sealed class RtuResponseReader(byte unitId, byte functionCode, byte[] r private readonly byte[] _frame = new byte[256]; private int _received; - internal byte[] Read(Stream stream, int budget) + internal byte UnitId => unitId; + + internal void BeginFrame() + { + _frame[0] = unitId; + _received = 1; + } + + internal byte[] Read(Stream stream, int budget) => Read(stream, ref budget); + + internal byte[] Read(Stream stream, ref int budget) { if (!ReadUntil(stream, 2, ref budget)) return null; bool isError = _frame[1] == (functionCode | 0x80); diff --git a/Tests/PLCSharp.Tests/ModbusRtuTimeoutTests.cs b/Tests/PLCSharp.Tests/ModbusRtuTimeoutTests.cs index ab4284b..b2bb5f2 100644 --- a/Tests/PLCSharp.Tests/ModbusRtuTimeoutTests.cs +++ b/Tests/PLCSharp.Tests/ModbusRtuTimeoutTests.cs @@ -99,6 +99,46 @@ public class ModbusRtuTimeoutTests Assert.Equal(new ushort[] { 42, 259 }, wire.Client.ReadHoldingRegisters(20, 2, 17)); } + private static byte[] AtStation(byte[] frame, byte station) + { + var copy = frame.ToArray(); + copy[0] = station; + ushort crc = ModbusRtuClient.CalcCrc(copy, 0, copy.Length - 2); + copy[^2] = (byte)crc; + copy[^1] = (byte)(crc >> 8); + return copy; + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(5)] + public void SilentStationDoesNotStopHealthyStation(int prefixLength) + { + using var wire = new ScriptedPort(); + wire.OnWrite = n => wire.Receive(n == 1 ? Old[..prefixLength] : AtStation(Fresh, 18)); + Assert.Null(wire.Client.ReadHoldingRegisters(1, 2, 17)); + for (int i = 0; i < 3; i++) + { + Assert.Null(wire.Client.ReadHoldingRegisters(1, 2, 17)); + Assert.Equal(new ushort[] { 42, 259 }, wire.Client.ReadHoldingRegisters(1, 2, 18)); + } + Assert.Equal(new byte[] { 17, 18, 18, 18 }, wire.Writes.Select(r => r[0])); + } + + [Fact] + public void MultipleLateRepliesAreRoutedDuringHealthyExchange() + { + using var wire = new ScriptedPort(); + Assert.Null(wire.Client.ReadHoldingRegisters(1, 2, 17)); + Assert.Null(wire.Client.ReadHoldingRegisters(1, 2, 18)); + wire.OnWrite = _ => wire.Receive([.. AtStation(Old, 18), .. Old, .. AtStation(Fresh, 19)]); + Assert.Equal(new ushort[] { 42, 259 }, wire.Client.ReadHoldingRegisters(1, 2, 19)); + wire.OnWrite = _ => wire.Receive(Fresh); + Assert.Equal(new ushort[] { 42, 259 }, wire.Client.ReadHoldingRegisters(1, 2, 17)); + Assert.Equal(new byte[] { 17, 18, 19, 17 }, wire.Writes.Select(r => r[0])); + } + private sealed class ScriptedPort : Stream { private readonly Queue _input = new();