Innovenergy_trunk/csharp/Lib/Devices/Adam6060/Adam6060Device.cs

103 lines
2.7 KiB
C#

using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Connections;
using static InnovEnergy.Lib.Devices.Adam6060.Adam6060Status;
using static InnovEnergy.Lib.Devices.Adam6060.Adam6060Control;
namespace InnovEnergy.Lib.Devices.Adam6060;
public class Adam6060Device
{
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)
{
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
{
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);
return new Adam6060Status
{
DigitalInput0 = inputs[0],
DigitalInput1 = inputs[1],
DigitalInput2 = inputs[2],
DigitalInput3 = inputs[3],
DigitalInput4 = inputs[4],
DigitalInput5 = inputs[5],
Relay0 = relays[0],
Relay1 = relays[1],
Relay2 = relays[2],
Relay3 = relays[3],
Relay4 = relays[4],
Relay5 = relays[5],
};
}
public Boolean WriteControl(Adam6060Control control)
{
try
{
OpenConnection();
Modbus!.WriteMultipleCoils(RelaysStartRegister, control.Relay0,
control.Relay1,
control.Relay2,
control.Relay3,
control.Relay4,
control.Relay5);
return true;
}
catch
{
CloseConnection();
return false;
}
}
}