104 lines
3.1 KiB
C#
104 lines
3.1 KiB
C#
using PLCCommunication.PLCType.Omron;
|
|||
|
|
using System;
|
||
|
|
using System.Threading.Tasks;
|
||
|
|
|
||
|
|
namespace WindowsService1
|
||
|
|
{
|
||
|
|
public class PLCWrapper
|
||
|
|
{
|
||
|
|
private OmronFinsNet _plc;
|
||
|
|
public bool _plcIsConnected;
|
||
|
|
private readonly string _ipAddress;
|
||
|
|
private readonly int _port;
|
||
|
|
private readonly int _maxReconnectAttempts;
|
||
|
|
private readonly int _reconnectDelay;
|
||
|
|
public PLCDataReader _dataReader;
|
||
|
|
public PLCWrapper(string ipAddress, int port, int maxReconnectAttempts = 3, int reconnectDelay = 5000)
|
||
|
|
{
|
||
|
|
_ipAddress = ipAddress;
|
||
|
|
_port = port;
|
||
|
|
_maxReconnectAttempts = maxReconnectAttempts;
|
||
|
|
_reconnectDelay = reconnectDelay;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<bool> ConnectAsync()
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
_plc = new OmronFinsNet
|
||
|
|
{
|
||
|
|
IpAddress = _ipAddress,
|
||
|
|
Port = _port
|
||
|
|
};
|
||
|
|
var connectResult = await Task.Run(() => _plc.ConnectServer());
|
||
|
|
_plcIsConnected = connectResult.IsSuccess;
|
||
|
|
if (_plcIsConnected)
|
||
|
|
{
|
||
|
|
_dataReader = new PLCDataReader(GetPLCClient());
|
||
|
|
Logger.WriteInfo("PLC连接成功");
|
||
|
|
}
|
||
|
|
else
|
||
|
|
{
|
||
|
|
Logger.WriteInfo("PLC连接失败");
|
||
|
|
}
|
||
|
|
return _plcIsConnected;
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
Logger.WriteError($"PLC连接失败: {ex.Message}");
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Disconnect()
|
||
|
|
{
|
||
|
|
if (_plcIsConnected)
|
||
|
|
{
|
||
|
|
_plc.ConnectClose();
|
||
|
|
_plcIsConnected = false;
|
||
|
|
Logger.WriteInfo("与PLC断开连接");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public OmronFinsNet GetPLCClient()
|
||
|
|
{
|
||
|
|
if (!_plcIsConnected || _plc == null)
|
||
|
|
{
|
||
|
|
throw new InvalidOperationException("PLC 未连接或未初始化。请先调用 ConnectAsync()。");
|
||
|
|
}
|
||
|
|
return _plc;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<bool> ReconnectAsync()
|
||
|
|
{
|
||
|
|
if (_plcIsConnected)
|
||
|
|
{
|
||
|
|
Logger.WriteInfo("PLC已连接,无需重连");
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
for (int attempt = 1; attempt <= _maxReconnectAttempts; attempt++)
|
||
|
|
{
|
||
|
|
Logger.WriteInfo($"尝试重新连接PLC,第 {attempt} 次尝试");
|
||
|
|
if (await ConnectAsync())
|
||
|
|
{
|
||
|
|
Logger.WriteInfo("PLC重新连接成功");
|
||
|
|
return true;
|
||
|
|
}
|
||
|
|
|
||
|
|
if (attempt < _maxReconnectAttempts)
|
||
|
|
{
|
||
|
|
await Task.Delay(_reconnectDelay);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Logger.WriteError($"PLC重新连接失败,已尝试 {_maxReconnectAttempts} 次");
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
public bool IsConnected()
|
||
|
|
{
|
||
|
|
return _plcIsConnected;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|