165 lines
5.6 KiB
C#
165 lines
5.6 KiB
C#
using System.IO;
|
|
using System.Threading;
|
|
|
|
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 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)
|
|
{
|
|
DrainBuffered(log);
|
|
if (Pending.ContainsKey(unit)) return null;
|
|
|
|
// 另一站的残帧不能占住总线。等候帧间隔,若仍在接收则留待下次轮询。
|
|
Thread.Sleep(frameGapMs);
|
|
if (bytesAvailable() > 0)
|
|
{
|
|
DrainBuffered(log);
|
|
return null;
|
|
}
|
|
_partial = null; // 仅丢弃残帧进度,原站仍在 Pending 中
|
|
}
|
|
else
|
|
{
|
|
discardInput();
|
|
}
|
|
|
|
var reply = new RtuResponseReader(unit, request[1], request[2..^2]);
|
|
try
|
|
{
|
|
stream.Write(request);
|
|
log($"ModbusTx [{BitConverter.ToString(request).Replace("-", " ")}]");
|
|
Thread.Sleep(frameGapMs + 50);
|
|
int budget = int.MaxValue;
|
|
return ReadFrames(reply, ref budget, log);
|
|
}
|
|
catch (Exception ex) when (ex is TimeoutException or IOException or InvalidDataException)
|
|
{
|
|
Pending[unit] = reply;
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private void DrainBuffered(Action<string> log)
|
|
{
|
|
int available = bytesAvailable();
|
|
ReadFrames(null, ref available, log);
|
|
}
|
|
|
|
private byte[] ReadFrames(RtuResponseReader current, ref int budget, Action<string> 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 成功就保存进度。
|
|
internal sealed class RtuResponseReader(byte unitId, byte functionCode, byte[] requestData)
|
|
{
|
|
private readonly byte[] _frame = new byte[256];
|
|
private int _received;
|
|
|
|
internal byte UnitId => unitId;
|
|
internal bool HasReceivedBytes => _received > 0;
|
|
|
|
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);
|
|
if (_frame[0] != unitId || (_frame[1] != functionCode && !isError))
|
|
throw new InvalidDataException("ModbusRTU 应答站号或功能码与请求不匹配");
|
|
|
|
int length = isError ? 5 : 8;
|
|
if (!isError && functionCode == ModbusRtuClient.FC_READ_HOLDING_REGISTERS)
|
|
{
|
|
if (!ReadUntil(stream, 3, ref budget)) return null;
|
|
length = 5 + _frame[2];
|
|
if (length > _frame.Length) throw new InvalidDataException("ModbusRTU 应答过长");
|
|
}
|
|
|
|
if (!ReadUntil(stream, length, ref budget)) return null;
|
|
int end = length - 2;
|
|
if (ModbusRtuClient.CalcCrc(_frame, 0, end) != (_frame[end] | _frame[end + 1] << 8))
|
|
throw new InvalidDataException("ModbusRTU: CRC 校验失败");
|
|
ModbusResponse.ValidatePdu(functionCode, requestData, _frame.AsSpan(1, end - 1));
|
|
return _frame[..end];
|
|
}
|
|
|
|
private bool ReadUntil(Stream stream, int end, ref int budget)
|
|
{
|
|
while (_received < end && budget > 0)
|
|
{
|
|
int n = stream.Read(_frame, _received, Math.Min(end - _received, budget));
|
|
if (n == 0) throw new EndOfStreamException();
|
|
_received += n;
|
|
budget -= n;
|
|
}
|
|
return _received >= end;
|
|
}
|
|
}
|