Implement failure resilient TCP connections for Adam and AMPT

This commit is contained in:
ig 2023-03-09 13:16:26 +01:00
parent f1394e4755
commit eb73beb1cd
2 changed files with 67 additions and 24 deletions

View File

@ -27,30 +27,42 @@ public class AmptCommunicationUnit
{
try
{
var modbus = OpenConnection();
return TryReadStatus(modbus);
OpenConnection();
return TryReadStatus();
}
catch
{
Modbus?.CloseConnection();
CloseConnection();
return null;
}
}
private ModbusTcpClient OpenConnection()
private void CloseConnection()
{
try
{
Modbus?.CloseConnection();
}
catch
{
// ignored
}
Modbus = null;
}
private void OpenConnection()
{
if (Modbus is null)
{
var connection = new ModbusTcpConnection(Hostname, Port);
Modbus = new ModbusTcpClient(connection, SlaveAddress);
}
return Modbus;
}
private static AmptCommunicationUnitStatus TryReadStatus(ModbusTcpClient modbus)
private AmptCommunicationUnitStatus TryReadStatus()
{
var r = modbus.ReadHoldingRegisters(1, 116);
var r = Modbus!.ReadHoldingRegisters(1, 116);
var currentFactor = Pow(10.0m, r.GetInt16(73));
var voltageFactor = Pow(10.0m, r.GetInt16(74));

View File

@ -7,31 +7,60 @@ namespace InnovEnergy.Lib.Devices.Adam6060;
public class Adam6060Device
{
private ModbusTcpClient Modbus { get; }
public String Hostname { get; }
public UInt16 Port { get; }
public Byte SlaveAddress { get; }
private ModbusTcpClient? Modbus { get; set; }
public Adam6060Device(String hostname, UInt16 port = 5004, Byte slaveAddress = 2)
{
var connection = new ModbusTcpConnection(hostname, port);
Modbus = new ModbusTcpClient(connection, slaveAddress);
Hostname = hostname;
Port = port;
SlaveAddress = slaveAddress;
}
private void OpenConnection()
{
if (Modbus is null)
{
var connection = new ModbusTcpConnection(Hostname, Port);
Modbus = new ModbusTcpClient(connection, SlaveAddress);
}
}
public Adam6060Status? ReadStatus()
{
try
{
OpenConnection();
return TryReadStatus();
}
catch (Exception)
catch
{
Modbus.CloseConnection();
CloseConnection();
return null;
}
}
private void CloseConnection()
{
try
{
Modbus?.CloseConnection();
}
catch
{
// ignored
}
Modbus = null;
}
private Adam6060Status TryReadStatus()
{
var inputs = Modbus.ReadDiscreteInputs(DigitalInputsStartRegister, NbDigitalInputs);
var relays = Modbus.ReadDiscreteInputs(RelaysStartRegister, NbRelays);
var inputs = Modbus!.ReadDiscreteInputs(DigitalInputsStartRegister, NbDigitalInputs);
var relays = Modbus!.ReadDiscreteInputs(RelaysStartRegister, NbRelays);
return new Adam6060Status
{
@ -55,7 +84,9 @@ public class Adam6060Device
{
try
{
Modbus.WriteMultipleCoils(RelaysStartRegister, control.Relay0,
OpenConnection();
Modbus!.WriteMultipleCoils(RelaysStartRegister, control.Relay0,
control.Relay1,
control.Relay2,
control.Relay3,
@ -63,9 +94,9 @@ public class Adam6060Device
control.Relay5);
return true;
}
catch (Exception)
catch
{
Modbus.CloseConnection();
CloseConnection();
return false;
}
}