This commit is contained in:
xyy
2026-02-27 16:58:02 +08:00
parent 82abc41dbc
commit 63c81b48a1
9 changed files with 237 additions and 3 deletions

View File

@@ -0,0 +1,65 @@
using System;
using System.Net.Sockets;
using System.Threading.Tasks;
using Modbus.Device;
namespace MembranePoreTester.Communication
{
public class ModbusTcpPlcService : IPlcService, IDisposable
{
private readonly PlcConfiguration _config;
private TcpClient _tcpClient;
private IModbusMaster _master;
public ModbusTcpPlcService(PlcConfiguration config)
{
_config = config;
}
private async Task EnsureConnectedAsync()
{
if (_tcpClient == null || !_tcpClient.Connected)
{
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(_config.IpAddress, _config.Port);
_master = ModbusIpMaster.CreateIp(_tcpClient);
}
}
// 读取两个连续的保持寄存器转换为32位浮点数假设大端模式
private async Task<float> ReadFloatAsync(ushort startAddress)
{
await EnsureConnectedAsync();
// 读取两个寄存器(从站地址由配置指定)
ushort[] registers = await _master.ReadHoldingRegistersAsync(_config.SlaveId, startAddress, 2);
// 将两个16位寄存器合并为32位浮点数大端
byte[] bytes = new byte[4];
bytes[0] = (byte)(registers[0] >> 8);
bytes[1] = (byte)(registers[0] & 0xFF);
bytes[2] = (byte)(registers[1] >> 8);
bytes[3] = (byte)(registers[1] & 0xFF);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes); // 如果系统是小端,需要反转字节顺序
return BitConverter.ToSingle(bytes, 0);
}
public async Task<float> ReadPressureAsync() =>
await ReadFloatAsync(_config.PressureRegister) * (float)_config.PressureFactor;
public async Task<float> ReadWetFlowAsync() =>
await ReadFloatAsync(_config.WetFlowRegister) * (float)_config.WetFlowFactor;
public async Task<float> ReadDryFlowAsync() =>
await ReadFloatAsync(_config.DryFlowRegister) * (float)_config.DryFlowFactor;
public void Dispose()
{
_master?.Dispose();
_tcpClient?.Close();
}
}
}