using System.IO; using System.Net; using System.Threading; namespace PLCSharp.VVMs.Connects.ModbusRtu { /// /// Modbus RTU 客户端 — 串口通信,继承 Connect /// public class ModbusRtuClient : Connect { /// /// FC_READ_HOLDING_REGISTERS /// public const byte FC_READ_HOLDING_REGISTERS = 0x03; /// /// FC_WRITE_SINGLE_REGISTER /// public const byte FC_WRITE_SINGLE_REGISTER = 0x06; /// /// FC_WRITE_MULTIPLE_REGISTERS /// public const byte FC_WRITE_MULTIPLE_REGISTERS = 0x10; private readonly object _lock = new(); private System.IO.Ports.SerialPort _port; /// 打开串口 public override void Open() { try { _port?.Close(); _port = new System.IO.Ports.SerialPort(IP_SerialPort, Params.BaudRate, Params.ParityValue, Params.DataBits, Params.StopBitsValue) { ReadTimeout = 5000, WriteTimeout = 2000 }; _port.Open(); Connected = true; Log($"串口 {IP_SerialPort} 已打开"); } catch (Exception ex) { Log($"打开串口失败: {ex.Message}"); Connected = false; } } /// /// 关闭 /// public override void Close() { try { _port?.Close(); } catch { } _port = null; Connected = false; } // ─── CRC16-Modbus ─── private static ushort CalcCrc(byte[] data, int offset, int count) { ushort crc = 0xFFFF; for (int i = 0; i < count; i++) { crc ^= data[offset + i]; for (int j = 0; j < 8; j++) { if ((crc & 0x0001) != 0) crc = (ushort)((crc >> 1) ^ 0xA001); else crc >>= 1; } } return crc; } // ─── 构建 RTU 帧 ─── private static byte[] BuildRequest(byte unitId, byte functionCode, byte[] data) { byte[] frame = new byte[1 + 1 + data.Length + 2]; frame[0] = unitId; frame[1] = functionCode; Array.Copy(data, 0, frame, 2, data.Length); ushort crc = CalcCrc(frame, 0, frame.Length - 2); frame[^2] = (byte)(crc & 0xFF); frame[^1] = (byte)((crc >> 8) & 0xFF); return frame; } // ─── 读写串口 ─── // 保留响应的线上布局供 CRC 校验及 ReceiveData 使用。 internal static byte[] ReadResponse(Stream stream, byte unitId, byte functionCode, ReadOnlySpan requestData) { byte[] head = new byte[2]; stream.ReadExactly(head); if (head[0] != unitId || (head[1] != functionCode && head[1] != (functionCode | 0x80))) throw new InvalidDataException("ModbusRTU 应答站号或功能码与请求不匹配"); bool isError = (head[1] & 0x80) != 0; bool hasByteCount = functionCode == FC_READ_HOLDING_REGISTERS && !isError; int count = hasByteCount ? stream.ReadByte() : isError ? 1 : 4; if (count < 0) throw new EndOfStreamException(); byte[] data = new byte[count]; stream.ReadExactly(data); byte[] response = hasByteCount ? [.. head, (byte)count, .. data] : [.. head, .. data]; Span crc = stackalloc byte[2]; stream.ReadExactly(crc); if (CalcCrc(response, 0, response.Length) != (crc[0] | crc[1] << 8)) throw new InvalidDataException("ModbusRTU: CRC 校验失败"); ModbusResponse.ValidatePdu(functionCode, requestData, response.AsSpan(1)); return response; } private byte[] Execute(byte unitId, byte functionCode, byte[] requestData) { lock (_lock) { Successful = false; ReceiveData = null; if (_port == null || !_port.IsOpen) { Log("ModbusRTU: 串口未打开"); return null; } try { // 清空接收缓冲区,避免残留数据污染本次读取 _port.DiscardInBuffer(); byte[] request = BuildRequest(unitId, functionCode, requestData); _port.Write(request, 0, request.Length); Log($"ModbusTx [{BitConverter.ToString(request).Replace("-", " ")}]"); // 等待响应:按波特率计算 3.5 字符时间 + 50ms 从机处理余量 double charMs = 1000.0 / Params.BaudRate * 10; // 8N1 = 10 bits/char int waitMs = (int)Math.Ceiling(3.5 * charMs) + 50; if (waitMs < 20) waitMs = 20; Thread.Sleep(waitMs); byte[] response = ReadResponse(_port.BaseStream, unitId, functionCode, requestData); Log($"ModbusRx [{BitConverter.ToString(response).Replace("-", " ")}]"); if ((response[1] & 0x80) != 0) { Log($"ModbusRTU 异常: func=0x{response[1] & 0x7F:X2} code={response[2]}"); return null; } ReceiveData = response; Successful = true; return response; } catch (InvalidDataException ex) { Log(ex.Message); return null; } catch (TimeoutException) { Log("ModbusRTU: 读取超时"); _port?.DiscardInBuffer(); return null; } catch (IOException) { Log("ModbusRTU: IO 错误"); _port?.DiscardInBuffer(); return null; } catch (Exception ex) { Log($"ModbusRTU 异常: {ex.Message}"); _port?.DiscardInBuffer(); Connected = false; return null; } } } // ─── 公开 API ─── /// /// 读取HoldingRegisters /// /// 启动Address /// 数量 /// unitId /// 返回结果 public ushort[] ReadHoldingRegisters(ushort startAddress, ushort count, byte? unitId = null) { byte uid = unitId ?? Params.UnitId; byte[] data = new byte[4]; Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)startAddress)), 0, data, 0, 2); Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)count)), 0, data, 2, 2); byte[] response = Execute(uid, FC_READ_HOLDING_REGISTERS, data); if (response == null || response.Length < 3) return null; // response = [addr, FC, byteCount, data...] ushort[] registers = new ushort[count]; for (int i = 0; i < count; i++) { int offset = 3 + i * 2; registers[i] = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, offset)); } return registers; } /// /// 写入Single注册 /// /// address /// 值 /// unitId /// 返回布尔值 public bool WriteSingleRegister(ushort address, ushort value, byte? unitId = null) { byte uid = unitId ?? Params.UnitId; byte[] data = new byte[4]; Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)address)), 0, data, 0, 2); Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)value)), 0, data, 2, 2); return Execute(uid, FC_WRITE_SINGLE_REGISTER, data) != null; } /// /// 写入MultipleRegisters /// /// 启动Address /// values /// unitId /// 返回布尔值 public bool WriteMultipleRegisters(ushort startAddress, ushort[] values, byte? unitId = null) { byte uid = unitId ?? Params.UnitId; int byteCount = values.Length * 2; byte[] data = new byte[5 + byteCount]; Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)startAddress)), 0, data, 0, 2); Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)values.Length)), 0, data, 2, 2); data[4] = (byte)byteCount; for (int i = 0; i < values.Length; i++) Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)values[i])), 0, data, 5 + i * 2, 2); return Execute(uid, FC_WRITE_MULTIPLE_REGISTERS, data) != null; } } }