添加配置连接窗口已经相关S7与ModbusTCP连接功能

This commit is contained in:
20492
2026-06-12 08:38:43 +08:00
parent 5d14afcb66
commit 1ff51cbc45
13 changed files with 1785 additions and 105 deletions

View File

@@ -1,4 +1,4 @@
using NModbus;
using NModbus;
using System;
using System.Net;
using System.Net.Sockets;
@@ -38,20 +38,48 @@ namespace DeviceCommand.Base
await _commLock.WaitAsync(ct);
try
{
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 开始连接 - IP: {IPAddress}, 端口: {Port}");
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 超时设置 - 发送: {SendTimeout}ms, 接收: {ReceiveTimeout}ms");
if (_tcpClient.Connected)
{
var remoteEndPoint = (IPEndPoint)_tcpClient.Client.RemoteEndPoint!;
if (remoteEndPoint.Address.MapToIPv4().ToString() == IPAddress && remoteEndPoint.Port == Port)
string currentIp = remoteEndPoint.Address.MapToIPv4().ToString();
int currentPort = remoteEndPoint.Port;
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 已有连接: {currentIp}:{currentPort}");
if (currentIp == IPAddress && currentPort == Port)
{
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 参数匹配,复用现有连接");
return true;
}
else
{
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 参数不匹配,需要重新连接");
}
}
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 关闭并释放旧连接");
_tcpClient.Close();
_tcpClient.Dispose();
_tcpClient = new TcpClient();
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 调用 ConnectAsync({IPAddress}, {Port})");
await _tcpClient.ConnectAsync(IPAddress, Port, ct);
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 创建ModbusMaster");
Modbus = new ModbusFactory().CreateMaster(_tcpClient);
return true;
bool isConnected = _tcpClient.Connected;
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 连接结果: {(isConnected ? "" : "")}");
return isConnected;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 连接异常: {ex.Message}");
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 异常类型: {ex.GetType().Name}");
System.Diagnostics.Debug.WriteLine($"[ModbusTcp] 异常堆栈: {ex.StackTrace}");
return false;
}
finally
{